Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass arguments to pytest if pytest is run programmatically from another module?

Tags:

python

pytest

In the following example, how do I pass args of run_tests() to pytest.main(...) so that I can use args for the test methods of TestFooBar in test_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'])

test_module.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']
like image 293
Rotareti Avatar asked Jan 10 '17 17:01

Rotareti


People also ask

How do I run pytest in parallel?

To overcome this, pytest provides us with an option to run tests in parallel. For this, we need to first install the pytest-xdist plugin. -n <num> runs the tests by using multiple workers, here it is 3. We will not be having much time difference when there is only a few tests to run.

What is the syntax to run a parameterized test in pytest?

you can put @pytest. mark. parametrize style parametrization on the test functions to parametrize input/output values as well.

Which command will execute tests of the selected module pytest?

In general, pytest is invoked with the command pytest (see below for other ways to invoke pytest). This will execute all tests in all files whose names follow the form test_*. py or \*_test.py in the current directory and its subdirectories.


1 Answers

If you execute pytest.main the you are doing the equivalent to calling py.test from the command line, so the only way to pass arguments that I am aware of is via a command line parameter. For this to be possible, your parameters need to be convertable to and from string.

Basically this means creating a conftest.py with the following

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

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

Now do something with args: deserialize it, make it a global variable, make it a fixture, anything you want. Fixtures from conftest.py will be available to the entire test.

Needless to say that your call should now include the new parameter:

pytest.main(['-q', '-s', '--additional_arguments', args_string, 'test_module.py::TestFooBar'])
like image 137
instant Avatar answered Sep 23 '22 11:09

instant