Python coverage: running more than 1 test

2019-08-20 12:52发布

问题:

I'm wondering is there a way to specify more than 1 test file to run when using python coverage config (.coveragerc) file. If not from a config file, maybe it is possible when running from command line? At the moment, for 3 different unit tests files I'm using:

coverage run test1
coverage run -a test2
coverage run -a test3

Can it be any shorter? Thanks

回答1:

Edit (2017-09-25): As @ned-batchelder says in the comments, prefer pytest over nose if starting a new project, as nose is unmaintained.

By taking a look at Coverage documentation, it looks like that the only mode that coverage supports is running a specific module with each command.

You could use a testing framework, such as nose pytest, to run all your tests, and report the success/failure rate and the total coverage.

Find out total code overage using pytest

1) Install pytest, coverage, and pytest-cov

pip install pytest
pip install coverage
pip install pytest-cov

2) Run the pytest commmand, using the --cov flag for every module or package whose coverage you need measured. For example:

pytest --cov=foo --cov=bar

Sample output:

Name     Stmts   Miss  Cover   Missing
--------------------------------------
bar.py       3      1    67%   5
foo.py       6      2    67%   9-11
--------------------------------------
TOTAL        9      3    67%

pytest will find your tests if they match the pattern test_*.py (or others, more info here).

Find out total code coverage using nose

1) Install nose and coverage

pip install nose
pip install coverage

2) Run the nosetests command, with the --with-coverage flag

nosetests --with-coverage

Sample output (when having a single module foo.py):

Name     Stmts   Miss  Cover
----------------------------
foo.py       6      2    67%
----------------------------------------------------------------------
Ran 1 test in 0.008s

OK

nosetests can automatically find your tests using some heuristics. For example, if you put your tests in filenames that start with test, and create your testcases by inheriting from unittest.TestCase, nosetests will find them. More info here.