Skip to main content

一些参数

pytest执行的时候,支持一些参数开启特定功能 好的!以下是 pytest 常用命令行参数的详细表格说明:

🔍 输出详细程度控制

参数全称说明示例
-v--verbose详细模式,显示每个测试的详细结果pytest -v
-q--quiet静默模式,只显示总体结果pytest -q
-s--capture=no禁用捕获,显示print输出和日志pytest -s
-vs组合参数详细+显示输出(常用组合)pytest -vs
--tb=style--traceback=style设置回溯显示样式pytest --tb=short
—tb 样式选项:
  • --tb=auto:默认,只显示失败测试的回溯
  • --tb=short:简短的回溯信息
  • --tb=long:详细回溯信息
  • --tb=line:每个失败只显示一行
  • --tb=no:不显示回溯信息

🎯 测试选择与过滤

参数说明示例
-k "表达式"关键字过滤,运行名称匹配表达式的测试pytest -k "login"
-m "标记"标记过滤,运行有特定标记的测试pytest -m "slow"
--lf只运行上次失败的测试pytest --lf
--ff先运行失败的,再运行其他的pytest --ff
-x遇到第一个失败就停止pytest -x
--maxfail=nn次失败后停止pytest --maxfail=3
--ignore=路径忽略指定路径pytest --ignore=tests/old/

📁 目录与文件指定

参数说明示例
路径/文件指定测试路径或文件pytest tests/
::指定具体测试函数/类pytest test_file.py::test_func
--collect-only只收集测试,不执行pytest --collect-only
--pyargs从Python包导入测试pytest --pyargs mypkg.tests

⚙️ 执行控制

参数说明示例
-n NUM并行执行(需pytest-xdist)pytest -n 4
--looponfail失败时循环运行pytest --looponfail
-p提前加载插件pytest -p myplugin
--fixtures显示可用fixturespytest --fixtures

📊 报告与输出

参数说明示例
--durations=N显示最慢的N个测试pytest --durations=10
--junitxml=路径生成JUnit XML报告pytest --junitxml=report.xml
--html=路径生成HTML报告(需pytest-html)pytest --html=report.html
--cov=源路径生成覆盖率报告(需pytest-cov)pytest --cov=myapp
--lf上次失败优先pytest --lf

🔧 配置与调试

参数说明示例
-c 文件指定配置文件pytest -c pytest.ini
--version显示pytest版本pytest --version
-h / --help显示帮助信息pytest -h
--setup-show显示fixture执行过程pytest --setup-show
-l显示局部变量值pytest -l

🎯 常用组合示例
# 最常用的组合:详细输出 + 显示打印信息
pytest -vs

# 详细输出 + 只运行名称包含"api"的测试
pytest -v -k "api"

# 运行特定文件中的特定测试类
pytest test_api.py::TestLogin -vs

# 并行运行 + 简短回溯 + 覆盖率
pytest -n auto --tb=short --cov=myapp

# 开发时的快速反馈循环
pytest -xvs --tb=short --lf

# 生成HTML报告
pytest -v --html=report.html --self-contained-html

📝 配置文件中的对应设置 这些参数也可以在 pytest.ini 中配置,pytest运行的时候会读取此文件,这样就不用自己每次去手动加参数了:
[pytest]
# 相当于命令行 -v
addopts = -v

# 相当于 -x
xfail_strict = true

# 相当于 --tb=short
addopts = --tb=short

# 相当于 -m
markers =
    slow: marks tests as slow
    fast: marks tests as fast

💡 使用建议
  1. 开发调试时pytest -xvs(快速失败+详细输出)
  2. CI/CD中pytest --tb=short --junitxml=report.xml(简洁+报告)
  3. 性能分析pytest --durations=10(找出慢测试)
  4. 大型项目pytest -n auto(并行执行)
这些参数可以根据实际需要灵活组合使用!

编程方式调用

pytest除了支持cli方式调用之外(pytest xxx.py),还支持一编码的方式调用
import pytest

if __name__ == "__main__": # 运行测试的主入口(这一行可选)
    # __file__是python内置的全局变量,代指当前文件
    pytest.main([__file__, "-v", "-s"])