Sharing Fixtures (conftest.py)
By default, fixtures defined inside a test file are only available to tests in that same file. When you want to reuse fixtures across multiple test files, pytest provides a special mechanism: the conftest.py file.
A conftest.py file allows you to define fixtures (and other pytest customizations) that are shared automatically, without requiring explicit imports.
NOTE
Large pytest projects often contain multiple conftest.py files. Each conftest.py acts as a local plugin for the directory it lives in, providing fixtures, hooks and other test-specific configuration to that directory and its subdirectories.
Key characteristics of conftest.py:
- No imports needed: Fixtures and hooks defined in
conftest.pyare automatically discovered by pytest. Tests can use them directly without importing anything. - Hierarchical lookup: When running a test, pytest searches for fixtures in the following order:
- The test file itself.
- The nearest
conftest.py. - Parent directories’
conftest.pyfiles, continuing upward until the project root is reached.
This structure makes it easy to share common setup logic while still keeping fixtures scoped appropriately within different parts of your test suite.
