How to run pytest on a module rather than file or directory?

Viewed 831

I have installed a third-party Python package (let's say it's named pkg) which contains pytest tests in a module pkg.test.

Typically, one invokes pytest from the command line or IDE on a directory or file. However, how can I programmatically run these tests from my own Python code?

I would like to do something like the following, where I use a hypothetical pytest.run_tests_in_module function:

import pytest

pytest.run_tests_in_module('pkg.tests')  # runs tests inside pkg.tests
1 Answers

There is a section in pytest documentation that directly answers your question: "Calling pytest from Python code".

The function is pytest.main(), and you can pass the same arguments you would pass via the command line.

To pass a python package as an argument instead of a directory, you may use --pyargs. It will force pytest to perform regular import to locate the package. So the full invocation for your example above will look like this:

pytest.main(['--pyargs',  'pkg.tests'])
Related