python-pytest-cases icon indicating copy to clipboard operation
python-pytest-cases copied to clipboard

Improve `@parametrize`: accept a dict for argvalues so that the id can be passed as the key

Open smarie opened this issue 3 years ago • 1 comments
trafficstars

@pytest.mark.parametrize("a", [0, 2], ids=["Null", "Positive"])

could become

@parametrize("a", dict(Null=0, Positive=2)

smarie avatar Feb 22 '22 11:02 smarie

This pytest example

@pytest.mark.parametrize(
    "a,b,expected",
    [
        pytest.param(
            datetime(2001, 12, 12), datetime(2001, 12, 11), timedelta(1), id="forward"
        ),
        pytest.param(
            datetime(2001, 12, 11), datetime(2001, 12, 12), timedelta(-1), id="backward"
        ),
    ],
)
def test_timedistance_v3(a, b, expected):
    diff = a - b
    assert diff == expected

would write:

@parametrize(
    "a,b,expected",
    dict(
        forward=(datetime(2001, 12, 12), datetime(2001, 12, 11), timedelta(1)),
        backward=(datetime(2001, 12, 11), datetime(2001, 12, 12), timedelta(-1)),
    ),
)
def test_timedistance_v3(a, b, expected):
    diff = a - b
    assert diff == expected

It seems more readable to me as the id is presented first. Of course it is still less readable than having two case functions, but probably faster to write/maintain for some tests.

See https://docs.pytest.org/en/6.2.x/example/parametrize.html

smarie avatar Feb 22 '22 11:02 smarie