pytest 常用命令行选项学习笔记(一)

1. pytest --help/-help 查看全部选项

2. pytest -m选项

描述:标记(marker)用于标记测试并分组,以便快速选中并运行。

3. pytest -v选项

描述:使用-v/--verbose选项,输出的信息会更详细。最明显的区别就是每个文件中每个测试用例都占一行,测试的名字和结果都会显示出来,而不仅仅是一个点或字符。如下图: 

4. pytest -s

描述:关闭Captured stdout call输出信息(失败或成功都不显示输出结果),但是会显示在test session start部分效果等同于 --capture=no

实例:

 $pytest teset_sample.py

$pyteset -s test_sample.py,加了-s不再显示Captured stdout call信息,但是会显示test session starts

 5. pytest --alluredir=DIR

描述: 在指定目录生成allure报告(需要安装第三方库pip install allure-pytest)

注意:pytest-allure-adaptor已经废弃,如果安装了它会导致pytest无法正常运行,所以建议安装allure-pytest

6. pytest test.py --reruns 3 或 pytest test.py --reruns 3 --reruns-delay 5

描述:重复执行失败的用例且每次执行器等待5秒后在继续执行,提前安装:pip install pytest-rerunfailures

7. pytest test.py --html=./testreport.html

描述:测试报告,提前安装:pip install pytest-html

8. pytest test.py pytest-randomly

描述:顺序随机测试,提前安装:pip install pytest-randomly

9. 分布式并发测试用例集

pip install pytest-xdist 或 pip install pytest-parallel

备注:pytest-parallel比pytst-xdist好用些。pytest-parallel支持python3.6及以上版本,如果是想做多进程并发的需要在linux平台或mac上做,如果是做多线程的可以再windows平台做

    –workers (optional)  * :多进程运行需要加此参数,  *是进程数。默认为1。

    –tests-per-worker (optional)  * :多线程运行, *是每个worker运行的最大并发线程数。默认为1

实例:

pytest test.py --workers 3:3个进程运行
pytest test.py --tests-per-worker 4:4个线程运行
pytest test.py --workers 2 --tests-per-worker 4:2个进程并行,且每个进程最多4个线程运行,即总共最多8个线程运行。

10. 出错立即返回:pip install pytest-instafail

11. 集成jenkins的junit报告:不用安装pytest已经集成了,使用命令:pytest --junitxml=path

实例:

pytest test.py --reruns 3 --html=./testreport.html --junitxml=xmlreport.xml

此时则执行完用例后,在本地目录生成testreport.html的测试报告,和xmlreport.xml的junit格式报告在jenkins中可调用展示。

12. python -m pytest test.py

备注:使用python执行的,可以顺便把当前目录加入到sys.path中,即环境变量

13. pytest退出码汇总

根据官方说法,提供了6种,分别如下:
    Exit code 0: 所有用例执行成功后则返回0
    Exit code 1: 所有用例执行后,有部分失败则返回1
    Exit code 2: 测试执行时被用户中断
    Exit code 3: 执行测试时发生内部错误
    Exit code 4: pytest 命令行使用错误
    Exit code 5: 没有收集到测试结果
    备注:如果是要自定义退出码,则需要配合插件:pytest-custom_exit_code

14. 运行用例遇到失败就停止

pytest -X test.py #遇到用例失败就停止,后面到不执行

pytest --maxfail=2 test.py #遇到第2哥用例失败就停止,后面第不执行

原文地址:https://www.cnblogs.com/helloTerry1987/p/10961522.html