test label
Use decorator: @pytest.mark. Custom label name
@pytest.mark.add
def test_add():
result = 1 + 2
assert result == 3
to parameterize
Use decorators: @pytest.mark.parametrize("parameter name", list)
@pytest.mark.parametrize("parameter name, parameter name...", [(parameter, parameter...), (parameter, parameter...)], ids=[use case name, use case name...])
Each set of test data is a tuple, and the data in the tuple corresponds to the parameters one by one. ids can define a name for each group of use cases, and a name will be automatically generated if it is left blank.
@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
Cartesian Product
The full combination of two sets x * y
@pytest.mark.parametrize("a", [1,2,3])
@pytest.mark.parametrize("b", [1,2,3])
def test_a(a, b):
pass
skip use case
1. Add a decorator
@pytest.mark.skip(reason="skip reason") or @pytest.mark.skipif(skip condition, reason="skip reason")
skip is always skipped, reason is not a necessary parameter. skipif is to skip when the condition is met, and reason is a required parameter. Displayed when a use case is skipped: 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. Add skip code to the code
pytest.skip("Skip 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
if a == 1:
pytest.skip("第一个参数为1时跳过")
assert round(result, 2) == expect
Expected failure use cases
1. Add a decorator
@pytest.mark.xfail(reason="Expected failure reason").
reason is an optional parameter. When the use case passes, it displays: XPASS, and when it fails, it displays: 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. Add the expected failure code to the code
pytest.xfail("Expected failure 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
if type(a) != int:
pytest.xfail("第一个参数必须为整型")
assert round(result, 2) == expect
Handling exception use cases
Use pytest.raises() to catch exceptions and assert exceptions to make the test case pass.
def test_error():
with pytest.raises(ZeroDivisionError) as e:
2 / 0
assert e.typename == "ZeroDivisionError"
The usage is the same as try...except in python
def test_error2():
try:
2 / 0
except ZeroDivisionError as e:
assert e.args == ('division by zero',)