传递命令行参数给已经参数化的 pytest 测试。

huangapple go评论68阅读模式
英文:

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')

huangapple
  • 本文由 发表于 2023年5月23日 00:25:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76308197.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定