- Pytest - Home
- Pytest - Introduction
- Pytest - Environment Setup
- Identifying Test files and Functions
- Pytest - Starting With Basic Test
- Pytest - File Execution
- Execute a Subset of Test Suite
- Substring Matching of Test Names
- Pytest - Grouping the Tests
- Pytest - Fixtures
- Pytest - Conftest.py
- Pytest - Parameterizing Tests
- Pytest - Xfail/Skip Tests
- Stop Test Suite after N Test Failures
- Pytest - Run Tests in Parallel
- Test Execution Results in XML
- Pytest - Summary
- Pytest - Conclusion
Pytest useful Resources
Pytest - Parameterizing Tests
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_multiplication.py −
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
Here the test multiplies 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 multiplied with 11 and the other is the expected result.
Execute the test by running the following command −
pytest -k multiplication -v
The above command will generate the following output −
============================ test session starts ================================
platform win32 -- Python 3.14.2, pytest-9.0.2, pluggy-1.6.0
-- C:\Users\mahes\AppData\Local\Programs\Python\Python314\python.exe
cachedir: .pytest_cache
rootdir: D:\Projects\python\myenv\automation
collected 12 items / 8 deselected / 4 selected
test_multiplication.py::test_multiplication_11[1-11] PASSED [ 25%]
test_multiplication.py::test_multiplication_11[2-22] PASSED [ 50%]
test_multiplication.py::test_multiplication_11[3-35] FAILED [ 75%]
test_multiplication.py::test_multiplication_11[4-44] PASSED [100%]
============================ 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
============================ short test summary info ==============================
FAILED test_multiplication.py::test_multiplication_11[3-35] - assert (11 * 3) == 35
============================ 1 failed, 3 passed, 8 deselected in 0.08s ============
Advertisements