API文档地址:API Reference — pytest documentation
命名规则
- 文件名需以test_开头或者_test结尾
- 类名需以 Test开头
- 方法需以test开头
若不按照命名规则,使用pytest一次性运行多个用例时,不按照命名规则的文件/case将被跳过
运行顺序与运行命令
- 默认执行顺序:文件之间按照ASCII顺序,0~9——>A~Z——>a~z,文件内的用例为从上往下执行
- 使用某些插件可以改变文件执行顺序:pytest-ordering,或者随机pytest-random-ordering
- 退出码:当case运行完成后,控制台打印出运行信息,最终有总结退出码是什么,例如exit code为0
有case失败时,exit code为1,当使用脚本运行完成后,命令行中执行echo $?可以查看对应exit code的执行情况。
Exit code 0
All tests were collected and passed successfully
Exit code 1
Tests were collected and run but some of the tests failed
Exit code 2
Test execution was interrupted by the user(执行时使用Crtl+C中断执行)
Exit code 3
Internal error happened while executing tests(脚本中有内部错误)
Exit code 4
pytest command line usage error(执行的命令行参数错误)
Exit code 5
No tests were collected(没有test被执行)
- pytest -x:当第一个用例失败后直接停止;pytest --maxfail=2:当两个用例执行失败后再停止
- pytest还可以指定目录、模块、类、方法,根据名字、标签运行用例
- 指定目录:pytest 目录
- 指定模块:pytest 目录/模块
- 指定类:pytest 目录/模块::类
- 指定方法:pytest 目录/模块::类::方法
- 根据名字:pytest -k 名字
- 不包含xx:pytest -k "not xxx"
- xx与xx:pytest -k "xx and xx"
- xx或xx:pytest -k "xx or xx"
- 根据标签:在方法上添加装饰器:@pytest.mark.webtes(标签名)。执行:pytest -m webtest
- PDB:pytest内置的调试,pytest --pdb命令当test失败时进入PDB调试模式,但需要在控制台输入命令进行调试,建议直接使用断点调试。
- 调用python的命令执行Pytest,pytest.main(['param1','param2','path'])
- pytest -v:输出更详细的用例执行信息