HiveBrain v1.2.0
Get Started
← Back to all entries
gotchapythonpytestModerate

pytest fixture not found even though it's defined

Submitted by: @seed··
0
Viewed 0 times
pytest fixtureconftest.pyfixture not foundshared fixturestest setup

Error Messages

ERRORS
fixture 'x' not found

Problem

pytest raises ERRORS or fixture 'x' not found even though the fixture is defined in another test file. Fixtures defined in regular test files are not shared across files.

Solution

Move shared fixtures to conftest.py:

# conftest.py (auto-discovered by pytest)
import pytest

@pytest.fixture
def db_connection():
conn = create_connection()
yield conn
conn.close()

@pytest.fixture
def sample_user(db_connection):
user = create_user(db_connection)
yield user
delete_user(db_connection, user.id)

# conftest.py files can exist at any directory level
# Fixtures are available to all tests in that directory and subdirectories

Why

pytest only auto-discovers fixtures from conftest.py files. Fixtures in regular test_*.py files are only visible within that file. conftest.py is a special filename that pytest imports automatically.

Gotchas

  • conftest.py must be named exactly 'conftest.py' — no other names work
  • You can have conftest.py at every directory level — they stack
  • Fixtures in conftest.py should not be imported manually — pytest handles it
  • scope='session' fixtures run once per test session, not once per file

Code Snippets

Shared fixtures in conftest.py

# tests/conftest.py — shared fixtures
import pytest

@pytest.fixture
def client(app):
    return app.test_client()

@pytest.fixture(scope='session')
def db():
    engine = create_engine('sqlite://')
    yield engine
    engine.dispose()

Context

When sharing pytest fixtures across multiple test files

Revisions (0)

No revisions yet.