Measuring test coverage with 'coverage.py'

Hello,

I want to measure test coverage in my Django project.

I followed Django docs and installed the coverage package. Then I executed from my project root:

coverage run --source="." manage.py test myapp

The test runner executes the tests, but the coverage report shows that no lines were executed. Example:
image

The only file with non-zero coverage, in red, is the project’s settings.py file.

So far I’ve tried:

  • running tests with --source="myapp" instead of --source=".". Still zero coverage reported, but this time it logs a "No data collected" error to the console.
  • wrapping manage.py with coverage.Coverage() as suggested in Adam Johnson’s blog. The command crashes with NoDataError("No data to report.").
  • running the entire test suite, instead of just 1 app
  • Trying pytest and pytest-cov – same result, since pytest-cov uses coverage under the hood

I feel like I am missing some basic piece of config. My django project lives inside a Docker container and it’s structured like this:

project/
  project_name/
    settings.py
    wsgi.py
    ...
  app1/
  app2/
  module1/
  module2/

I am running the comands from the project/ directory. All dependencies are installed globally.

Any suggestions? Thank you!

1 Like

Were you able to figure this out? I’m also looking for guidance on running coverage with django projects

For the that specific project, I haven’t figured out why the coverage tool isn’t working.

However, I tried the coverage tool in a fresh Django project, and the tool works as advertised. So there is something wrong with how I use the tool in my main project, but I am still not sure what.

Ah makes sense. I have figured it out too. I installed django_test_coverage which I’m honestly not sure if it makes a difference.

But then I was able to get it to work with

docker exec <container name> coverage run --source="." manage.py test [app name]

and then get reports with:

docker exec <container name> coverage report
# or
docker exec <container name> coverage html