How to Fix conftest.py Not Loading in pytest
conftest.py is not loading in pytest, ensure it is placed in the correct directory where pytest can discover it, typically the root or test folder. Also, verify the file is named exactly conftest.py and contains valid Python code without syntax errors.Why This Happens
pytest uses conftest.py files to share fixtures and hooks across tests. If pytest does not find or load your conftest.py, it usually means the file is not in a directory pytest scans or the file name is incorrect. Another common cause is syntax errors inside conftest.py that prevent it from loading.
# Directory structure example causing conftest not to load project_root/ tests/ test_sample.py conf_test.py # Incorrect filename, should be conftest.py # test_sample.py import pytest def test_example(fixture_from_conftest): assert fixture_from_conftest == 42
The Fix
Rename the file to conftest.py and place it in the directory where pytest looks for tests, usually the root or the tests/ folder. Also, ensure the file has no syntax errors and defines the fixtures correctly.
# Correct directory structure project_root/ tests/ conftest.py test_sample.py # conftest.py import pytest @pytest.fixture def fixture_from_conftest(): return 42 # test_sample.py def test_example(fixture_from_conftest): assert fixture_from_conftest == 42
Prevention
Always name the file exactly conftest.py and place it in or above the test directories. Use a consistent project structure with a dedicated tests/ folder. Run pytest --collect-only to check if pytest discovers your fixtures. Use linting tools or IDEs to catch syntax errors early.
Related Errors
Other common pytest errors include:
- Fixture not found: Happens if the fixture is not defined or imported properly.
- Import errors in conftest.py: Syntax or import errors prevent pytest from loading the file.
- Multiple conftest.py files conflict: Fixtures with the same name in different
conftest.pyfiles can cause confusion.