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

Rot*_*eti 8 python pytest

在下面的例子中,我怎么传argsrun_tests(),以pytest.main(...)让我可以使用args的测试方法TestFooBartest_module.py

my_module.py

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

测试模块.py

class TestFooBar():

    # How do I get 'args' of 'run_tests()' from 'my_module.py' here.

    @pytest.mark.parametrize("args", [args])
    def test_something(args):
       assert 'foo' == args['foo']

    @pytest.mark.parametrize("args", [args])
    def test_something_else(args):
        assert 'bar' == args['bar']
Run Code Online (Sandbox Code Playgroud)

ins*_*ant 5

如果执行pytest.mainpy.test ,则相当于从命令行调用 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')
Run Code Online (Sandbox Code Playgroud)

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

不用说,您的调用现在应该包含新参数:

pytest.main(['-q', '-s', '--additional_arguments', args_string, 'test_module.py::TestFooBar'])
Run Code Online (Sandbox Code Playgroud)