症状
测试在收集或 setup 阶段失败并报 fixture not found,尽管 fixture 在仓库某处已定义。当同一 fixture 在某个目录的测试里可用、在另一个目录里失败时,困惑加剧,这说明是作用域问题而非缺少定义。
诊断
用 pytest –fixtures 查看该测试文件可见的 fixture;用 find 找 conftest.py 的位置;必要时显式指定 rootdir 或配置再次运行。
pytest --fixtures -q test_file.py
根因
pytest 从测试模块及其祖先 conftest.py 中解析 fixture。定义在别处或名称不同的 fixture 不在此测试的解析路径中。
修复
把共享 fixture 放到需要它的测试的祖先目录下的 conftest.py 中,修正 fixture 名称,并确保 pytest 能发现项目根目录以加载各 conftest。
验证
重新运行确认错误消失;对该测试文件运行 pytest –fixtures 确认 fixture 已被列出。名列其中即证明 pytest 能为该测试解析它。
常见陷阱
把 fixture 复制到多个文件会让维护变难;应统一放入合适的 conftest 作用域。