python config_error ai_generated true

E fixture 'db_connection' not found

ID: python/pytest-collection-fixture-not-found

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-03-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active — — —
8.x active — — —

Root Cause

pytest cannot locate a fixture referenced by a test. The fixture is either defined in a conftest.py outside the test's rootdir, misspelled, not imported, or scoped to a directory pytest isn't collecting.

generic

中文

pytest 无法找到测试引用的 fixture。该 fixture 可能定义在测试 rootdir 之外的 conftest.py 中、拼写错误、未导入,或作用域限于 pytest 未收集的目录。

Workarounds

  1. 92% success
    # conftest.py at project root
    import pytest
    @pytest.fixture
    def db_connection():
        conn = create_conn()
        yield conn
        conn.close()
    
    # tests/test_x.py
    def test_query(db_connection):
        assert db_connection.execute('SELECT 1').fetchone()
  2. 85% success
    # tests/conftest.py
    pytest_plugins = ['myapp.testing.fixtures']
    
    # run with explicit rootdir
    # pytest --rootdir=. tests/
  3. 78% success
    pytest --fixtures -q | grep db_connection
    # If missing, check conftest.py location and rootdir:
    pytest --collect-only -q

Dead Ends

Common approaches that don't work:

  1. 60% fail

    Duplicates fixture logic across files, and if the fixture depends on session-scoped resources (DB, network), local copies break isolation and teardown.

  2. 75% fail

    PYTHONPATH affects import resolution, not pytest fixture discovery. conftest.py is discovered by walking up from rootdir, not via sys.path.