如果从另一个模块以编程方式运行pytest,如何将参数传递给pytest?

时间:2017-01-10 17:48:58

标签: python pytest

在以下示例中,如何将args的{​​{1}}传递给run_tests(),以便我可以将pytest.main(...)用于args的测试方法TestFooBar

my_module.py

test_module.py

test_module.py

def run_tests(args):
    # How do I pass parameter 'args' to pytest here.
    pytest.main(['-q', '-s', 'test_module.py::TestFooBar'])

1 个答案:

答案 0 :(得分:3)

如果你执行pytest.main,那么你所做的就是从命令行调用py.test,所以传递我所知道的参数的唯一方法是通过命令行参数。为此,您的参数需要可以转换为字符串。

基本上这意味着使用以下

创建conftest.py
def pytest_addoption(parser):
    parser.addoption('--additional_arguments', action='store', help='some helptext')

def pytest_configure(config):
    args = config.getoption('additional_arguments')

现在用args做一些事情:反序列化它,使它成为一个全局变量,使它成为一个夹具,你想要的任何东西。来自conftest.py的灯具将可用于整个测试。

毋庸置疑,您的通话现在应该包含新参数:

pytest.main(['-q', '-s', '--additional_arguments', args_string, 'test_module.py::TestFooBar'])