A minimal example of using namedtuples in pytest parameterized tests | Rida Ayed

A minimal example of using namedtuples in pytest parameterized tests

What means - in the test parameters below?
Nevermind I don’t get it either.
Only after counting the commas I could guess gender.

@pytest.mark.parametrize(
"lang, salutation, gender, title, expect",
[
    ("DE", "","m","","doe","Hallo"),
    ("DE", "","m","Dr.","doe","Hallo Dr. Doe"),
    ("EN", "","-","Dr.","doe","Dear Dr. Doe"),
    ("FR", "","f","","xyz","Cher Madame Xyz"),
    ("EN", "Dear Bob","m","","doe","Dear Bob"),
])

To put the problem in full context, I’ve simplified and highlighted the parameters in the complete example below:

test_before.py
import pytest

@pytest.mark.parametrize("gender,lang", (
    ('-', 'EN'),
))
def test(gender, lang):
    assert gender

Namedtuples are the salvation for this problem.
Notice now how easy the highlighted gender = '-' is understood.

test_after.py
import pytest
from collections import namedtuple

Param = namedtuple('Param', ('gender', 'lang'))
@pytest.mark.parametrize(Param._fields, (
    Param(gender='-', lang='EN'),
))
def test(gender, lang):
    assert gender

I have described another mitigation for incomprehensive structures here.
Another approach using NamedTuple from typing is shown here youtube.
This blogpost –with a bit more text to glance over– inspired me to write this post.