Feature Spotlight: Python Code Coverage with PyCharm
Happy Friday everyone!
Hopefully, most of us are aware of what code coverage is and how it’s being used in the software development process. It helps ensure that our code actually is executed and what’s equally important, our tests actually are testing our code. This is essential for any software written in any language, including Python.
I’ve already covered how PyCharm helps you write clean, quality, maintainable code as well as test it with the integrated graphical test runner. This post will supplement earlier blog posts by highlighting Code Coverage support available in PyCharm.
Basically, everything is quick and simple. To collect coverage statistics, all you need to do is have your code open in PyCharm, have the project Python interpreter specified in the project settings, and have one or several run configurations (preferably including some configurations for tests).
In this short example, I have a project open in PyCharm, with Python interpreter defined in the project settings:
This project contains some tests, which can be run by the nose testing framework. I define the test configuration in PyCharm by clicking “Edit configurations”:
After that, I specify my new ‘Nosetest_run’ configuration in the dialog:
So now I’m able to run my code using this configuration in different modes, including simple run, debug, profiler, and especially ‘Run with Coverage’:
When done, PyCharm gives me the full report on the test run, including coverage data:
Browse the coverage tool window to check the coverage percentage for each directory or file. You can also navigate to any file straight from this tool window, as well as perform other common actions like “Generate Coverage Report” which will show you the full coverage report in HTML:
Note that you can inspect the result of the coverage report right inside the editor. In the left-hand editor gutter, PyCharm marks covered lines with green, and uncovered ones in red:
By the way, PyCharm uses the standard coverage.py tool created by Ned Batchelder. To have it working, make sure it’s installed on your project interpreter (check your PyCharm project settings).
That’s it! I hope you try this very useful code coverage integration and make use of it often.
Just in case you’re craving for more details, check out the official PyCharm documentation.
Talk to you soon,