Pytest - 参数化测试

  • 简述

    完成测试的参数化以针对多组输入运行测试。我们可以通过使用以下标记来做到这一点 -
    
    @pytest.mark.parametrize
    
    将以下代码复制到名为test_multiplication.py
    
    import pytest
    @pytest.mark.parametrize("num, output",[(1,11),(2,22),(3,35),(4,44)])
    def test_multiplication_11(num, output):
       assert 11*num == output
    
    这里测试将输入乘以 11,并将结果与​​预期输出进行比较。该测试有 4 组输入,每组有 2 个值——一个是要乘以 11 的数字,另一个是预期结果。
    通过运行以下命令执行测试 -
    
    Pytest -k multiplication -v
    
    上述命令将生成以下输出 -
    
    test_multiplication.py::test_multiplication_11[1-11] PASSED
    test_multiplication.py::test_multiplication_11[2-22] PASSED
    test_multiplication.py::test_multiplication_11[3-35] FAILED
    test_multiplication.py::test_multiplication_11[4-44] PASSED
    ============================================== FAILURES
    ==============================================
    _________________ test_multiplication_11[3-35] __________________
    num = 3, output = 35
       @pytest.mark.parametrize("num, output",[(1,11),(2,22),(3,35),(4,44)])
       def test_multiplication_11(num, output):
    >  assert 11*num == output
    E  assert (11 * 3) == 35
    test_multiplication.py:5: AssertionError
    ============================== 1 failed, 3 passed, 8 deselected in 0.08 seconds
    ==============================