python config_error ai_generated true

ScopeError: fixture 'db' defined in conftest.py conflicts with fixture 'db' defined in test_module.py

ID: python/pytest-fixture-scope-collision

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.4.0 active
8.0.0 active

Root Cause

同一夹具名称在 conftest.py 和测试模块中重复定义,pytest 无法确定使用哪个夹具,导致作用域冲突。

generic

中文

同一夹具名称在 conftest.py 和测试模块中重复定义,pytest 无法确定使用哪个夹具,导致作用域冲突。

Workarounds

  1. 90% success
    在 conftest.py 中定义通用夹具,在测试模块中定义专用夹具,并确保名称唯一。例如:conftest.py 中定义 'db_global',测试模块中定义 'db_local'。
  2. 70% success
    将 conftest.py 中的夹具设为可覆盖,测试模块中定义同名夹具时,pytest 会优先使用测试模块中的。但需确保 conftest.py 中夹具不需要被其他测试使用。

Dead Ends

Common approaches that don't work:

  1. 60% fail

    如果 conftest.py 中的夹具被其他测试文件使用,删除会导致其他测试失败。

  2. 40% fail

    重命名后,测试函数中的引用需要同步修改,容易遗漏,且不解决根本冲突。