Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 283
nikow Avatar asked Jul 27 '10 11:07

nikow


People also ask

Is pytest included in Python?

As most Python packages, pytest is available on PyPI. You can install it in a virtual environment using pip : Windows. Linux + macOS.

How is pytest used?

PyTest is a testing framework that allows users to write test codes using Python programming language. It helps you to write simple and scalable test cases for databases, APIs, or UI. PyTest is mainly used for writing tests for APIs. It helps to write tests from simple unit tests to complex functional tests.


2 Answers

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)
like image 166
nikow Avatar answered Sep 30 '22 19:09

nikow


It seems that now (py.test version 2.0+) someone can also do this :

import pytest

pytest.main('-x {0}'.format(argument))

# Or
# pytest.main(['-x', 'argument'])

Ref

like image 43
Richard Avatar answered Sep 30 '22 21:09

Richard