如何通过命令行在pytest中传递参数
收藏

我有一个代码,我需要从终端传递诸如name之类的参数。 这是我的代码以及如何传递参数。我收到了我不理解的“找不到文件”类错误。

I have tried the command in the terminal: pytest <filename>.py -almonds I should get the name printed as "almonds"

@pytest.mark.parametrize("name")
def print_name(name):
    print ("Displaying name: %s" % name)

最佳答案

In your pytest test, don't use @pytest.mark.parametrize:

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

In conftest.py:

def pytest_addoption(parser):
    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 -s tests/my_test_module.py --name abc

    公众号
    关注公众号订阅更多技术干货!