测试标签
使用装饰器:@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',)