📜  Pytest-参数化测试

📅  最后修改于: 2020-11-06 05:21:56             🧑  作者: Mango


完成测试的参数化以针对多组输入运行测试。我们可以通过使用以下标记来做到这一点-

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