Pytest - pytest 命令(3) - 常用命令的使用
pytest 常用命令
测试信息输出
# 设置pytest的执行参数 "-q":安静模式, 不输出环境信息 pytest.main(["-q"]) # 设置pytest的执行参数 "-s":显示程序中的print/logging输出 pytest.main(["-s"]) # 设置pytest的执行参数 "-v":丰富信息模式, 输出更详细的用例执行信息 pytest.main(["-v"])
指定用例执行
- 执行全部用例;
# 直接执行pytest.main():自动查找当前目录下,以`test_`开头或者以`_test`结尾的 .py 文件 pytest.main()
- 执行指定py文件的用例;
# main函数中填写py文件,会运行指定文件内的测试任务; pytest.main(["test_login.py"])
- 执行指定方法的测试用例;
# main函数中填写 `py文件::类::方法` (例如:test_mod.py::TestClass::test_method) # 会运行指定文件内的、指定类的、指定测试任务; pytest.main(["test_login.py::Test_Login::test_login"])
- 执行被标记的测试任务;
# 设置pytest的执行参数 "-m slow":会执行被装饰器 `@pytest.mark.marker` 装饰的所有测试用例; # @pytest.mark.marker中,`marker` 字符名称可以自定义;例如定义为 `level1` @pytest.mark.level1 def test_a(self): pass pytest.main(['-m=level1'])
测试报告输出
- allure 测试报告输出,详细使用方法见《Allure测试报告》
# 需要安装 allure-pytest # 设置pytest的执行参数 "--alluredir=./report" ## --alluredir : 生成报告类型 ## ./report : 生成报告存放路径及名称 pytest.main(['--alluredir=./report'])
- html 静态报告
# 需要安装 pytest-html # 设置pytest的执行参数"--html=./report.html":执行测试文件并生成html格式的报告 ## --html : 生成报告类型 ## ./report.html : 生成报告存放路径,及报告名称 pytest.main(['--html=./report.html'])
# '--self-contained-html':将html的css样式合并到测试报告中 pytest.main(['--html=./report.html' , '--self-contained-html'])
- xml 格式报告(没用过)
# 设置pytest的执行参数 "--junitxml=./report.xml":执行测试文件并生成xml格式的报告; # 可以与jenkins做集成时使用 ## --junitxml : 生成报告类型 ## ./report.xml : 生成报告存放路径,及报告名称 pytest.main(["--junitxml=./report.xml"])
- log 格式报告(没用过)
# 设置pytest的执行参数 "--resultlog=./report.txt":执行测试文件并生成log格式的报告(4.0以上版本被移除) ## --resultlog : 生成报告类型 ## ./report.txt : 生成报告存放路径,及报告名称 pytest.main(["--resultlog=./report.txt"])
注:输出测试报告的时候,如果运行的文件不再代码目录的 根目录 下,是不会生成测试报告的。
可在根目录下写一个run.py文件,然后运行即可生产测试报告
run.py
import pytest pytest.main(['-q','./AAS_v65/testcase/test_secadmin.py','--alluredir=./report'])
测试执行策略
- 失败 1 次停止测试
# 设置pytest的执行参数 -x":第01次失败就停止测试 pytest.main(["-x"])
- 指定最大失败次数后,停止测试
# 设置pytest的执行参数 "--maxfail=2":第02次失败就停止测试 pytest.main(["--maxfail=2"])
- 指定失败重试次数后,停止测试
# 需要安装 pytest-rerunfailures # 设置pytest的执行参数 "--reruns=NUM"(NUM是重试次数):测试用例运行失败时,重新运行用例 pytest.main(["--reruns=2"])
- 指定用例并发进程数(还没用过)
# 需要安装 pytest-xdist # 设置pytest的执行参数 "-n NUM"(NUM是需要并发的进程数):支持多线程运行测试用例 pytest.main(["-n=2"])
分类:
Pytest
标签:
Python-自动化测试
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署