采用Tests as part of application code模式时pytest的conftest发现问题
解决pytest中__tests__目录下conftest跨子模块识别问题
问题背景
采用「测试代码作为应用代码一部分」的模式,目录结构如下:
module_a/ a.py __tests__/ conftest.py test_a.py submodule/ b.py __tests__/ test_b.py
module_a/__tests__/conftest.py中定义的fixtures无法被module_a/submodule/__tests__下的测试识别,不想将conftest移到module_a根目录,需要可行的解决办法。
解决方案
方案1:在子模块测试目录的conftest中导入上层fixtures
在module_a/submodule/__tests__/conftest.py中添加以下代码,直接导入上层conftest里的fixtures:
# 导入单个fixture,替换成你实际的fixture名称 from module_a.__tests__.conftest import my_shared_fixture # 或者导入所有fixture from module_a.__tests__.conftest import *
注意:确保项目根目录在Python的sys.path中(可以通过在项目根目录运行pytest,或设置PYTHONPATH环境变量实现)。
方案2:使用pytest_plugins加载上层conftest
同样在module_a/submodule/__tests__/conftest.py中,通过pytest_plugins声明要加载的上层conftest模块:
pytest_plugins = ["module_a.__tests__.conftest"]
pytest会自动将这个模块作为插件加载,其中定义的所有fixtures都能在子模块测试中直接使用。
方案3:配置pytest测试路径与Python路径
在项目根目录创建pytest.ini配置文件,添加以下内容:
[pytest] # 指定测试目录,同时包含上层和子模块的测试路径 testpaths = module_a/__tests__ module_a/submodule/__tests__ # 将项目根目录加入Python路径,确保模块可导入 pythonpath = .
运行pytest时会同时扫描两个测试目录,配合方案1或方案2即可让子模块测试识别上层fixtures。
方案4:运行pytest时指定测试目录
如果不想修改配置文件,每次运行pytest时直接指定两个测试目录:
pytest module_a/__tests__/ module_a/submodule/__tests__/
需确保项目根目录在sys.path中,再配合方案1或方案2导入fixtures。
内容的提问来源于stack exchange,提问作者Golan Kiviti
相关产品推荐
相关产品推荐

