"""confest.py file."""
import pytest
def pytest_addoption(parser):
parser.addoption(
"--cmdopt", action="store", default=None
)
@pytest.fixture(scope="session", autouse=True)
def cmdopt(request):
"""Reading data from command prompt."""
return request.config.getoption("--cmdopt")
@pytest.fixture(scope="session", autouse=True)
def do_something(cmdopt)
"""Would need to preprocess the needed one to make it parameterised."""
return list_of_tuples
测试文件的结构是这样的
""" Test Suite File."""
import pytest
#do_something is in conftest file
@pytest.mark.parametrize("val1,val2", variables = do_something)
def test_case1(val1, val2):
assert val1 == val2
当前代码实际上会引发错误,因为do_something
中使用的conftest.py
方法无法正常工作。我该如何纠正代码?
答案 0 :(得分:1)
您不能使用固定装置来做到这一点;但是,您可以编写一个pytest_generate_tests
挂钩,以参数化val1
,val2
测试参数。示例:
# conftest.py
import pytest
def pytest_addoption(parser):
parser.addoption('--range', action='store', type=int, default=None)
def pytest_generate_tests(metafunc):
if all(arg in metafunc.fixturenames for arg in ('val1', 'val2')):
hi = metafunc.config.getoption('--range')
if hi is not None:
variables = [(i, i) for i in range(hi)]
metafunc.parametrize("val1,val2", variables)
测试模块:
def test_case1(val1, val2):
assert val1 == val2
以不同的--range
号运行测试将产生不同数量的测试:
$ pytest -v --range 1
...
test_spam.py::test_case1[0-0] PASSED
...
$ pytest -v --range 5
...
test_spam.py::test_case1[0-0] PASSED
test_spam.py::test_case1[1-1] PASSED
test_spam.py::test_case1[2-2] PASSED
test_spam.py::test_case1[3-3] PASSED
test_spam.py::test_case1[4-4] PASSED
...