【问题标题】:Passing arguments to pytest.mark.parametrize via command line arguments通过命令行参数将参数传递给 pytest.mark.parametrize
【发布时间】:2021-11-29 10:11:48
【问题描述】:

我正在尝试将命令行参数传递给 pytest 测试。 来自question的示例

print ("Displaying name: %s" % name)

在测试中

parser.addoption("--name", action="store", default="default name")


def pytest_generate_tests(metafunc):
    # This is called for every test. Only get/set command line arguments
    # if the argument is specified in the list of test "fixturenames".
    option_value = metafunc.config.option.name
    if 'name' in metafunc.fixturenames and option_value is not None:
        metafunc.parametrize("name", [option_value])

我想将名称参数传递给 pytest.mark.parametrize。 现在,我知道根据我引用的问题,答案提到我不应该使用@pytest.mark.parametrize。但是,我正在开发一个已经使用它的代码库,并且我还需要在 CI 过程中传递参数。是否有解决方法或者我注定要重新编写所有测试?

编辑: 由于我不够清楚 - 我不能将 mark.parametrize 中的命令行参数与 pytest 控制台行参数一起使用。 示例-我有一个返回列表并输入名称的函数,并将其添加到 mark.parametrize:

@pytest.mark.parametrize("return_list", foo(name)):
def test_name(return_list):
    pass

name 参数,就像我提到的,需要来自命令行,这在我遇到的任何方法中都不起作用。 我不知道如何在没有mark.parametrize的pytest中使用列表,所以这是一个问题

【问题讨论】:

  • 为什么不使用os.environ.get("FIXTURE_NAME", "default name") 或类似的方式读取环境变量?

标签: python pytest command-line-arguments


【解决方案1】:

好的,所以我使用pytest-lazy-fixture 找到了答案。 可以为任何高于 3.2.5(包括在内)的 pytest 版本安装它。 Gist 通过其关键字调用自定义夹具(测试本身的 conftest)。 将在此处留下完整答案以供将来参考:

完整示例:

在测试中

def pytest_addoption(parser):
    parser.addoption("--name", action="store", default="default name")

@pytest.fixture(scope = 'module', autouse = True)
def names(request):
    """ main code and manipulation on the data """
    return request.config.getoption("--name")

在 test.py 中

@pytest.mark.parametrize('arg1',
[pytest.lazy_fixture('names')]
)
def test_something(arg1):
    # do something here
    pass

如果将lazy_fixture 输入另一个函数,这也适用于mark.parametrize。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多