Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Pytest & fixturesMiddleCommonPractical

What does `@pytest.mark.parametrize` do, and why is it usually better than a `for` loop over test cases inside one test function?

Answer

`@pytest.mark.parametrize("input,expected", [(1, 2), (2, 4)])` runs the decorated test function once per tuple of arguments, and pytest reports each one as its own independently named, independently pass/fail test result. A `for` loop inside a single test function instead runs all cases inside one test, so the first failing case stops the loop and hides the results of every case after it, and a failure only reports the enclosing test's generic name instead of pinpointing exactly which input failed.

Strong answer includes

  • runs the test once per parameter tuple, each reported as its own test result
  • a for loop stops at the first failure and hides later cases
  • parametrize pinpoints exactly which input failed instead of one generic result

Practical example

Python example
@pytest.mark.parametrize("n,expected", [(0, 0), (1, 1), (5, 120)])
def test_factorial(n, expected):
    assert factorial(n) == expected

reports

Python example
test_factorial[5-120]

as a separately failing test if only that case breaks.

#pytest#testing

Sources

pytest documentationpytest · Fixture scope, parametrization, markers and plugin architecture