【Pytest】常用装饰器

本文介绍了如何使用Pytest的装饰器进行测试管理,包括自定义标签、参数化测试、生成笛卡尔积、跳过和预期失败的用例以及处理异常。通过@pytest.mark.parametrize进行参数化测试,@pytest.mark.skipif和@pytest.mark.xfail来标记预期失败和跳过的测试。同时展示了如何捕获和断言异常。
摘要由CSDN通过智能技术生成

测试标签

使用装饰器:@pytest.mark.自定义标签名

@pytest.mark.add
def test_add():
    result = 1 + 2
    assert result == 3

参数化

使用装饰器:@pytest.mark.parametrize("参数名", list)

@pytest.mark.parametrize("参数名, 参数名…", [(参数, 参数…), (参数, 参数…)], ids=[用例名, 用例名…])

每组测试数据为一个元组,元组中的数据和参数一一对应。ids可以为每组用例定义名称,不填时会自动生成一个名称。

@pytest.mark.add
@pytest.mark.parametrize("a,b,expect", [(1, 2, 3), (2.2, 4.8, 7)], ids=["加法1", 2])
def test_add(a, b, expect):
    result = a + b
    assert round(result, 2) == expect

笛卡尔积

两个集合x * y的全组合方式

@pytest.mark.parametrize("a", [1,2,3])
@pytest.mark.parametrize("b", [1,2,3])
def test_a(a, b):
    pass

跳过用例

1.添加装饰器

@pytest.mark.skip(reason="跳过原因")或者@pytest.mark.skipif(跳过条件,reason="跳过原因")

skip为始终跳过,reason非必要参数。skipif为满足条件时跳过,reason为必要参数。用例被跳过时显示:SKIPPED。

@pytest.mark.skipif(condition=True, reason="始终跳过")
@pytest.mark.add
@pytest.mark.parametrize("a,b,expect", [(1, 2, 3), (2.2, 4.8, 7)], ids=["加法1", 2])
def test_add(a, b, expect):
    result = a + b
    assert round(result, 2) == expect

2.代码中添加跳过代码

pytest.skip("跳过原因")

@pytest.mark.add
@pytest.mark.parametrize("a,b,expect", [(1, 2, 3), (2.2, 4.8, 7)], ids=["加法1", 2])
def test_add(a, b, expect):
    result = a + b
    if a == 1:
        pytest.skip("第一个参数为1时跳过")
    assert round(result, 2) == expect

预期失败用例

1.添加装饰器

@pytest.mark.xfail(reason="预期失败原因")。

reason非必要参数。用例通过时显示:XPASS,失败时显示:XFAIL。

@pytest.mark.xfail(reason="数据类型错误")
@pytest.mark.add
@pytest.mark.parametrize("a,b,expect", [(1, 2, 3), (2.2, "1", 7)], ids=["加法1", 2])
def test_add(a, b, expect):
    result = a + b
    assert round(result, 2) == expect

2.代码中添加预期失败代码

pytest.xfail("预期失败原因")

@pytest.mark.add
@pytest.mark.parametrize("a,b,expect", [(1, 2, 3), (2.2, 4.8, 7)], ids=["加法1", 2])
def test_add(a, b, expect):
    result = a + b
    if type(a) != int:
        pytest.xfail("第一个参数必须为整型")
    assert round(result, 2) == expect

处理异常用例

使用pytest.raises()捕获异常,断言异常使得测试用例通过。

def test_error():
    with pytest.raises(ZeroDivisionError) as e:
        2 / 0
    assert e.typename == "ZeroDivisionError"

 用法和python中的try…except一样

def test_error2():
    try:
        2 / 0
    except ZeroDivisionError as e:
        assert e.args == ('division by zero',)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值