Skip to content
Advertisement

How to use `pytest` from Python?

I’m working in a project that recently switched to the pytest unittest framework. I was used to calling my tests from Eclipse, so that I can use the debugger (e.g. placing breakpoints to analyze how a test failure develops). Now this is no longer possible, since the only way to run the tests is via the command line blackbox.

Is there some way to use pytest from within Python, so that one is not forced to drop out of the IDE? The tests should of course not be run in a separate process.

Advertisement

Answer

I think I can now answer my own question, it’s pretty simple:

import pytest

pytest.main(args)

which is documented in the Section “Calling pytest from Python code”. Then I can run this module and/or start it with the integrated debugger.

args is the list of command-line arguments, so for example to run only particular tests I can use something like:

args_str = "-k test_myfavorite"
args = args_str.split(" ")
pytest.main(args)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement