parametrize
- Python course
- Advanced
- Lesson 16/83
- 5 min
Learn parameterized tests with @pytest.mark.parametrize.
parametrize
@pytest.mark.parametrize runs the same test with different data. A single test function is automatically repeated for many inputs.
import pytest
@pytest.mark.parametrize("a,b,expected", [
(1, 2, 3),
(10, 5, 15),
(-1, 1, 0),
])
def test_add(a, b, expected):
assert add(a, b) == expectedEach triple runs as a separate test. If one fails, pytest shows which data caused it. Ideal for data-driven testing.
Data-driven testing
With parametrize you gather many edge cases in one test. Each row is a test case; the first string is parameter names, the list is data tuples.
Example: with names "n,expected" and data [(0, 0), (1, 1), (5, 25)], the test runs three times; n and expected are bound each time.
This approach saves you from writing repeated test functions; one failure reveals the whole dataset.
Practice square test with parametrize
The function square(n) returns n * n. Decorate test_square with @pytest.mark.parametrize; first string "n,expected", second argument [(2, 4), (3, 9), (4, 16)]. The test body contains assert square(n) == expected. At the end call test_square(2, 4); test_square(3, 9); print("ok").
Starter code
import pytest
# square(n): return n squared
# test_square: use parametrize with two cases
# body compares square(n) with expected
# finally test_square(2, 4); test_square(3, 9); print("ok")Sample solution
import pytest
def square(n):
return n * n
@pytest.mark.parametrize("n,expected", [(2, 4), (3, 9), (4, 16)])
def test_square(n, expected):
assert square(n) == expected
test_square(2, 4)
test_square(3, 9)
print("ok")Expected output
ok
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add the parametrize decorator
import pytest
@____("a,b,expected", [(1, 2, 3), (10, 5, 15)])
def test_add(a, b, expected):
assert add(a, b) == expected
import pytest
@pytest.mark.parametrize("a,b,expected", [(1, 2, 3), (10, 5, 15)])
def test_add(a, b, expected):
assert add(a, b) == expected
Explanation: The pytest.mark.parametrize decorator is used for data-driven tests.
2 Match the parametrize parts
| Term | Meaning |
|---|---|
"a,b,expected" |
Parameter names |
(1, 2, 3) |
One test case |
@pytest.mark.parametrize |
Repeats the test |
def test_add(a, b, expected) |
Test signature |
3 What does the first string argument of parametrize specify?
- The test function name
- The expected output
- The module name
- Parameter names (comma-separated) Correct answer
Explanation: The first string lists parameter names; data tuples bind in that order.