Python Testing Tip #7 / Feb. 5, 2025

Parametrize tests using pytest

Testing software requires ensuring it behaves as expected. While single examples sometimes suffice, validating complex functions like email validators demands multiple test cases. Pytest's parametrize decorator offers an elegant solution.

Parametrize Decorator

Pytest provides a built-in parametrize decorator enabling developers to define names of variables and list of examples. This approach allows easily extending test cases—when bugs are reported, new examples can be added to verify functionality across additional scenarios.

import pytest

@pytest.mark.parametrize("email,is_valid", [
    ("user@example.com", True),
    ("invalid-email", False),
    ("user@domain", False),
    ("user.name@example.co.uk", True),
])
def test_email_validation(email, is_valid):
    assert validate_email(email) == is_valid

More Examples, More Confidence

Testing with only one example creates risk during refactoring. The parametrization feature helps developers keep previous examples and add new ones while ensuring changes don't break existing functionality, ultimately increasing test suite reliability.

Do Not Abuse It

Some developers adopt parametrization excessively after learning the feature. Two core testing principles apply regardless:

  • A test should assert single behavior
  • Tests must not contain IF statements

The recommendation is maintaining one test per behavior—separate tests for valid versus invalid email addresses, for instance. Parametrizing output alongside logic makes tests hard to read and obscures which specific behavior failed.

Conclusion

With great power comes great responsibility. Parametrization reduces code while covering multiple scenarios, but overuse diminishes test clarity and maintainability.

Share this tip

Get Python Testing Tips in Your Inbox

Practical Python testing advice delivered to your inbox.