Python pytest如何同时使用getoption和parameterize

Python pytest如何同时使用getoption和parameterize,python,pytest,Python,Pytest,我有一个测试,它在某些可执行文件上运行子进程并测试stdout结果 所以我用 #conftest.py def pytest_addoption(parser): parser.addoption("--executable", action="store") @pytest.fixture(scope="session", autouse=True) def pass_executable(request): try: return request.conf

我有一个测试,它在某些可执行文件上运行子进程并测试stdout结果

所以我用

#conftest.py
def pytest_addoption(parser):
    parser.addoption("--executable", action="store")


@pytest.fixture(scope="session", autouse=True)
def pass_executable(request):
    try:
        return request.config.getoption("--executable")
    except AttributeError:
        pass
这样我就可以使用命令行arg来设置传递可执行文件的路径。我希望在我所有的测试中使用它作为全局变量。但是,我在需要@pytest.mark.parametrize decorator的测试中遇到了问题。因此,我的解决方案是创建一个
test\u update\u路径(pass\u executable)
来更新一个全局变量路径,这是可行的

# test.py
PATH = 'defaultpath/app'


def test_update_path(pass_executable):
    global PATH 
    PATH = pass_executable
    print("Gloabl path is update to: ")
    print(PATH)

def test_1():
    # This will work 
    print("Now next")
    print(PATH)
    cmd = [PATH]
    stdout, stderr = run_subprocess(cmd)
    assert stdout == 'some expected result'


@pytest.mark.parametrize("args", [1, 2, 3])
def test_2(path, args):
    print("Now next")
    print(PATH)
    cmd = paramparser(PATH, args)
    stdout, stderr = run_subprocess(cmd)
    assert stdout == 'some expected result'

if __name__ == '__main__':
    pytest.main()
pytest--executable=newpath/app-s
可以正常工作,但这是一个丑陋的黑客行为。更重要的是,它运行了一个没有进行任何实际测试的测试。这也是有问题的,因为参数不是可选的。没有设置——可执行。路径将是
NoneType
,而不是原始默认路径

有什么建议吗


谢谢

您不需要全局变量,只需使用
请求
fixture作为测试参数来访问命令行arg,就像在
传递可执行文件
中一样。这就是我将如何更改这两个测试:

def test_1(request):
    cmd = [request.config.getoption("--executable")]
    stdout, stderr = run_subprocess(cmd)
    assert stdout == 'some expected result'


@pytest.mark.parametrize("arg", [1, 2, 3])
def test_2(request, arg):
    cmd = paramparser(request.config.getoption("--executable"), arg)
    stdout, stderr = run_subprocess(cmd)
    assert stdout == 'some expected result'
如果您不喜欢这两个测试中的代码复制,请将其提取到fixture中并将其用作测试参数,就像内置的
请求一样:

@pytest.fixture
def executable(request):
    return request.config.getoption("--executable")


def test_1(executable):
    cmd = [executable]
    stdout, stderr = run_subprocess(cmd)
    assert stdout == 'some expected result'


@pytest.mark.parametrize("arg", [1, 2, 3])
def test_2(executable, arg):
    cmd = paramparser(executable, arg)
    stdout, stderr = run_subprocess(cmd)
    assert stdout == 'some expected result'

这太棒了。非常感谢。很高兴我能帮忙!