fixtures.py
Overview
The [fixtures.py](/projects/286/67370) file is part of the pytest testing framework, specifically focusing on the implementation, testing, and validation of pytest's fixture system. Fixtures are a core concept in pytest used to provide a fixed baseline environment for tests, allowing for setup and teardown routines, resource management, and dependency injection.
This file primarily contains extensive test cases that validate pytest's fixture mechanism. These tests cover a wide range of scenarios including fixture discovery, parameterization, scope management, autouse behavior, finalizers, error handling, interaction with markers, and integration with plugins and conftest files. It also verifies the behavior of request objects used within fixtures.
The file ensures that pytest fixtures behave correctly across different Python versions and complex use cases, including edge cases like recursive dependencies, scope mismatches, and fixture overriding.
Key Components and Functions
Imported Modules
Standard libraries:
os,sys,textwrap,pathlib.PathPytest internals:
_pytest.compat.getfuncargnames,_pytest.config.ExitCode,_pytest.fixtures.*,_pytest.monkeypatch.MonkeyPatch,_pytest.pytester.*,_pytest.python.Functionpytesttesting framework
Utility Function
test_getfuncargnames_functions()
Purpose: Tests the getfuncargnames utility for normal functions, verifying it correctly identifies positional argument names.
Usage: Internal test for function signature inspection.
test_getfuncargnames_methods()
Purpose: Tests getfuncargnames for instance methods with various argument styles (positional-only, keyword-only, etc.).
Usage: Ensures method argument introspection works correctly.
test_getfuncargnames_staticmethod(), test_getfuncargnames_staticmethod_inherited()
Purpose: Test getfuncargnames with static methods, including inherited ones.
Usage: Verifies argument introspection for static methods.
Test Classes
These classes contain grouped test cases focusing on different aspects of fixture functionality.
TestFillFixtures
Tests fixture filling behavior and error handling.
Covers recursive dependency detection, fixture lookup failures, and fixture extension across modules, classes, and plugins.
Demonstrates how fixtures with the same name are overridden at different levels (module, conftest, plugin).
Validates autouse fixtures and parametrized fixtures behavior.
TestRequestBasic
Tests the
TopRequestobject which represents the context of a test function execution.Verifies attributes like function, keywords, module, class, config, and request-specific methods.
Includes tests for garbage collection, recursive fixture calls via
getfixturevalue, finalizer execution order, and exception handling during finalization.Usage example: Interacting with
requestin fixtures to add finalizers or access fixture values.
TestRequestSessionScoped
Validates attribute availability restrictions for session-scoped fixtures.
Example: Accessing
pathormoduleattributes from a session-scoped request should raiseAttributeError.
TestRequestMarking
Tests the ability of
requestobjects to apply markers like xfail and skipif to test items.Validates the dynamic modification of test markers within fixtures or test functions.
TestFixtureUsages
Extensive tests covering fixture declaration, parameterization, scope mismatch errors, fixture shadowing parameters, and usefixtures markers.
Validates setup and teardown order, caching of fixture setup, and finalizers.
Tests compatibility with class and static methods.
Usage examples include parametrized fixtures, autouse fixtures, and fixture dependencies.
TestFixtureManagerParseFactories
Tests the fixture manager's ability to parse and discover fixtures across conftest files, modules, and class scopes.
Handles edge cases like objects raising exceptions on attribute access.
Validates relative node IDs and package-scoped fixture behaviors.
TestAutouseDiscovery
Tests discovery of autouse fixtures in various contexts (conftests, modules, classes).
Validates autouse fixtures' execution order, scoping, and interaction with other fixtures.
TestAutouseManagement
Focuses on nuanced behaviors of autouse fixtures, including mid-directory conftest autouse fixtures.
Tests fixture usage with parametrization and finalizer execution.
Includes regression tests for known issues.
TestFixtureMarker
Tests interaction between fixture parameterization and pytest markers.
Validates scope handling, skip behaviors, and indirect parametrization.
TestRequestScopeAccess
Parametrized tests for what attributes are available on
requestobjects depending on fixture scope.Verifies correct attribute access restrictions per scope level.
TestErrors
Tests error conditions such as missing fixture dependencies, fixture finalizers raising exceptions, and double decoration of fixtures.
Validates that exceptions are correctly reported and do not leak internal errors.
TestShowFixtures
Tests the --fixtures command line option output.
Validates fixture documentation display, trimming, indentation, and multiple fixture sources.
Ensures fixtures with the same name from different sources are distinctly shown.
TestContextManagerFixtureFuncs
Tests fixtures implemented as context managers using
yield.Validates setup and teardown prints, handling of multiple yields, and custom fixture names.
TestParameterizedSubRequest
Tests behavior when fixtures request other parametrized fixtures via
getfixturevalue.Ensures proper error reporting when parameters are missing for requested fixtures.
Standalone Test Functions
test_call_fixture_function_error(): Ensures direct calls to fixture functions raise an error.test_fixture_double_decorator(): Checks that applying@pytest.fixturetwice raises an error.test_fixture_class(): Verifies error on applying@pytest.fixtureto a class.test_fixture_param_shadowing(): Tests parameter shadowing between fixtures and parametrized arguments.test_fixture_named_request(): Ensures 'request' is reserved and warns if used as a fixture parameter name.test_indirect_fixture_does_not_break_scope(): Verifies fixture scope is respected with indirect parametrization.test_fixture_parametrization_nparray(): Integration test with numpy arrays as parameters.test_fixture_arg_ordering(): Tests the order of fixture setup when dependencies are not explicit.test_yield_fixture_with_no_value(): Ensures error if fixture yields no value.test_deduplicate_names(): Tests utility for deduplicating fixture names.test_staticmethod_classmethod_fixture_instance(): Regression test for static and class method fixtures.test_scoped_fixture_caching(),test_scoped_fixture_caching_exception(): Tests caching and finalization of scoped fixtures.test_scoped_fixture_teardown_order(): Ensures proper teardown order for scoped fixtures.test_subfixture_teardown_order(): Tests finalizer re-registration and teardown ordering.test_parametrized_fixture_scope_allowed(): Ensures parametrization scope does not affect dependability.test_collect_positional_only(): Supports positional-only arguments in test collection.
Important Implementation Details and Algorithms
Fixture Discovery & Resolution: The file tests how fixtures are discovered from multiple sources (conftest, plugins, modules, classes) and how overriding works, including parameterized fixtures.
Scope and Dependency Ordering: Tests validate that fixtures are ordered and executed respecting their scopes (
session,package,module,class,function), dependencies, and autouse settings. Finalizer execution order is tested to confirm reverse order of setup.Dynamic Scopes: Fixtures can have scopes determined dynamically at runtime via callable scope functions.
Parameterization: Multiple layers of parameterization are supported, including fixtures with parameters and indirect parametrization via markers.
Request Object: The
requestobject encapsulates fixture request context, including adding finalizers, accessing fixture values, and applying markers dynamically.Error Handling: The tests validate robust error reporting for missing fixtures, scope mismatches, recursive dependencies, and double decoration.
Integration with pytest Hooks: Tests verify that hooks like pytest_fixture_setup and pytest_fixture_post_finalizer are called appropriately.
Yield Fixtures: Fixtures can be implemented as generators with
yield, enabling setup and teardown semantics.Caching: Scoped fixtures cache their setup results, and multiple uses within scope reuse the cached result.
Interaction with Other Parts of the System
pytest Core: This file tests the fixture subsystem of pytest, which is tightly integrated with test collection, configuration, and execution.
_pytest.fixtures Module: Uses internal classes like
TopRequestand utilities likededuplicate_names._pytest.pytester: The Pytester utility is used extensively for creating test files, running pytest subprocesses, and validating output.
_pytest.config and ExitCode: Used to check test run results.
_pytest.monkeypatch: Used for patching environment or attributes in some tests.
pytest Markers: The interaction with pytest's marker system is tested extensively.
Test Modules and Conftests: Tests involve creating temporary files and directories to simulate real test environments with fixtures defined across modules and conftest scripts.
Usage Examples
Example: Defining and Using a Fixture
import pytest
@pytest.fixture
def sample_fixture():
return 42
def test_example(sample_fixture):
assert sample_fixture == 42
Example: Parametrized Fixture
@pytest.fixture(params=[1, 2, 3])
def param_fixture(request):
return request.param
def test_param(param_fixture):
assert param_fixture in [1, 2, 3]
Example: Using request to Add a Finalizer
@pytest.fixture
def resource(request):
# setup code
def cleanup():
print("Resource cleanup")
request.addfinalizer(cleanup)
return "resource"
Mermaid Class Diagram
The main class used and tested in this file is `TopRequest`. Below is the class diagram illustrating its key attributes and methods, reflecting its role in fixture request handling.
classDiagram
class TopRequest {
+function
+keywords
+module
+cls
+config
+path
+fixturenames
+getfixturevalue(name)
+addfinalizer(func)
+applymarker(marker)
+_fillfixtures()
+__repr__()
}
TopRequest --> pytest.Function : uses
Summary
The [fixtures.py](/projects/286/67370) file is an extensive test suite validating the robustness, correctness, and flexibility of pytest's fixture system. It covers nearly all aspects of fixture behavior, including scope, parameterization, autouse, error conditions, dynamic scope, and integration with pytest internals like markers and request objects. The tests ensure that fixtures behave reliably in complex real-world scenarios and that pytest's fixture API remains consistent and user-friendly.
This file is crucial for maintaining the quality and reliability of pytest's fixture system, one of its most powerful and widely used features.