@pytest.mark.parametrize cho phép chạy cùng test với nhiều input/output khác nhau:
python
import pytest
@pytest.mark.parametrize("email,is_valid", [
("user@example.com", True),
("invalid-email", False),
("@nodomain.com", False),
("user@.com", False),
("", False),
])
def test_validate_email(email: str, is_valid: bool):
assert validate_email(email) == is_valid
# Multiple params
@pytest.mark.parametrize("a,b,expected", [
(1, 2, 3),
(0, 0, 0),
(-1, 1, 0),
(100, 200, 300),
])
def test_add(a, b, expected):
assert add(a, b) == expected
# Nested parametrize — cartesian product
@pytest.mark.parametrize("base", [2, 10])
@pytest.mark.parametrize("exponent", [0, 1, 2])
def test_power(base, exponent):
assert power(base, exponent) == base ** exponent
# 6 test cases: (2,0), (2,1), (2,2), (10,0), (10,1), (10,2)
# Với pytest.param cho custom IDs hoặc marks
@pytest.mark.parametrize("value", [
pytest.param(None, id="null-value"),
pytest.param([], marks=pytest.mark.xfail, id="empty-list"),
])
def test_process(value): ...