Introduction
Parametrizing tests lets you run the same test with many inputs. This helps find more problems quickly without writing many tests.
Parametrizing tests lets you run the same test with many inputs. This helps find more problems quickly without writing many tests.
@pytest.mark.parametrize("input,expected", [(value1, result1), (value2, result2), ...]) def test_function(input, expected): assert function_to_test(input) == expected
@pytest.mark.parametrize("num,expected", [(1, 2), (3, 4), (5, 6)]) def test_increment(num, expected): assert num + 1 == expected
@pytest.mark.parametrize("text,expected_len", [("hello", 5), ("", 0), ("pytest", 6)]) def test_length(text, expected_len): assert len(text) == expected_len
This test runs four times with different pairs of numbers to check if their sum matches the expected value.
import pytest @pytest.mark.parametrize("a,b,expected", [ (2, 3, 5), (0, 0, 0), (-1, 1, 0), (100, 200, 300) ]) def test_addition(a, b, expected): assert a + b == expected
Parametrization helps catch bugs that only appear with certain inputs.
It keeps tests clean and avoids repeating similar code.
Use descriptive names for parameters to make tests easy to read.
Parametrizing runs one test many times with different data.
This increases test coverage without extra test functions.
It helps find more bugs and keeps tests simple.
@pytest.mark.parametrize in tests?@pytest.mark.parametrize decorator runs one test function multiple times with different input values.a and b in pytest?@pytest.mark.parametrize with a string of parameter names and a list of tuples for values.@pytest.mark.parametrize('a,b', [(1, 2), (3, 4)]). Others have wrong names or formats.import pytest
@pytest.mark.parametrize('x', [0, 1, 2])
@pytest.mark.parametrize('y', [10, 20])
def test_sum(x, y):
assert x + y > 10
@pytest.mark.parametrize('num', [1, 2, 3])
def test_is_even(num):
assert num % 2 == 0
@pytest.mark.parametrize decorators on a single test function affect test coverage and execution?Pass the test and this pattern moves unknown