Pytest: How to parametrize input

1.3k views Asked by At

Is there a way to pass input to pytest.mark.parametrize()?

If I try…

import pytest
from typing import List


@pytest.mark.parametrize("rotation", range(len(input_sequence)))
def test_sequence_rotation(
    input_sequence: List[float],
    rotation: int,
) -> None:
    sequence = input_sequence[rotation:] + input_sequence[:rotation]
    print(f"Testing sequence {sequence}")

… I get NameError: name 'input_sequence' is not defined.

For some context, I have input_sequence defined as a pytest command option in conftest.py:

import pytest
from typing import List
from _pytest.config.argparsing import Parser
from _pytest.fixtures import SubRequest


def pytest_addoption(parser: Parser) -> None:
    parser.addoption("--sequence-csv", type=str, required=True)


@pytest.fixture()
def input_sequence(request: SubRequest) -> List[float]:
    csv = request.config.getoption("--sequence-csv")
    return [float(i) for i in csv.split(",")]
1

There are 1 answers

0
larsks On

You're referring to a variable input_sequence in your call to @pytest.mark.parametrize, but no such variable is in scope. You would need to define this at the module level (either directly or by importing it from somewhere).

You would also need to remove it from the parameter list of test_sequence_rotation.

E.g., something like:

import pytest
from typing import List

input_sequence = ['a', 'b', 'c', 'd', 'e']

@pytest.mark.parametrize("rotation", range(len(input_sequence)))
def test_sequence_rotation(rotation: int) -> None:
    sequence = input_sequence[rotation:] + input_sequence[:rotation]
    print(f"Testing sequence {sequence}")

The above code will produce output like this when run via pytest -v:

============================= test session starts ==============================
platform linux -- Python 3.9.4, pytest-6.0.2, py-1.10.0, pluggy-0.13.1 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: /home/lars/tmp/python
plugins: cov-2.11.1, flake8-1.0.7, asyncio-0.14.0, xonsh-0.9.26
collecting ... collected 5 items

test_sequence.py::test_sequence_rotation[0] PASSED                       [ 20%]
test_sequence.py::test_sequence_rotation[1] PASSED                       [ 40%]
test_sequence.py::test_sequence_rotation[2] PASSED                       [ 60%]
test_sequence.py::test_sequence_rotation[3] PASSED                       [ 80%]
test_sequence.py::test_sequence_rotation[4] PASSED                       [100%]

============================== 5 passed in 0.03s ===============================