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
# 运行所有名字含 "login" 的用例
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 才能被正确加载)。
Q:能同时指定多个文件吗?
A:可以:pytest tests/test_a.py tests/test_b.py。
Q:IDE 里怎么只跑一个用例?
A:PyCharm/VSCode 的测试面板可以右键单个用例运行,底层就是拼接 文件::用例名 格式。