I'm getting following error by passing my fixture defined in conftest.py in @pytest.mark.parametrize:
pytest --alist="0220,0221" test_1.py -v -s
NameError: name 'alist' is not defined
conftest.py:
def pytest_addoption(parser):
parser.addoption("--alist", action="store")
@pytest.fixture
def alist(request):
return request.config.getoption("--alist").split(",")
test_1.py:
@pytest.mark.parametrize("channel", alist, scope="class")
class TestRaIntegrationReplay:
def test_ra_start_time(self, channel):
print(channel)
If I am passing alist to the test as fixture like:
def test_ra_start_time(self, alist):
for channel in alist:
print(channel)
It works well, but it does not work with passing to @pytest.mark.parametrize
As mentioned in the comment, you cannot directly pass a fixture to a mark.parametrize
decorator, because the decorator is evaluated at load time.
You can do the parametrization at run time instead by implementing pytest_generate_tests
:
import pytest
@pytest.hookimpl
def pytest_generate_tests(metafunc):
if "alist" in metafunc.fixturenames:
values = metafunc.config.option.alist
if value is not None:
metafunc.parametrize("alist", value.split(","))
def test_ra_start_time(alist):
for channel in alist:
print(channel)
def test_something_else():
# will not be parametrized
pass
The parametrization is done based on the presence of the alist
parameter in the test function. For parametrization to work, this parameter is needed (otherwise you would get an error because of the missing argument).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.