Browse Chunks
Showing 5301-5350 of 7392 chunks
Captures the standard output and standard error streams produced by the code under test during a pytest test, storing them in the variables out and err for later assertion.
out, err = capsys.readouterr()
This decorator conditionally skips a test when a given boolean expression evaluates to True, typically used to omit tests that require optional extensions or libraries not present in the current environment.
@pytest.mark.skipif(; , reason=';')
Defines a test fixture method that runs before each test method in a unittest.TestCase subclass, used to initialize test state.
def setUp(self): ;
Cleans up test fixtures by deleting the instance attribute `value` after each test method runs, ensuring test isolation.
def tearDown(self): del self.;
Defines a pytest module-level setup function that initializes a cache dictionary on the module object for sharing state across tests in the same module.
def setup_module(module):\n module.cache = {}
Defines a class method that initializes a shared resource before any test methods in the class run.
@classmethod\ndef setUpClass(cls):\n cls.shared = SharedResource()\n cls.shared.setup()
A pytest fixture that automatically mocks an external HTTP GET request to return a predefined JSON response, ensuring tests run without making real network calls.
@pytest.fixture(autouse=True) def <fixture_name>(requests_mock): requests_mock.get('<url>', json=<payload>) yield
This chunk uses unittest.mock.patch as a context manager to temporarily replace a specified attribute with a mock object during the execution of a block. It addresses the need to isolate unit tests from external dependencies or side‑effects. Developers reach for it when they want to control the behavior of a function, method, or object within a test without modifying production code.
with patch('target') as mock:
A Python unit test that uses unittest.mock.patch to replace a method of a class with a mock object, injecting the mock as a function argument so the test can verify interactions without executing the real method.
@patch('target') def test_function(mock):
Sets the return value of a mock method so that when the method is called during testing, it returns the specified value.
mock_method.return_value = <value>
Verifies that a mock object was called exactly once with the specified arguments. This assertion helps ensure that a unit under test interacts with its dependencies as expected, catching cases where the mock is called zero times, multiple times, or with incorrect parameters. It is typically used after exercising the code under test to validate the interaction contract.
mock.assert_called_once_with(*expected_args, **expected_kwargs)
Configures a mock object to raise a specified exception when invoked, allowing tests to verify error‑handling behavior.
<mock_object>.side_effect = Exception('<exception_message>')
A context manager that temporarily replaces a method with a mock returning a specified value, used to isolate units under test.
with patch.object(<Class>, '<method>', return_value=<value>):
Applies multiple patches to a module using unittest.mock.patch.multiple, providing mocks or default objects as arguments to the decorated test function.
decorator pattern for multiple patching
...
with patch(;, ;) as ;:
Temporarily replaces environment variables within a context, automatically restoring them after the block ends. This avoids polluting the global os.environ during tests that depend on specific configuration values. Use it when a unit test needs to simulate a particular environment setup.
with patch.dict('os.environ', {env_var: env_value}):
A context manager that temporarily replaces a class property with a PropertyMock, allowing the property's get/set/delete behavior to be controlled in unit tests.
with patch.object(Class, 'attribute', new_callable=PropertyMock) as mock:
Sets the side_effect attribute of a mock method to return a sequence of values on successive calls.
<mock_object>.side_effect = [<value1>, <value2>, ...]
Replaces a class or object with a mock during testing, allowing you to control its behavior and isolate the unit under test. The autospec argument ensures the mock mimics the original's signature, preventing accidental misuse.
@patch(; , autospec=;)
Parametrizes a test function with multiple sets of arguments, causing the test to run once per argument tuple.
@pytest.mark.parametrize('arg1,arg2,...', [(val1,val2,...), ...])
A parameterized unit test loop that iterates over a collection of input‑output tuples, uses unittest.subTest to isolate each case, and asserts equality of the function under test.
for <a>, <b>, <expected> in [<tuple>, ...]: with self.subTest(<a>=<a>, <b>=<b>): self.assertEqual(<func>(<a>, <b>), <expected>)
The parameterized.expand decorator generates multiple test methods from a single test function, each with a different set of arguments taken from a list of tuples. It enables data‑driven (table‑driven) unit tests without writing repetitive test code. Use it when you need to verify the same logic across many input/output pairs.
@parameterized.expand([; ]) def test_; (self, ; ): self.assertEqual(; (; ), ; )
Creates a coverage measurement object using the coverage.py library to track which lines of code are executed during test runs.
cov = coverage.Coverage()
Starts measuring code coverage using the coverage.py library.
cov.start() where cov is an instance of coverage.Coverage
Stops measuring code coverage for a coverage.py Coverage object, finalizing the collected coverage data.
cov.stop()
Generates an HTML coverage report in the specified directory.
cov.html_report(directory='<path>')
cov.report() generates a profiling report of the covariance matrix of a DataFrame, typically used in pandas‑profiling or pandas‑profiling‑like libraries to produce a detailed statistical report.
<dataframe>.cov().report()
Removes an element from a container named cov using its erase method.
cov.erase(element)
Calls the save method on an object to persist its state, typically to disk or a storage backend.
; .save()
Generates an XML coverage report file from collected coverage data.
cov.xml_report(outfile='<filepath>')
Combines multiple covariance matrices into a single pooled estimate, typically via a weighted average, to produce a unified uncertainty estimate.
cov.combine(*covariances, weights=None)
Generates a JSON coverage report of measured code coverage and writes it to the specified output file.
object.method(keyword_arg=value)
Loads a covariance matrix from a file into a covariance object.
cov.load()
Calls the get_data method on an object named cov to retrieve the underlying data array or matrix stored inside a covariance or similar statistical object. This provides access to the raw numeric data for further analysis, inspection, or passing to other routines.
;.get_data()
@given(st.integers()) is a hypothesis decorator that configures a test function to receive automatically generated integer arguments for property-based testing.
@given(st.integers())
Defines a test function that asserts the commutative property of addition for two operands.
def test_<name>(<arg1>, <arg2>): assert <arg1> <op> <arg2> == <arg2> <op> <arg1>
Returns a single example value from a Hypothesis strategy that generates lists of integers. Eliminates the need to manually devise representative test data when writing property‑based tests. Used when a quick concrete sample is needed to inspect a strategy’s output or to seed a manual test.
st.lists(element_strategy).example()
...
@given(st.lists(st.; min_size=;))
Configures Hypothesis test generation to allow up to 2000 examples and disables test timeouts.
@settings(max_examples=<int>, deadline=None) where <int> ≥ 1
States that the list xs is assumed to have at least one element; used as a precondition to guarantee non‑empty input before processing.
assume(len(;) > 0)
Applies a decorator named `example` to a function, passing a list (or other expression) as configuration; often used to attach sample data or test cases to a function for testing or demonstration.
@example(; )
A type annotation indicating a list whose elements are integers.
List[<type>]
A dictionary that maps string keys to integer values.
Dict[<key_type>, <value_type>] where key_type is str and value_type is int
Denotes a type that can be either an integer or a string.
Union[<type1>, <type2>]
Represents a value that may be either a float or None, used to indicate optional numeric values in type annotations.
Optional[; ]
Represents a list where each element is a tuple containing a string and an integer. Used when you need a collection of key‑value‑like pairs where the key is a string and the value is an integer, e.g., labeling items with counts.
List[Tuple[str, int]]
Specifies that an object is a callable which accepts an integer and a string and returns a Boolean value.
Callable[[<arg1_type>, <arg2_type>], <return_type>] (specific: Callable[[int, str], bool])
Represents a collection of unique, immutable groups of float values. Each inner frozenset is hashable, allowing it to be an element of the outer set. This structure is useful for deduplicating sets of floats where the grouping itself must be treated as a single, unordered entity.
Set[FrozenSet[item_type]]
A type annotation indicating that a value can be either a list of integers or a dictionary mapping strings to arbitrary types.
Union[TypeA, TypeB] where TypeA and TypeB are themselves parameterized generic types
A list of dictionaries where each dictionary maps string keys to integer values.
list[Dict[str, int]]