Browse Chunks

Showing 5251-5300 of 7392 chunks

mock = MagicMock
CAT_8

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)

mock_func.assert_called_once_with
CAT_8

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)

with patch.object(MyClass, 'compute', side_effect=ValueError):
CAT_8

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):

with patch.dict(os.environ, {'DEBUG': '1'}):
CAT_8

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

with patch('module.submodule.ClassName', autospec=True) as MockClass:
CAT_8

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:

with patch.multiple('my_module', func_a=DEFAULT, func_b=MagicMock(side_effect=RuntimeError)) as mocks:
CAT_8

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:

assert mock_func.call_args == call
CAT_8

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)

patch.stopall()
CAT_8

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()

mock = MagicMock()
CAT_8

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()

with patch('my_module.ExternalService') as MockService:
CAT_8

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:

fake_repo = type('FakeRepo', (), {'save': lambda self, item: None})()
CAT_8

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})()

stub = lambda x: x * 2
CAT_8

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

fake_cache = type('FakeCache', (), {'get': lambda self, key: None, 'set': lambda self, key, value: None})()
CAT_8

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})

mock_func = Mock
CAT_8

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)

with patch.object(my_obj, 'compute', return_value=10) as mock_compute:
CAT_8

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:

with patch.multiple('my_module', func1=Mock(return_value=1), func2=Mock(side_effect=ValueError())):
CAT_8

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)):

mock_obj = create_autospec
CAT_8

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)

patcher = patch
CAT_8

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).

sentinel_obj = sentinel.MY_DEPENDENCY
CAT_8

Assigns a sentinel object from the sentinel module to a variable for use as a unique default value.

{variable} = {module}.{attribute}

from hypothesis import given, strategies as st
CAT_8

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

@given(st.integers(), st.integers())
CAT_8

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.

def test_add_commutative(a, b): assert a b == b a
CAT_8

Asserts that addition is commutative for the given operands.

def test_<name>(<parameter_list>): assert <expression>

def test_reverse_is_involutive(s): assert s; == s
CAT_8

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

@given(st.integers(), st.integers()) def test_mul_distributive(a, b): assert a * (b + 1) == a*b + a
CAT_8

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

@given(st.integers()) def test_nonzero_inverse(x): assume(x != 0); assert math.isclose(1/x * x, 1)
CAT_8

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)

@given(st.tuples(st.integers(), st.integers()))
CAT_8

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()

def test_addition():
CAT_8

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():

assert
CAT_8

The assert statement tests a boolean condition; if the condition is false, it raises an AssertionError with an optional message.

assert condition[, message]

with mock.patch('module.func') as m:
CAT_8

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 ;:

@pytest.mark.parametrize('x,expected'
CAT_8

Defines a parametrized test case in pytest, providing input-output pairs for a test function.

@pytest.mark.parametrize('<arg_names>', [<tuple_of_values>])

with pytest.raises(ValueError):
CAT_8

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):

assert mock.call_count == 3
CAT_8

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 == ;

@pytest.fixture def sample(): return {'key': 'value'}
CAT_8

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 ;

assert pytest.approx(0.1 0.2) == 0.3
CAT_8

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.

class TestExample(unittest.TestCase):
CAT_8

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):

def test_addition(self):
CAT_8

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.

self.assertEqual
CAT_8

Asserts that two values are equal using unittest's assertEqual method.

self.assertEqual(arg1, arg2)

with self.assertRaises(ValueError): int
CAT_8

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()

@unittest.skipIf
CAT_8

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>')

with self.subTest(i=idx):
CAT_8

Creates a subtest context for iterative test cases, labeling each iteration with the given identifier for granular test reporting.

with self.subTest(<parameter>=<value>):

self.addCleanup
CAT_8

Registers a cleanup function to clean up a temporary directory after a test.

self.addCleanup(callable)

def test_true_is_true():
CAT_8

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>():

assert True
CAT_8

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 ;

assert == pytest.approx()
CAT_8

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(;)

with pytest.raises(TypeError):
CAT_8

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(;):

@pytest.mark.parametrize('x,y,expected'
CAT_8

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,...), ...])

def test_add(x, y, expected):
CAT_8

Defines a test case for an addition function, specifying inputs x and y and the expected result.

def test_<name>(param1, param2, expected):

assert add(x, y) == expected
CAT_8

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>

with tmpdir as d:
CAT_8

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:

monkeypatch.setattr
CAT_8

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>)