Python How to pass a list to parametrize in Pytest

eye-catch Python

I searched for a way to pass a list as a parameter but I didn’t find the answer. Because it is too easy to do…?

Sponsored links

Passing multiple arguments

If multiple arguments are necessary to inject, we can write it in the following way.

@pytest.mark.parametrize(
    argnames=["x", "y", "z"],
    argvalues=[
        (1, 2, 3)
    ]
)
def test_pass_multi_args(x, y, z):
    print(f"(x, y ,z): ({x}, {y}, {z})")

# (x, y ,z): (1, 2, 3)

Then, I thought that list could be passed in the following way.

@pytest.mark.parametrize(
    argnames=["x"],
    argvalues=[
        ([1, 2, 3]) # with square brackets
    ]
)
def test_pass_list_fail(x):
    print(f"List: {x}")

But it is actually incorrect. Pytest throws an error in this case because it requires three arguments in this case. Look at the next example. It defines 3 arguments.

@pytest.mark.parametrize(
    argnames=["x", "y", "z"],
    argvalues=[
        ([1, 2, 3])
    ]
)
def test_pass_multi_args2(x, y, z):
    print(f"(x, y ,z): ({x}, {y}, {z})")

# (x, y ,z): (1, 2, 3)
Sponsored links

Use list to pass list

The solution is the following.

import pytest


TEST_DATASET = [
    [[1, 2, 3]],
    [["1", "2", "3"]],
    [["1", 2, 3]],
    [[[1, 2, 3], [4, 5, 6]]],
    [[["1", 2, 3], [4, "5", 6]]],
    [[[[11, 12, 13], [21, 22]], [[31, 32], [41, 42]]]],
]


@pytest.mark.parametrize(
    argnames=["values"],
    argvalues=TEST_DATASET
)
def test_pass_list(values):
    print(f"values: {values}")

# values: [1, 2, 3]
# values: ['1', '2', '3']
# values: ['1', 2, 3]
# values: [[1, 2, 3], [4, 5, 6]]
# values: [['1', 2, 3], [4, '5', 6]]
# values: [[[11, 12, 13], [21, 22]], [[31, 32], [41, 42]]]

Each parameter needs to be in square brackets.

Comments

Copied title and URL