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
==============================