Browse Chunks

Showing 5301-5350 of 7392 chunks

out, err = capsys.readouterr()
CAT_8

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

@pytest.mark.skipif
CAT_8

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

def setUp(self): self.value = 42
CAT_8

Defines a test fixture method that runs before each test method in a unittest.TestCase subclass, used to initialize test state.

def setUp(self): ;

def tearDown(self): del self.value
CAT_8

Cleans up test fixtures by deleting the instance attribute `value` after each test method runs, ensuring test isolation.

def tearDown(self): del self.;

def setup_module(module): module.cache = {}
CAT_8

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 = {}

@classmethod def setUpClass(cls): cls.shared = SharedResource() cls.shared.setup()
CAT_8

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

@pytest.fixture(autouse=True) def mock_external_api(requests_mock): requests_mock.get('https://api.example.com/data', json={'status': 'ok'}) yield
CAT_8

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

with patch('module.Class.method') as mock_method:
CAT_8

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:

@patch('module.Class.method')\ndef test_something(mock_method):
CAT_8

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

mock_method.return_value = 42
CAT_8

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>

mock_method.assert_called_once_with()
CAT_8

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)

mock_method.side_effect = Exception
CAT_8

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

with patch.object(MyClass, 'method', return_value='mocked'):
CAT_8

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

@patch.multiple('module', Class1=DEFAULT, func2=MagicMock())\ndef test_something(Class1, func2):
CAT_8

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('builtins.open', mock_open(read_data='test_data')) as mocked_open:
CAT_8

...

with patch(;, ;) as ;:

with patch.dict('os.environ', {'API_KEY': 'fake'}):
CAT_8

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

with patch.object(MyClass, 'prop', new_callable=PropertyMock) as mock_prop:
CAT_8

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:

mock_method.side_effect =
CAT_8

Sets the side_effect attribute of a mock method to return a sequence of values on successive calls.

<mock_object>.side_effect = [<value1>, <value2>, ...]

@patch
CAT_8

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

@pytest.mark.parametrize('a,b,expected'
CAT_8

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

for a, b, expected in; with self.subTest(a=a, b=b): self.assertEqual(add(a, b), expected)
CAT_8

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

@parameterized.expand(; ) def test_add(self, a, b, expected): self.assertEqual(add(a, b), expected)
CAT_8

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

cov = coverage.Coverage()
CAT_8

Creates a coverage measurement object using the coverage.py library to track which lines of code are executed during test runs.

cov = coverage.Coverage()

cov.start()
CAT_8

Starts measuring code coverage using the coverage.py library.

cov.start() where cov is an instance of coverage.Coverage

cov.stop()
CAT_8

Stops measuring code coverage for a coverage.py Coverage object, finalizing the collected coverage data.

cov.stop()

cov.html_report
CAT_8

Generates an HTML coverage report in the specified directory.

cov.html_report(directory='<path>')

cov.report()
CAT_8

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

cov.erase()
CAT_8

Removes an element from a container named cov using its erase method.

cov.erase(element)

cov.save()
CAT_8

Calls the save method on an object to persist its state, typically to disk or a storage backend.

; .save()

cov.xml_report
CAT_8

Generates an XML coverage report file from collected coverage data.

cov.xml_report(outfile='<filepath>')

cov.combine()
CAT_8

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)

cov.json_report
CAT_8

Generates a JSON coverage report of measured code coverage and writes it to the specified output file.

object.method(keyword_arg=value)

cov.load()
CAT_8

Loads a covariance matrix from a file into a covariance object.

cov.load()

cov.get_data()
CAT_8

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

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

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

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>

st.lists(st.integers()).example()
CAT_8

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.integers(), min_size=0))
CAT_8

...

@given(st.lists(st.; min_size=;))

@settings
CAT_8

Configures Hypothesis test generation to allow up to 2000 examples and disables test timeouts.

@settings(max_examples=<int>, deadline=None) where <int> ≥ 1

assume(len(xs) > 0)
CAT_8

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)

@example
CAT_8

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

List
CAT_9

A type annotation indicating a list whose elements are integers.

List[<type>]

Dict
CAT_9

A dictionary that maps string keys to integer values.

Dict[<key_type>, <value_type>] where key_type is str and value_type is int

Union
CAT_9

Denotes a type that can be either an integer or a string.

Union[<type1>, <type2>]

Optional
CAT_9

Represents a value that may be either a float or None, used to indicate optional numeric values in type annotations.

Optional[; ]

List
CAT_9

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

Callable; bool]
CAT_9

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

Set
CAT_9

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

Union; Dict
CAT_9

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

list
CAT_9

A list of dictionaries where each dictionary maps string keys to integer values.

list[Dict[str, int]]