Browse Chunks
Showing 5251-5300 of 7392 chunks
Creates a configurable mock callable whose return_value attribute determines what the mock returns each time it is invoked. Addresses the need to stub dependencies with deterministic outputs during unit testing. Reached for whenever a test requires a collaborator to produce a known, repeatable value without executing real logic.
MagicMock(return_value=value)
Verifies that a mock object was called exactly once with the specified positional and keyword arguments. Addresses the need to assert both call count and argument values in a single check, rather than verifying them separately. Triggered when writing unit tests that must confirm a dependency was invoked precisely once with the expected data.
mock_func.assert_called_once_with(*args, **kwargs)
Replaces a method on a class with a mock that raises a specified exception when called. This addresses the need to test error handling paths and resilience to failures in dependent components. It is triggered when a test needs to verify behavior under failure conditions without altering the source code of the dependency.
with patch.object(target_class, method_name, side_effect=exception_type):
Temporarily patches environment variables inside a with block using unittest.mock.patch.dict, restoring original values when the block exits. It solves test pollution where modifying os.environ directly would leak state between tests. Reach for this whenever a test or debug session needs a controlled environment without side effects persisting afterward.
with patch.dict(os.environ, {env_var: value}): body
Temporarily replaces a specified attribute with a mock object for the duration of the with block, automatically restoring the original attribute afterward. Used in unit tests to isolate the code under test from its dependencies.
with patch(target, autospec=True) as mock_var:
Patches multiple attributes on a single module simultaneously inside a context manager, allowing each patch to be configured independently—some as default autospecced mocks, others with custom behaviors like side effects. Addresses the pain point of deeply nested with-statements when a unit under test depends on several collaborators in the same module. Reached for when more than one function or object in a module must be replaced for a test.
with patch.multiple(module, target_a=DEFAULT, target_b=MagicMock(side_effect=exception)) as mocks:
This chunk asserts that a mock object received the expected call arguments. It addresses the pain point of unverified interactions in unit tests, which can lead to tests passing despite incorrect behavior. You reach for this when you need to confirm that a function under test called a mocked dependency with specific arguments.
assert mock.call_args == call(positional_args, keyword_args)
Stops all currently active patches started by unittest.mock.patch.start(), restoring every patched object to its original state. Addresses the pain point of mock state leaking between tests, which causes unpredictable test failures and order-dependent test behavior. Triggered when multiple patches were started manually via .start() and you need a single call to clean them all up in teardown.
patch.stopall()
Creates a mock object that auto-generates attributes and methods on access, serving as a configurable test double. Addresses the need to isolate units under test from their real dependencies without implementing actual behavior. Triggered when writing unit tests that require a stand-in for a collaborator or external service.
mock = MagicMock()
Usage of unittest.mock.patch as a context manager to temporarily replace my_module.ExternalService with a mock object named MockService for testing.
with patch('module.Class') as Alias:
Uses Python's three-argument type() call to dynamically construct a class with stub methods, then immediately instantiates it into an object. It eliminates the boilerplate of defining a full class when all you need is a lightweight test double that accepts method calls without real behavior. You reach for it during unit testing when a dependency must satisfy an interface but no actual logic is required.
type('classname', (), {'methodname': lambda self, arg: None})()
Creates an anonymous function restricted to a single expression, which is evaluated and returned when the function is called. Addresses the boilerplate of defining a named def block for trivial one-line logic. Reached for when a short, inline callable is needed as an argument to a higher-order function such as map, filter, or sorted.
lambda parameters: expression
Creates a simple mock cache object with get and set methods that do nothing and return None, serving as a test double or placeholder.
type(class_name, (), {'method_name': lambda self, *args: default_return})
Creates a mock object whose return value is computed dynamically from its input arguments via a lambda function. Addresses the limitation of return_value, which always returns the same value regardless of call arguments. Reached for when the code under test passes varying arguments to a dependency and the test must produce context-dependent responses.
Mock(side_effect=lambda x: expression)
Temporarily replaces a named method or attribute on a specific object with a Mock that returns a fixed value, automatically restoring the original when the with-block exits. It solves the problem of testing code that depends on expensive, nondeterministic, or unavailable collaborators. You reach for it when you need to isolate a unit under test by controlling what a dependency returns without permanently modifying the object.
with patch.object(target, attribute, return_value=value) as mock_handle:
Temporarily replaces multiple attributes in a target module with Mock objects during the execution of the with block. It addresses the pain point of isolating code under test from multiple external dependencies simultaneously, triggering when a test requires overriding several functions or classes in the same module at once.
with patch.multiple(module, func1=Mock(return_value=value), func2=Mock(side_effect=exception)):
Creates a strict mock object that enforces the spec of ExternalService, allowing attribute access only on defined attributes and returning a mock instance.
create_autospec(Class, spec_set=True, instance=True)
Creates a mock object that replaces time.sleep in the specified module with a no-op that returns None, allowing tests to run without real delays.
patch('target.attribute', return_value=None) assigned to a variable (often named patcher).
Assigns a sentinel object from the sentinel module to a variable for use as a unique default value.
{variable} = {module}.{attribute}
Imports the `given` decorator and the `strategies` module (aliased as `st`) from the `hypothesis` library for property‑based testing.
from hypothesis import given, strategies as st
A hypothesis decorator that supplies two arbitrary integer arguments to a test function for property-based testing.
@given(st.<strategy1>(), st.<strategy2>()) where each strategy returns a value for a test function parameter.
Asserts that addition is commutative for the given operands.
def test_<name>(<parameter_list>): assert <expression>
Asserts that applying string reversal twice yields the original string, demonstrating that the reversal operation is an involution.
def test_<name>(s): assert s[::-1][::-1] == s
Tests the distributive property of multiplication over addition for integers using hypothesis property-based testing.
@given(st.integers(), st.integers()) def test_mul_distributive(a, b): assert a * (b + 1) == a*b + a
Tests that the floating-point multiplicative inverse of a non-zero integer approximates one within floating-point tolerance, expressing the inverse property under rounding error.
@given(st.integers()) def test_<name>(x): assume(x != 0); assert math.isclose(1/x * x, 1)
Generates arbitrary tuples of two integers for property-based testing using the Hypothesis library.
@given(st.tuples(X, Y)) where X and Y are hypothesis strategies; here X=st.integers(), Y=st.integers()
Defines a test function named test_addition that will be automatically discovered by test runners to verify the correctness of an addition operation. This addresses the need for automated regression testing, preventing manual verification errors. It is typically reached for when practicing test-driven development or when adding new functionality that requires validation.
def function_name():
The assert statement tests a boolean condition; if the condition is false, it raises an AssertionError with an optional message.
assert condition[, message]
Temporarily replaces a function or object with a mock during a with block, allowing you to isolate code under test and verify interactions.
with mock.patch(';') as ;:
Defines a parametrized test case in pytest, providing input-output pairs for a test function.
@pytest.mark.parametrize('<arg_names>', [<tuple_of_values>])
Asserts that a specific exception is raised within the indented block; the test passes if the exception is raised, fails otherwise.
with pytest.raises(ExceptionType):
Asserts that a mock object has been called a specific number of times, typically used in unit tests to verify interaction counts.
assert mock.call_count == ;
A pytest fixture that provides a simple dictionary sample for use in tests. It can be injected into test functions to supply consistent test data.
@pytest.fixture def ;: return ;
Asserts that the result of 0.1 + 0.2 is approximately equal to 0.3, accounting for floating-point representation error.
assert pytest.approx(<expression>) == <expected_value> where <expression> is any numeric expression and <expected_value> is the anticipated numeric result.
Defines a test case class that inherits from unittest.TestCase, enabling the use of unittest's test discovery, setup/teardown hooks, and assertion methods for unit testing.
class <ClassName>(unittest.TestCase):
Defines a test method named test_addition intended to verify the addition operation within a unittest.TestCase subclass.
def test_<method_name>(self): where <method_name> starts with 'test_' and describes the behavior under test.
Asserts that two values are equal using unittest's assertEqual method.
self.assertEqual(arg1, arg2)
The with self.assertRaises(ValueError): int('invalid') statement executes int('invalid') inside a context manager that expects a ValueError to be raised; if the exception is raised, the test passes, otherwise it fails. It provides a concise way to verify that specific invalid inputs trigger the expected exception, avoiding boilerplate try/except blocks in unit tests. Used when writing test cases to confirm that a function or expression raises a particular exception under erroneous conditions.
with self.assertRaises(exception_type): callable()
A unittest decorator that skips a test when a feature flag evaluates to False, preventing test failures when the feature is unavailable.
@unittest.skipIf(not <FEATURE_FLAG>, '<MESSAGE>')
Creates a subtest context for iterative test cases, labeling each iteration with the given identifier for granular test reporting.
with self.subTest(<parameter>=<value>):
Registers a cleanup function to clean up a temporary directory after a test.
self.addCleanup(callable)
Defines a test function named test_true_is_true that asserts the boolean True is equal to True, serving as a trivial sanity check in a test suite.
def test_<description>():
Used to assert that a condition is true during development; raises an AssertionError if the condition is false. It helps catch programming errors early and documents assumptions that must hold at that point in the code.
assert ;
Verifies that a floating-point computation is approximately equal to an expected value within a tolerance, using pytest's approx helper. This avoids false test failures due to floating-point rounding errors.
assert ; == pytest.approx(;)
The `with pytest.raises(TypeError):` context manager asserts that the code block inside raises a TypeError exception; if the block does not raise the expected exception, the test fails.
with pytest.raises(;):
A pytest decorator that generates multiple test cases from a single test function by supplying tuples of argument values.
@pytest.mark.parametrize('param1,param2,...', [(val1,val2,...), ...])
Defines a test case for an addition function, specifying inputs x and y and the expected result.
def test_<name>(param1, param2, expected):
An assert statement that checks whether the function add(x, y) returns the expected value, used as a simple assertion or test assertion.
assert <function_call>(<arg1>, <arg2>) == <expected>
The `with tmpdir as d:` statement creates a temporary directory context using the pytest `tmpdir` fixture, binding the directory path (as a py.path.local object) to the variable `d` for the duration of the block. It eliminates the need for manual cleanup, ensuring that the temporary directory and its contents are automatically removed after the block exits, even if an exception occurs. Use this pattern when a test or script requires an isolated scratch space that must not leave residual files after execution.
with resource as alias:
Replaces a method of a class with a lambda that returns a constant value, typically used in testing to stub dependencies.
monkeypatch.setattr('<target>', lambda self: <constant>)