← Debugging Guides

阅读中文版本

pytest — fixture not found though it is defined

Fix pytest fixture-not-found errors by placing fixtures at the right scope and ensuring conftest files are discoverable.

beginnerdebuggingpythonpytest

Symptoms

  • fixture "db" not found when running a test
  • The fixture exists in another test file but is not accessible
  • Adding an import causes a name mismatch
  • The fixture works in one directory but not another

Possible causes

  • The fixture is defined in a module that is not an ancestor conftest.py of the test
  • A typo or renamed fixture does not match the test argument
  • The fixture is defined inside a class instead of at module level
  • pytest rootdir or import mode prevents conftest discovery

Diagnosis steps

List available fixtures

pytest --fixtures -q test_file.py

Interpretation

The output lists fixtures visible to that test file. If the needed one is absent, it lives outside the discovery scope.

Locate conftest files

find . -name conftest.py

Interpretation

Fixtures in conftest.py are available to tests in that directory and below. A fixture in a sibling directory is not visible.

Run with explicit rootdir

pytest -c pyproject.toml test_file.py

Interpretation

If specifying the config changes discovery, the rootdir or ini settings were wrong.

Root cause

pytest resolves fixtures from the test module and ancestor conftest.py files. A fixture defined elsewhere, or named differently, is not in the resolution path for that test.

Fix

Move shared fixtures into a conftest.py that is an ancestor of the tests that need them, correct the fixture name, and ensure pytest discovers the project root so conftest files load.

Verify the fix

Run the test again and confirm the error is gone; run pytest --fixtures on the test file to confirm the fixture is now listed.

Symptom walkthrough

A test fails at collection or setup with fixture not found even though the fixture is written somewhere in the repository. The confusion grows when the same fixture works for tests in one directory and fails in another, which points at scope rather than a missing definition.

Fix in practice

Place fixtures that multiple test files share in a conftest.py in an ancestor directory, since pytest makes those visible to that directory and below. Also verify the fixture name matches the test argument exactly and that the fixture is module level rather than buried in a class.

Verification

Rerun the test and confirm the error is gone, then list available fixtures for that file to confirm the expected fixture appears. Seeing it listed proves pytest resolves it for that test. A fixture that appears in the listing yet still fails at setup usually points at a scoping shadow instead of a missing definition.

Diagnostic commands

Check the behavior with commands like these:

pytest --fixtures -q test_file.py
find . -name conftest.py
pytest -c pyproject.toml test_file.py