You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 18:17:19