0
0
PytestDebug / FixBeginner · 4 min read

How to Fix conftest.py Not Loading in pytest

If 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.

python
# 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
Output
E fixture 'fixture_from_conftest' not found pytest failed to find fixture defined in conftest.py because the file is misnamed or misplaced.
🔧

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.

python
# 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
Output
============================= test session starts ============================== collected 1 item test_sample.py . [100%] ============================== 1 passed in 0.01s ===============================
🛡️

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.py files can cause confusion.

Key Takeaways

Place conftest.py in the root or test directories so pytest can find it.
Name the file exactly conftest.py with no typos or extra characters.
Check conftest.py for syntax errors that block loading.
Use pytest --collect-only to verify fixture discovery.
Maintain a clear project structure with a dedicated tests folder.