如何通过pytest.main()传入位置参数指定测试文件扫描路径?
解决pytest.main无法找到测试用例的问题
你当前代码的问题是把两个测试路径合并成了单个字符串参数传给pytest.main,pytest会把这个带空格的字符串当成一个完整的文件名去查找,自然找不到匹配的文件。而终端执行时,shell会自动拆分参数并解析通配符,所以能正常运行。
以下是两种可行的解决方案:
方案一:拆分路径为独立的列表元素
直接把每个路径作为单独的元素放入参数列表,pytest会自动处理通配符:
retcode = pytest.main([ "/Platform/test_*.py", "/Platform/Another_folder/test_*.py", "--rootdir=/Platform", "--tb=auto" ])
方案二:用glob手动解析通配符(更稳妥)
如果担心不同系统下通配符解析差异,可以用Python的glob模块先把通配符转换成实际的文件路径,再传给pytest:
import glob import pytest # 解析所有匹配的测试文件路径 test_paths = glob.glob("/Platform/test_*.py") + glob.glob("/Platform/Another_folder/test_*.py") # 启动pytest retcode = pytest.main(test_paths + ["--rootdir=/Platform", "--tb=auto"])
内容的提问来源于stack exchange,提问作者Jason Chan
相关产品推荐
相关产品推荐

