Data Providers / Parametrized tests in Python

Take as example a simple validator function: it is usually a pure function, simple input data structure and boolean return value. Writing tests for a validator can create a lot of boilerplate and repetitive code. A solution for simpler test structure are data providers and parametrized tests. In e.g. JavaScript / node.js or PHP you usually use the term “data provider” whereas in Python “parametrized” is used. Below you can find an example for parametrized tests for an is_valid_email validator.

import pytest
from ..validators import is_valid_email


@pytest.mark.parametrize("email", [
    "test@test.de",
    "test+plus@test.de",
    "test.dot@test.co.uk",
    "test.dot.dot@test.de",
    "test-minus.dot@test.de",
    "test_under@test.de",
    "test@student.oxford.co.uk",
    "test@mail.student.oxford.co.uk",
])
def test_is_valid_email_true(email):
    assert is_valid_email(email) is True


@pytest.mark.parametrize("email", [
    "",
    "test",
    "test@test",
])
def test_is_valid_email_false(email):
    assert is_valid_email(email) is False


@pytest.mark.parametrize("email", [
    None,
    1,
    -1,
    0,
    True
])
def test_is_valid_email_error(email):
    with pytest.raises(TypeError):
        is_valid_email(email)