While pytest's parametrization feature is valuable, it can become difficult to read when handling numerous examples or values. Understanding the purpose behind test examples matters—both immediately and when revisiting code later or reading others' tests.
Using pytest.param for Named Examples
The recommended approach involves using pytest.param, a helpful pytest utility. This function wraps parametrized values (accepting any number of positional arguments) and allows you to assign an id parameter. You can use any string as the identifier, making it ideal for naming examples clearly.
import pytest
@pytest.mark.parametrize("url,expected", [
pytest.param("https://example.com", True, id="valid_https_url"),
pytest.param("http://example.com", True, id="valid_http_url"),
pytest.param("not_a_url", False, id="invalid_string"),
pytest.param("", False, id="empty_string"),
])
def test_is_valid_url(url, expected):
assert is_valid_url(url) == expected
Key Benefits
- Improved readability of test code and reasoning behind specific examples
- Better pytest logging output during test execution
- Easier identification of failed tests through their assigned IDs
- Quicker debugging compared to seeing raw values or type information