前提
pytest是一个非官方的单元测试框架,需要先进行安装。所以pip一下
技术点
一、运行参数(进入到相应目录)
1、无参数运行
pytest运行命名规则:运行时查找当前目录下及子目录下的以 test_*.py 或者 *_test.py为标识的文件,文件中的内容只运行test开头的函数或类
运行目录下的所有py文件:pytest
运行目录下某一个py文件:pytest test_01.py
运行目录下py文件中的某个类:pytest test_02.py::TestClass
运行目录下py文件中某个类的某个方法:pytest test_02.py::TestClass::test_one
指定目录运行:pytest testpy
2、-v参数
打印详细的日志信息
3、-s参数
代码里面有 print 输出语句,想在运行结果中打印 print 输出
-v 和-s 可以写在一块 -sv
4、-k参数
pytest -k '类名' //运行指定的类
pytest -k '方法名' //运行指定的方法
pytest -k '类名 and not 方法名' //运行类里的方法,不包含某个方法
pytest -k “test_demo1 or test_demo2” //执行test_demo1 和 test_demo2
5、-x参数
遇到失败用例立即停止运行
6、--maxfail参数
用例失败个数达到阀值后停止运行
pytest --maxfail 2 test_02.py
7、-m参数 分组
只运行标记 @pytest.mark.[标记名] 的方法和类
比如类名上添加:@pytest.mark.oneone,
执行命令:pytest -m "oneone" test_02.py
如果有多个标记可以用 and 或 or 进行组合
1 import pytest
2
3 def inc(x):
4 return x + 1
5
6 class TestPytest:
7 def setup(self):
8 print("setup")
9
10 @pytest.mark.success
11 def test_demo_1(self):
12 assert inc(4) == 5
13
14 @pytest.mark.fail
15 def test_demo_2(self):
16 assert inc(3) == 5
17
18 def teardown(self):
19 print("teardown")
1 仅执行标记为success的用例,以下两种写法均可以:
2 pytest -m "success and not fail" test_pytest.py
3 pytest -m "success" test_pytest.py
8、--durations参数
获取执行最慢的一个:pytest --durations=1
9、--collect-only参数
只收集用例不执行,可用于统计用例数
10、-q参数
只显示用例执行结果
二、pytest前置和后置
1 import pytest
2
3 def setup_module():
4 print("\nsetup_module,一个py文件只执行一次,不管该py文件中有多少方法和类")
5 def teardown_module():
6 pri