Mark主要用于在测试用例/测试类中给用例打标记,实现测试分组功能,并能和其它插件配合设置测试方法执行顺序等。
在实际工作当中,我们要写的自动化用例会比较多,而且不会都放在一个.py文件里。
如下图,现在需要只执行红色部分的测试方法,其它方法不执行。

在Pytest当中,先给用例打标记,在运行时,通过标记名来过滤测试用例。
步骤:
@pytest.mark.标签名标记在需要执行的用力上。(标签名自定义)pytest 测试套件名 -m 标签名示例:
# 如:在test_01.py文件的testa()方法上进行mark标识。@pytest.mark.hellotestdef test_a(): """购物下单""" print("test_01文件的函数a") assert True# 其他两个文件中的方法同理。执行命令,查看结果:
if __name__ == '__main__': pytest.main(["-vs", "-m", "hellotest"])# 同理也可以用命令行的方式执行。"""执行结果:test_01.py::test_a test_01文件的函数aPASSEDtest_02.py::test_b test_02文件的函数bPASSEDtest_03.py::test_a test_03文件的函数aPASSED3 passed, 3 deselected, 3 warnings说明:3个用例通过,3个用例没有选择,有3个警告"""这样就简单的实现了Mark标记的使用,但是我们在工作中不这样用,我们需要把Mark标记进行注册。
Mark标签官方提供的注册方式有2种,这里只提供一种最简单直接的方式:
通过pytest.ini配置文件注册。
在pytest.ini文件当中配置:
[pytest] # 固定的section名markers= # 固定的option名称,注意缩进。 标签名1: 标签名的说明内容。 标签名2: 不写也可以 标签名N示例:还是上面的练习。
pytest.ini配置文件内容如下:
[pytest]addopts = -vstestpaths = scriptspython_files = test*python_classes = Test*python_functions = test*markers= hellotest: Mark Description smoke执行命令,查看结果:
if __name__ == '__main__': pytest.main(["-m", "hellotest"])"""执行结果:test_01.py::test_a test_01文件的函数aPASSEDtest_02.py::test_b test_02文件的函数bPASSEDtest_03.py::test_a test_03文件的函数aPASSED3 passed, 3 deselected, 说明:3个用例通过,3个用例没有选择,没有警告了。"""只执行test_01.py文件中的测试用例:
import pytest@pytest.mark.hellotestdef test_a(): """购物下单""" print("test_01文件的函数a") assert True@pytest.mark.Fail_retrydef test_b(): """购物下单""" print("test_01文件的函数b") assert Falseif __name__ == '__main__': pytest.main(["-m", "Fail_retry"])"""执行结果:test_01.py::test_b test_01文件的函数bRERUNtest_01.py::test_b test_01文件的函数bRERUNtest_01.py::test_b test_01文件的函数bFAILED1 failed, 1 deselected, 2 rerun说明:1个失败,1个取消选择,2次重跑用例"""下面是pytest.ini配置文件内容:
[pytest]addopts = -vs --reruns 2(配置重跑两次)testpaths = scriptspython_files = test_01.pypython_classes = Test*python_functions = test*markers= hellotest: Mark Description Fail_retry:1)多个Mark标签可以用在同一个用例上。
@pytest.mark.hello@pytest.mark.worlddef test_a(): """购物下单""" print("test_01文件的函数a") assert True2)Mark标签也可以用到测试类上。
@pytest.mark.helloclass Test_Mark: @pytest.mark.world def test_a(self): """购物下单""" print("test_01文件的函数a") assert True工作中的使用场景:冒烟测试,分模块执行测试用例,分接接口执行测试用例等。
参考:
- https://www.cnblogs.com/ritaliu/p/13524588.html
- https://www.cnblogs.com/xingyunqiu/p/11734226.html