如何 运行 pytest.main("-v test_script2.py") 当 test_script2.py 需要一些命令行参数以便测试函数执行 运行 时?

How to run pytest.main("-v test_script2.py") when test_script2.py needs some command line arguments in order for the test functions to run?

我有两个脚本。一个脚本解析所有参数并决定脚本的控制流。另一个脚本定义了所有测试函数,我想使用 pytest 模块来调用 'test_script2.py' 和 运行 所有测试。但是在测试用例 运行 之前,我需要将一些参数传递给 test_script2.py。

我能想到的一种方法是写入文件并让 test_script2.py 在第一个 运行 时从该文件中读取所有参数。如果您有任何其他想法,请告诉我。感谢您的帮助。谢谢!

如果我对你的问题的理解正确,你可以创建一个 conftest.py 文件并使用 pytest_addoption 挂钩向 pytest 添加选项:

def pytest_addoption(parser):
    parser.addoption(
        '--arg1',
        dest="arg1",
        help="first argument")

现在 py.test 理解这个选项,所以如果你执行:

py.test --arg1 hey

然后在同一目录下测试可以访问这样的选项:

def test_foo(request):
    arg1 = request.config.getoption('arg1')
    assert arg1 == "hey"