Using code coverage tools can be a fun way to help you keep the spirit while writing (sometimes) boring tests but in some situations 100% coverage can seem like a gigantic waste of time. However that doesn't mean that measuring code coverage is a waste. Take for example this simple coverage.py script combined with this script which outputs colored HTML of your code. When used correctly and applied carefully, the two can be a powerful tool that helps you ensure that at least the important parts of your code is tested thoroughly!
Earlier this year Siddharta Govindaraj wrote two great posts that showed how to integrate the above scripts with your Django code. Unfortunately they won't work if you use the latest and greatest Django development version, so I have hacked together a new and improved version of his simple test runner.
Here is how you use it:
Get the Python modules mentioned above and put them somewhere in your Python load path. I like to keep things simple so I keep them in my Django project folder alongside my
settings.pyetc. You need coverage.py, coverage_color.py and coverage_tests.py.Edit your
settings.pyand add the following line:TEST_RUNNER = 'coverage_tests.run_test'Add each module that you want to test to the
COVERAGE_MODULESlist insettings.py. For example:COVERAGE_MODULES = ['myproject.blog.views', 'myproject.blog.models']
And that's it. The next time you run manage.py test you will see a simple summary like this:
Name Stmts Exec Cover
-----------------------------------------------
rssepisodes.main.forms 9 9 100%
rssepisodes.main.managers 69 64 92%
rssepisodes.main.models 144 106 73%
rssepisodes.main.views 75 60 80%
-----------------------------------------------
TOTAL 297 239 80%
And even more importantly: take a look at the files generated in build/coverage/; your code, in nicely formatted and colored HTML. Yeah!
I will try my very best to keep that script linked to above in sync with the Django development version. Contact me if you're having any trouble.