brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python pytest.mark.parametrize runs one test against a table of cases

Python
~/tips/tip-python-pytest-parametrize

import pytest

Test a function with many inputs without copying the test function.

When you catch yourself writing test_to_gb_zero, test_to_gb_small and test_to_gb_big with the same body, I’d say it’s time for parametrize.

import pytest

def to_gb(n):
    return round(n / 1e9, 1)

@pytest.mark.parametrize("size, expected", [
    (0, 0),
    (1_500_000_000, 1.5),
    (999, 0.0),
])
def test_to_gb(size, expected):
    assert to_gb(size) == expected

pytest runs the test once per tuple and fills in the arguments by name. Each case shows up as its own test, like test_to_gb[1500000000-1.5], so when one fails you see exactly which input broke it and the others still run.

Adding a case is now one line in a table. That makes it much easier to add the odd edge case you just found in a bug report, which I think is the real win.

Those generated ids get unreadable once the inputs are long strings or objects. Pass ids=["zero", "normal", "tiny"], or wrap single cases in pytest.param(..., id="zero"), to give them names you can also select with -k. Keep the table about one behaviour. If half the cases need a different assertion, two separate tests are easier to read.

Further reading: pytest: parametrize

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link