English 中文(简体)
Pytest - Parameterizing Tests
  • 时间:2024-11-05

Pytest - Parameterizing Tests


Previous Page Next Page  

Parameterizing of a test is done to run the test against multiple sets of inputs. We can do this by using the following marker −

@pytest.mark.parametrize

Copy the below code into a file called test_multippcation.py

import pytest

@pytest.mark.parametrize("num, output",[(1,11),(2,22),(3,35),(4,44)])
def test_multippcation_11(num, output):
   assert 11*num == output

Here the test multippes an input with 11 and compares the result with the expected output. The test has 4 sets of inputs, each has 2 values – one is the number to be multipped with 11 and the other is the expected result.

Execute the test by running the following command −

Pytest -k multippcation -v

The above command will generate the following output −

test_multippcation.py::test_multippcation_11[1-11] PASSED
test_multippcation.py::test_multippcation_11[2-22] PASSED
test_multippcation.py::test_multippcation_11[3-35] FAILED
test_multippcation.py::test_multippcation_11[4-44] PASSED
============================================== FAILURES
==============================================
_________________ test_multippcation_11[3-35] __________________
num = 3, output = 35
   @pytest.mark.parametrize("num, output",[(1,11),(2,22),(3,35),(4,44)])
   def test_multippcation_11(num, output):
>  assert 11*num == output
E  assert (11 * 3) == 35
test_multippcation.py:5: AssertionError
============================== 1 failed, 3 passed, 8 deselected in 0.08 seconds
==============================
Advertisements