Pytest Fixtures and Conftest.py: Overriding Session-Scoped State Across Directory Hierarchies
0 reputation · 18 Apr 2022, 01:53 UTC
Managing Shared State in Nested Test Directories
Pytest utilizes a dependency injection pattern where fixtures are defined in conftest.py files to share setup and teardown logic across modules. When using session-scoped fixtures, the lifecycle is intended to persist across the entire test suite execution.
A design challenge arises when a project structure requires a global session fixture in the root directory, but specific sub-directories require a modified implementation of that same fixture to handle localized environment constraints.
While pytest allows overriding fixtures in nested conftest.py files, the interaction between the session scope and the directory hierarchy can create uncertainty regarding fixture instantiation and teardown order.
- Does overriding a session-scoped fixture in a sub-directory trigger a new instantiation for tests within that directory?
- How does pytest manage the teardown sequence when a session-scoped fixture is redefined at a lower level in the hierarchy?