Search GimmeJob

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

Use pytest parametrization to test several valid and invalid age values without duplicating the test body.

Answer

Use `@pytest.mark.parametrize` with explicit input and expected-result columns. pytest creates one independent test case for each row, so failures identify the specific data set while the assertion logic stays in one place. Include boundary values rather than only typical values because those are usually where validation defects appear.

Strong answer includes

  • uses pytest.mark.parametrize
  • keeps one test body for multiple cases
  • includes boundary and invalid values

Practical example

Boundary-focused parametrization
import pytest

def is_valid_age(age):
    return 18 <= age <= 120

@pytest.mark.parametrize(
    ("age", "expected"),
    [
        (17, False),
        (18, True),
        (120, True),
        (121, False),
    ],
)
def test_age_validation(age, expected):
    assert is_valid_age(age) is expected

Each tuple becomes a separate pytest case, and the chosen data covers both valid boundaries plus the immediately adjacent invalid values.

Expected result: Four passing test cases.

#pytest#parametrization#testing

Sources

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