对应的视频教程:https://www.bilibili.com/video/BV1py4y1t7bJ?p=4
# 默认规则
- 模块名必须以 test_开头或者_test 结尾
- 测试类必须以 Test 开头,并且不能有 init 方法
- 测试方法必须以 test 开头
# 运行方式
- 主函数模式
- 命令行模式
- 通过读取 pytest.ini 配置文件运行
# 主函数模式
test_login.py | import pytest |
| |
| |
| class Test_login: |
| |
| def test_C001001(self): |
| print('\ncaseC001001') |
| assert 1 == 1 |
| |
| |
| if __name__ == "__main__": |
| pytest.main() |
注:
pytest.main()
默认会执行目录下所有的测试用例,即使测试类在别的模块中,也会被执行
| pytest.main('-vs', '模块路径::类名::方法名') |
# 命令行模式
# 配置文件
pytest.ini
是 pytest 单元测试框架的核心配置文件
- 位置:一般放在项目的根目录
- 编码:必须是 ANSI
- 作用:改变 pytest 默认的行为
- 机制:不管是主函数模式、命令行模式,都会读取这个文件
pytest.ini | [pytest] |
| addopts = -vs |
| testpaths = ./testcase |
| python_files = test_*.py |
| python_classes = Test* |
| python_functions = test |
| markers = |
| smoke: 冒烟用例 |
| usermanage: 用户管理模块 |
# 可用参数
参数 | 说明 |
---|
-s | 表示输出调试信息,包括 print 的内容 |
-v | 输出详细信息 |
-n 线程数 | 支持多线程或者分布式运行测试用例 |
--reruns = 重跑次数 | 设置失败后重跑 |
-x | 只要有一个失败,测试停止 |
--maxfail n | 失败次数达到 n 时,停止测试 |
-k | 根据测试用例的部分字符串指定测试用例 |
# 执行顺序
pytest 默认是从上到下执行,指定顺序需要 pytest-ordering
| |
| @pytest.mark.run(order=n) |
# 分组执行