Pytest常用装饰器使用

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

在UI自动化测试过程中会使用到pytest相关装饰器,本文主要介绍自己工作过程中使用到的装饰器

设置跳过用例用于函数体外,可用于标注功能暂未实现的用例

import pytest
@pytest.mark.skip(reason="测试跳过")
def test001():
    print('test001')
def test002():
    print('test002')
pytest.main()

用例执行过程中若条件不成立时跳出当前用例,用于函数体内

import pytest
def test001():
    if 2 > 1:
        pytest.skip("条件成立")
    print('test001')
pytest.main()

根据条件跳过用例,用于类方法和具体函数,可以用于归类用例,限定条件来执行对应用例数据

import pytest
condition='monica'
@pytest.mark.skipif(condition=='monica',reason='测试跳过')
def test002():
    print('test002')
pytest.main()

该方法主要用到某些场景bug未修复或者用例存在问题可以直接标注为失败状态

import pytest
@pytest.mark.xfail(reason='测试标注失败')
def test001():
    print('用例1')
def test002():
    print('用例2')
pytest.main()

设置用例执行顺序,数字越小优先执行

import pytest
#pytest装饰器
@pytest.mark.run(order=1)
def test002():
    print('用例2')
@pytest.mark.run(order=2)
def test001():
    print('用例1')
pytest.main()
#1.参数名为str类型,多个属性用逗号隔开,一个key对应list对象中的一个value,且list中可以嵌套list、tuple
#2.若存在多个属性和值时,用例会自动执行多次不用人为通过for循环遍历测试数据,且方法的入参个数要与装饰器中
#参数个数一致否则报错
import pytest
#传入单个值
@pytest.mark.parametrize('user',[1])
def test001(user):
    print(user)
#多个属性值
@pytest.mark.parametrize('user,name',[[1,2]])
def test002(user,name):
    print(user)
    print(name)
#多个属性值对应多个值
@pytest.mark.parametrize('user,name,age',[['monica1','monica2',18],('monica4','monica5',19)])
def test003(user,name,age):
    print(user,name,age)
#测试数据也可以作为一个变量传入
data=   [['monica1','monica2',18],('monica4','monica5',19)]
@pytest.mark.parametrize('user,name,age',data)
def test004(user,name,age):
    print(user,name,age)
if __name__ == '__main__':
    pytest.main(["-vs"])

Original: https://blog.csdn.net/tianheihei__/article/details/125529500
Author: Monica_ll
Title: Pytest常用装饰器使用

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/773955/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球