pythad
pythad

Reputation: 4267

How to run coverage.py on a directory?

I have a directory tests that includes a lot of different tests named test_*.

I tried to run coverage run tests but it doesn't work.

How can I run a single command to coverage multiple files in the directory?

Upvotes: 18

Views: 30211

Answers (4)

erncyp
erncyp

Reputation: 1672

None of the answers here quite worked for me. I found that coverage and pytest worked fine though:

coverage run -m pytest

This was run at the project folder. It was able to find the folder called tests, and run all the tests (which was split into multiple python files and had a __init__.py file) within them. To see the report run:

coverage report

Upvotes: 5

Nirmal
Nirmal

Reputation: 1259

Here is a complete example with commands from the same PWD for all phases in one place. With a worked up example, I am also including the testing and the report part for before and after coverage is run. I ran the following steps and it worked all fine on osx/mojave.

  1. Discover and run all tests in the test directory

$ python -m unittest discover <directory_name>

Or Discover and run all tests in "directory" with tests having file name pattern *_test.py

$ python -m unittest discover -s <directory> -p '*_test.py'

  1. run coverage for all modules

$ coverage run --source=./test -m unittest discover -s <directory>/

  1. get the coverage report from the same directory - no need to cd.

$ coverage report -m

Notice in above examples that the test directory doesn't have to be named "test" and same goes for the test modules.

Upvotes: 18

Juan Diego Garcia
Juan Diego Garcia

Reputation: 823

You can achieve that using --source. For example: coverage run --source=tests/ <run_tests>

Upvotes: 10

9000
9000

Reputation: 40894

Use --include to only include files in particular directories. It matches file paths, so it can match a subdirectory.

Upvotes: 9

Related Questions