
当采用 pytest 的“测试作为应用代码”组织方式时,若将 conftest.py 放在嵌套的 __tests__ 目录中,默认无法被兄弟或下级测试目录自动发现;需通过调整目录结构或显式配置使 fixture 跨层级生效。
pytest 对 conftest.py 的发现遵循严格的作用域就近原则:它仅对同级及所有子目录下的测试文件生效,而不会向上回溯父目录,也不会横向扫描兄弟目录。在您给出的结构中:
module_a/
a.py
__tests__/
conftest.py ← 仅对 module_a/__tests__ 及其子目录(如 __tests__/subdir/)有效
test_a.py
submodule/
b.py
__tests__/
test_b.py ← 此处不继承上层 __tests__/conftest.py!module_a/submodule/__tests__/test_b.py 与 module_a/__tests__/conftest.py 属于平行路径(同为 module_a/ 的子目录),因此 pytest 不会自动加载该 conftest。
✅ 推荐解决方案:统一测试入口,保持语义清晰
最符合 pytest 设计哲学且无需额外配置的做法是——将所有测试收归到顶层 __tests__ 目录下,并按模块路径组织子包,例如:
module_a/
a.py
submodule/
b.py
__tests__/
__init__.py
conftest.py ← 所有 module_a 下测试共享的 fixture
test_a.py
submodule/
__init__.py
test_b.py ← 自动继承 __tests__/conftest.py此时运行 pytest module_a/__tests__ 或直接 pytest module_a/,pytest 均能正确识别并应用 __tests__/conftest.py 中定义的 fixture 到 submodule/test_b.py。
? 提示:确保每个 __tests__ 及其子目录中包含 __init__.py(可为空),使其成为合法 Python 包,有助于 import 和 fixture 解析稳定性。
⚠️ 替代方案(不推荐,仅作了解)
-
使用 pytest_plugins 显式导入:在 module_a/submodule/__tests__/conftest.py 中添加
pytest_plugins = ["module_a.__tests__.conftest"]
但需保证模块可导入(即 module_a 在 Python path 中),且易引发循环依赖或路径管理复杂性。
修改 pytest.ini 指定 conftest 搜索路径:pytest 不支持全局配置 conftest 查找范围,此路不通。
✅ 最佳实践总结
| 原则 | 说明 |
|---|---|
| conftest 作用域 = 目录树向下单向继承 | 它只影响自身所在目录及其全部后代目录,不跨平级、不向上 |
| 测试目录应作为逻辑根节点 | 将 __tests__ 设为测试专属根,内部按源码结构镜像建模,兼顾组织性与 discoverability |
| 避免多层分散 conftest | 除非有明确隔离需求(如不同环境 fixture),否则优先集中管理以降低维护成本 |
通过上述结构调整,您既能坚守“测试即代码”的整洁理念,又能无缝复用 fixture,无需妥协目录语义或引入脆弱配置。










