Python
parametrize
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) == expected
Each 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.
Exercise 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").
Show example 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")
Test yourself
-
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
Show answer
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
-
Match the parametrize parts
- "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
-
What does the first string argument of parametrize specify?
- The test function name
- The expected output
- The module name
- Parameter names (comma-separated)
Show answer
Parameter names (comma-separated) — The first string lists parameter names; data tuples bind in that order.
Next lesson: monkeypatch