微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Pytest之自定义mark

一个完整的项目,测试用例比较多,比如我们想将某些用例用来做冒烟测试,那该怎么办呢?pytest中可以自定义配置文件,用例按照指定的方式去运行。

 

配置文件

 

 

 

1定义配置文件

 

在项目根目录下,创建一个文件:pytest.ini (固定名称,不要修改)。

 

 

2配置文件格式pytest.ini 
[pytest]
markers =
    demo: just for demo
    smoke

① 案例一:

之前在讲解用例被标记为@pytest.mark.xfail时,如果用例运行通过,显示XPASS。

test_demo.py

@pytest.mark.xfail()
def test_demo02():
    print("这是test_demo02")
    assert 1 == 1

 

配置文件中未配置xfail_strict = True时,运行结果如下:

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

 

在pytest.ini 中加上xfail_strict = True配置后

运行结果为:

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

 

② 案例二:addopts

addopts参数可以更改认命令行选项,省去手动敲命令行参数。

比如命令行想输出详细信息、分布式执行或最大失败次数,每次敲命令很麻烦,在配置里设置,以后命令直接输入pytest即可。

现有如下用例:

test_demo.py

def test_demo01():
    print("这是test_demo01")
    assert 1 == 2
def test_demo02():
    print("这是test_demo02")

 

如果需要输出信息更详细、输出调试信息及用例执行错误时立即退出,那么配置如下:

[pytest]
markers =
    demo: just for demo
    smoke
addopts = -v -s -x

 

命令行输入:pytest

输出结果为:

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

 

 

 

测试用例执行实战

 

比如我想从众多用例中挑选出部分用例,作为冒烟测试用例,怎么配置呢?

 

pytest.ini

[pytest]
markers =
    demo: just for demo
    smoke

其中smoke为标签,用例前加上标签名smoke,即都属于冒烟测试用例。

 

 

1模块级别

 

在模块里加上标签,那么该模块下的类、方法函数都会带上标签

test_demo.py

import pytest
pytestmark = pytest.mark.smoke
class TestDemo:
    def test_demo01(self):
        print("这是test_demo01")
    def test_demo02(self):
        print("这是test_demo02")
    def test_demo03(self):
        print("这是test_demo03")

 

命令行输入:pytest -v -m smoke。

输出结果为:

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

 

2类级别

在类上添加标签,则类下的所有方法都带上标签

test_demo.py

import pytest
@pytest.mark.smoke
class TestDemo:
    def test_demo01(self):
        print("这是test_demo01")
    def test_demo02(self):
        print("这是test_demo02")
    def test_demo03(self):
        print("这是test_demo03")
def test_demo04():
    print("这是test_demo04")

 

在命令行输入:pytest -v -m smoke test_demo.py

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

 

 

3函数级别

函数添加标签,那么此函数带上标签

test_demo.py

import pytest
class TestDemo:
    def test_demo01(self):
        print("这是test_demo01")
    def test_demo02(self):
        print("这是test_demo02")
    def test_demo03(self):
        print("这是test_demo03")
@pytest.mark.smoke
def test_demo04():
    print("这是test_demo04")

 

命令行输入:pytest -v -m smoke test_demo.py

输出结果为:

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐