Pytest:如何参数化输入



有没有办法将输入传递给pytest.mark.parameter((?

如果我尝试…

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}")

…我得到NameError: name 'input_sequence' is not defined

对于某些上下文,我在conftest.py:中将input_sequence定义为pytest命令选项

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(",")]

您在对@pytest.mark.parametrize的调用中引用了一个变量input_sequence,但作用域中没有这样的变量。您需要在模块级别定义它(直接或从某个地方导入(。

您还需要将其从test_sequence_rotation的参数列表中删除。

例如:

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}")

当通过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 ===============================

相关内容

  • 没有找到相关文章