添加pytest.ini后pytest找不到测试模块?无该文件时为何正常?
pytest测试模块查找机制及配置导致导入失败的原因
场景说明
场景1:无pytest.ini时测试正常运行
目录结构:
根目录/ ├── tests/ │ └── test_sum.py └── script_to_test.py
test_sum.py代码:
import script_to_test def test_sum(): d = script_to_test.sum(6,5) assert d == 11
script_to_test.py代码:
def sum(a,b): return a + b
在根目录执行pytest命令,测试正常通过。
场景2:添加pytest.ini后导入失败
在根目录添加pytest.ini,内容如下:
[pytest] python_files = test_* python_classes = *Tests python_functions = test_*
再次执行pytest命令,触发错误:ModuleNotFoundError: No module named 'script_to_test'
核心原因分析
无pytest.ini时的默认行为
pytest在未找到任何配置文件(pytest.ini/tox.ini/setup.cfg)时,会将当前执行命令的工作目录(根目录)添加到Python的sys.path中。此时test_sum.py里的import script_to_test会直接在根目录查找该模块,自然能成功导入。
添加pytest.ini后的行为变化
只要存在pytest配置文件,pytest会切换导入策略:它会将测试文件所在的目录(即tests/文件夹)添加到sys.path,不再把根目录加入其中。此时test_sum.py所在的tests/是sys.path的一部分,但根目录不在列表内,因此无法找到上层目录的script_to_test模块,从而抛出导入错误。
哪怕你配置的python_files等参数和pytest默认值完全一致,只要配置文件存在,这个导入策略的变化就会触发。
内容的提问来源于stack exchange,提问作者KansaiRobot
相关产品推荐
相关产品推荐

