pytest 中如何只运行单个测试文件(或单个用例)?
pytest 运行单个文件:pytest tests/test_file.py;运行文件里某个用例:pytest tests/test_file.py::test_name;加 -k 按名称过滤。本文汇总精确定位测试的各种写法。
直接跟上文件路径:pytest tests/test_file.py。要精确到某个用例:pytest tests/test_file.py::test_name。
常用写法
# 整个文件
pytest tests/test_file.py
# 文件中的单个测试函数
pytest tests/test_file.py::test_addition
# 文件中的某个测试类
pytest tests/test_file.py::TestMath
# 类中的某个方法
pytest tests/test_file.py::TestMath::test_addition
按名称模糊匹配:-k
# -k 对测试名称及父级名称等关键字做不区分大小写的表达式匹配
pytest -k login
# 组合条件
pytest -k "login and not slow"
其他实用参数
pytest tests/test_file.py -v # 显示每个用例的详细结果
pytest tests/test_file.py -x # 第一个失败就停止
pytest tests/test_file.py -s # 显示 print 输出
pytest --lf # 重跑缓存中上次失败用例;无失败缓存时默认运行全部
常见问题(FAQ)
Q:路径必须相对项目根目录吗?
A:相对当前运行目录即可。conftest.py 发现取决于收集路径、配置与作用域,不要求只有在项目根目录运行才正确;参数化 node ID 含 [] 等字符时应整体加引号。
Q:能同时指定多个文件吗?
A:可以:pytest tests/test_a.py tests/test_b.py。
Q:IDE 里怎么只跑一个用例?
A:PyCharm/VSCode 的测试面板可以右键单个用例运行,底层就是拼接 文件::用例名 格式。