0
点赞
收藏
分享

微信扫一扫

pytest之【mark标记功能】使用实例以及使用原理(pytest钩子函数之pytest_configure)

weednoah 2022-06-17 阅读 82

前言

①使用 @pytest.mark.标签名 装饰器可以将测试用例分类。

②pytest测试框架中的内置mark标签

@pytest.mark.skip()  跳过用例
@pytest.mark.skipif() 满足条件跳过用例
@pytest.mark.parametrize() 实现参数化
@pytest.mark.usefixture() 使用fixture的函数
@pytest.mark.xfail() 标记失败

③终端以命令行方式运行测试用例或者通过python模块中的main函数运行测试用例,例如:

pytest test_1.py -s -m='p0'  #  只运行p0用例
pytest test_1.py -s -m='p0 or p1' # 运行p0和p1用例
pytest test_1.py -s -m='not p0' # 只运行非p0用例
if __name__ == '__main__':
pytest.main(['-s', 'test_1.py',"-m=not runtest"])

其中:

运行的时候使用 -m 参数;m是mark的意思,来运行某个或某个分类的测试用例;

 -m 参数同样支持python表达式:用or实现多选的效果;用not实现反选的效果。

使用方法

1、注册标签名

2、在测试用例/测试类前面加上: @pytest.mark.标签名 ;打标记范围:【测试用例,测试类,测试模块】

3、用例执行

注册方式:将自定义标签名注册到pytest测试框架中,pytest可以识别出注册后的标签名然后进行相应操作

1、单个标签

在conftest.py添加如下代码:

def pytest_configure(config):
# demo是标签名
config.addinivalue_line("markers", "demo:示例运行")

2、多个标签

在conftest.py添加如下代码:

def pytest_configure(config):

marker_list = ["testdemo", "demo", "smoke"] # 标签名集合
for markers in marker_list:
config.addinivalue_line("markers", markers)

或者:

import pytest
def pytest_configure(config):

config.addinivalue_line("markers", "slow:this one of slow test")
config.addinivalue_line("markers", "fast:this one of fast test")

3、添加pytest.ini 配置文件

参照:​pytest之配置文件pytest.ini

[pytest]
markers=
smoke:this is a smoke tag
demo:demo
testdemo:testdemo

用例执行

test_demo.py

import pytest


@pytest.mark.testdemo
def test_demo01():
print("函数级别的test_demo01")


@pytest.mark.smoke
def test_demo02():
print("函数级别的test_demo02")


@pytest.mark.demo
class TestDemo:
def test_demo01(self):
print("test_demo01")

def test_demo02(self):
print("test_demo02")

1、命令行方式

pytest命令行运行方式如下:

通过标记表达式执行
pytest -m demo
这条命令会执行被装饰器@pytest.mark.demo装饰的所有测试用例

生成html报告:
pytest -m demo --html=Report/report.html

生成xml报告:
pytest -m demo --junitxml=Report/report.xml

运行指定模块:
pytest -m demo --html=Report/report.html TestCases/test_pytest.py

运行指定测试目录
pytest -m demo --html=Report/report.html TestCases/

通过节点id来运行:
pytest TestCases/test_pytest.py::TestDemo::test_demo01

通过关键字表达式过滤执行
pytest -k "MyClass and not method"
这条命令会匹配文件名、类名、方法名匹配表达式的用例

获取用例执行性能数据
获取最慢的10个用例的执行耗时
pytest --durations=10

2、新建run.py文件运行

代码如下:

pytest.main(["-m","demo","--html=Report/report.html"])

 

去期待陌生,去拥抱惊喜。

举报

相关推荐

0 条评论