pytest框架中 装饰器的用法

跳过

#  直接跳过
@pytest.mark.skip(reason="The test case)
def test_one():
    print(“test_one”)

#  条件跳过 condition 为跳过条件,例:1==1 跳过 1!=1时执行
@pytest.mark.skipif(condition="1==1", reason='The test case')
def test_7():
    print("test_7")

if __name__ == "__main__":
    pytest.main(["-s", "test.py"])

参数化

1、传一个参数时

@pytest.mark.parametrize("a", [1])
def test_2(a):
    if a < 2:
        print(a)

#  值多时,会循环执行所有
@pytest.mark.parametrize("a", [1, 2, 3])
def test_2(a):
    if a < 2:
        print(a)

2、多个参数时

@pytest.mark.parametrize("a, b, c", [[1, 2, 3], [4, 5,6], [7, 8, 9]])
def test_2(a, b, c):
    if a < b:
        print('\n-----------------')
        print(a, b)
    elif a < c:
        print(a + c)
    elif a+b < c:
        print(c)


if __name__ == "__main__":
    pytest.main(["-s", "test_new.py"])

value = [[1, 2, 3], [4, 5,6], [7, 8, 9]]

@pytest.mark.parametrize("a, b, c", value)
def test_2(a, b, c):
    if a < b:
        print('\n-----------------')
        print(a, b)
    elif a < c:
        print(a + c)
    elif a+b < c:
        print(c)


if __name__ == "__main__":
    pytest.main(["-s", "test_new.py"])

条件判断 “预期失败”

#  condition 条件相等判断失败
@pytest.mark.xfail(condition='1==1', reason="The test case")
def test_1():
    print("\n-------")

#  condition 条件不等判断成功
@pytest.mark.xfail(condition='1==2', reason="The test case")
def test_2():
    print("\n-------")

数据继承

@pytest.fixture()
def test1():
    a = '测试数据的继承1'
    return a


def test2(test1, test3):
    print(test1, test3)


@pytest.fixture()
def test3():
    return "测试数据的继承2"


if __name__ == "__main__":
    pytest.main(["-s", "test_new.py"])

执行顺序设定

安装插件: pytest-ordering

# 全是正数的话,越小越先执行,比如order=3, 2, 1的话,order为1的先执行
# 都是负数的话,值越小越先执行
# 0和负数的话,0先执行,剩下的数值越小越先执行;0和正数的话,0先执行,剩下的数越小越先执行
# 0 正数 负数,0先执行,正数再执行,负数最后
# 顺序:0 ---> 较小的正数 ---> 较大的正数 ---> 较小的负数 ---> 较大的负数

@pytest.mark.run(order=3)
def test1():
    print('\n测试数据3')


@pytest.mark.run(order=2)
def test2():
    print('\n测试数据2')


@pytest.mark.run(order=4)
def test3():
    print('\n测试数据4')


if __name__ == "__main__":
    pytest.main(["-s", "test_new.py"])

失败后二次执行

安装插件:pytest-rerunfailures


#  reruns 设置失败后反复执行的次数
#  reruns_delay  设置每次执行间隔的时间
#  执行成功,反复停止
@pytest.mark.flaky(reruns=5, reruns_delay=1)
def test3():
    print("\n执行")
    assert 1 == 2


if __name__ == "__main__":
    pytest.main(["-s", "test_new.py"])
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值