Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke pytest from python for current module only

Tags:

I know that py.test can test a single module if I do:

py.test mod1.py

Or, I can invoke pytest inside python:

import pytest
pytest.run(['mod1.py'])

Can I do it inside python, and let it to run the current module? I guess I can do:

import pytest
import os
pytest.main([os.path.basename(__file__)])

But wonder whether this is the most "pythonic" way to do it. Thanks!

like image 668
Yuxiang Wang Avatar asked Feb 12 '16 02:02

Yuxiang Wang


People also ask

How do I run a specific pytest function?

Running pytest We can run a specific test file by giving its name as an argument. A specific function can be run by providing its name after the :: characters. Markers can be used to group tests. A marked grouped of tests is then run with pytest -m .

How do I invoke pytest?

Calling pytest through python -m pytest You can invoke testing through the Python interpreter from the command line: python -m pytest [...] This is almost equivalent to invoking the command line script pytest [...] directly, except that calling via python will also add the current directory to sys.

How do I bypass pytest?

The simplest way to skip a test function is to mark it with the skip decorator which may be passed an optional reason : @pytest. mark.


1 Answers

Your versions do not allow passing extra arguments to pytest (e.g. allow ./test_file.py -v). I tried simply

import sys


if __name__ == '__main__':
    pytest.main(sys.argv)

and it seems to do the trick. sys.argv[0] is the script name (i.e. __file__, possibly as a relative path), so it restricts the call to the script, and sys.argv[1:] contain extra arguments passed on the command-line.

Any better idea appreciated!

like image 143
Matthieu Moy Avatar answered Sep 17 '22 13:09

Matthieu Moy