python config_error ai_generated true

E fixture 'db_connection' 未找到

E fixture 'db_connection' not found

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

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-03-12首次发现

版本兼容性

版本状态引入弃用备注
7.x active — — —
8.x active — — —

根因分析

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

English

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

解决方案

  1. 92% 成功率
    # 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% 成功率
    # tests/conftest.py
    pytest_plugins = ['myapp.testing.fixtures']
    
    # run with explicit rootdir
    # pytest --rootdir=. tests/
  3. 78% 成功率
    pytest --fixtures -q | grep db_connection
    # If missing, check conftest.py location and rootdir:
    pytest --collect-only -q

无效尝试

常见但无效的做法:

  1. 60% 失败

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

  2. 75% 失败

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