当前位置: 首页> 技术文章> Pytest 单元测试框架之标记用例

Pytest 单元测试框架之标记用例

1、Pytest 中标记用例

  • 接参数 -k 来挑选要执行的测试项

    • test_szdcs 为函数名称

    • pytest -k test_szdcs -s

    • -k 后面接的名称可以为函数名称、类名称、文件名称、目录名称

    • 区分大小写

    • 支持模糊匹配

    • 可以用 not 表示选择用例名称中不包含哪些内容,如下

class Test01():
    def test_szdcs(self):
        print("深圳多测师")
    def test_gzdcs(self):    
        print("广州多测师")class Test02():
    def test_shdcs(self):    
        print("上海多测师")
# 运行命令    
pytest -k "not sz" -s
# 结果如下
test_demo1.py 
广州多测师.
上海多测师.

    • 可以用 and 表示选择的用例名称中同时包含多个关键字,如下

class Test01():
    def test_szdcs(self):    
        print("深圳多测师")    
    def test_gzdcs(self):    
        print("广州多测师")
class Test02():
    def test_shdcs(self):    
        print("上海多测师")
# 运行命令    
pytest -k "g and z" -s
# 结果如下
test_demo1.py 
广州多测师.

    • 可以用 or 表示选择的用例名称中包含其中一个关键字即可,如下

class Test01():
    def test_szdcs(self):        
        print("深圳多测师")    
    def test_gzdcs(self):    
        print("广州多测师")
class Test02():
    def test_shdcs(self):    
        print("上海多测师")# 运行命令        
pytest -k "sh or sz" -s
# 结果如下
test_demo1.py 
深圳多测师.
上海多测师.
  • 指定标签运行需要运行的测试项

    • pytest 后面可以接类名称、文件名称、目录名称

    • -m 后面接标签名称

    • tag 为自定义的标签名称

    • 可以对方法加上标签

    • 也可以对整个类加上标签

    • 也可以定义全局标签

    • @pytest .mark.tag

    • pytest test_demo1.py -m tag -s

# 对方法加标签
import pytest
class Test01():
    def test_szdcs(self):    
        print("深圳多测师")

    @pytest.mark.tag        # 通过装饰器定义标签,自定义标签名称 tag
    def test_gzdcs(self):    
        print("广州多测师")
class Test02():
    def test_shdcs(self):    
        print("上海多测师")# 运行命令         
pytest test_demo1.py -m tag -s
# 结果如下
test_demo1.py 
广州多测师.
# 对类加标签
import pytest
class Test01():
    def test_szdcs(self):   
        print("深圳多测师")    
    def test_gzdcs(self):    
        print("广州多测师")

@pytest.mark.tag
class Test02():
    def test_shdcs(self):    
        print("上海多测师")
# 运行命令         
pytest test_demo1.py -m tag -s
# 结果如下
test_demo1.py 
上海多测师.
import pytest
# 定义全局标签
mark = pytest.mark.tag
class Test01():
    def test_szdcs(self):    
        print("深圳多测师")    
def test_gzdcs(self):    
    print("广州多测师")
class Test02():
    def test_shdcs(self):    
        print("上海多测师")
# 运行命令        
pytest -m tag -s
# 结果如下
test_demo1.py 
深圳多测师.
广州多测师.
上海多测师.


上一篇: Jmeter中传递cookie值

下一篇: 软件测试之手工测试人员如何转测试开发?

QQ技术交流群

多测师官方学习交流
556733550

加入群聊