英文:
Passing command line arguments to an already parameterized pytest test
问题
我已经对pytest测试进行了参数化。如何向测试添加一个额外的参数,该参数作为命令行参数传递给pytest?
我尝试向解析器添加一个名为xyz的选项,并将命令行参数作为一个fixture返回,就像这样。。
conftest.py:
def pytest_addoption(parser):
parser.addoption(
"--some_other_option", action="store_true", default=True, help="Skip some tests"
)
parser.addoption(
"--xyz", action="store_true", default=True, help="Test xyz"
)
@pytest.fixture
def xyz(config):
return config.getoption('--xyz')
测试文件:
@pytest.mark.parametrize('arg1, arg2, arg3, arg4, arg5', [
('asdf', 1, 1, 0, [0.64]),
...
])
def test_stuff(arg1, arg2, arg3, arg4, arg5, xyz):
if xyz: # 仅在xyz为True时执行此操作
assert func(arg3) == 42
....
我也尝试过这样做。在两种情况下,问题是pytest对每个测试都返回错误
`E fixture 'config' not found
我做错了什么?`
英文:
I have parameterized pytest tests. How to add an additional parameter to the tests that is passed to pytest as a command line argument?
I tried adding an option xyz to the parser and put return the command line argument as a fixture, like so..
conftest.py:
def pytest_addoption(parser):
parser.addoption(
"--some_other_option", action="store_true", default=True, help="Skip some tests"
)
parser.addoption(
"--xyz", action="store_true", default=True, help="Test xyz"
)
@pytest.fixture
def xyz(config):
return config.getoption('--xyz')
test file:
@pytest.mark.parametrize('arg1, arg2, arg3, arg4, arg5', [
(asdf', 1, 1, 0, [0.64]),
...
])
def test_stuff(arg1, arg2, arg3, arg4, arg5, xyz):
if xyz: # only do this if xyz is True
assert func(arg3) == 42
....
I have also tried it like this.
In both cases, the issue is that pytest returns an error for every test
`E fixture 'config' not found
What am I doing wrong?
`
答案1
得分: 1
“config”对象可以从“pytest_configure”钩子 (https://docs.pytest.org/en/7.1.x/reference/reference.html#pytest.hookspec.pytest_configure) 中访问。但是通过“request”也足够了。
所以,如果您想要“xyz”作为一个fixture,您可以尝试:
@pytest.fixture
def xyz(request):
return request.config.getoption('--xyz')
英文:
The config
object is accessible from the pytest_configure
hook (https://docs.pytest.org/en/7.1.x/reference/reference.html#pytest.hookspec.pytest_configure). But with request
it is enough.
So if you want xyz
as a fixture, you could try:
@pytest.fixture
def xyz(request):
return request.config.getoption('--xyz')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论