Thursday, January 9, 2014

Check coverage percentage in Python

When I wrote about TDD I mentioned that it ensures that you have a high coverage percentage. But how to actually see that? I'll show you one tool to do that in Python. Very useful to have all the code tested.

Note: This tutorial is for Windows. I used Windows 8. There is no much difference with other versions of Windows.

Requirements:

Python installed.

Steps:

1. Install Coverage. Coverage is a tool for Python that you can download and user for free. To install it:
   1.1 Install Setuptools. You have to download setuptools-2.1.tar.gz.
   1.2 Extract that file somewhere you can access easyly.
   1.3 Open a CMD console and go to the extracted folder.
   1.4  For this step you should already have Python in path. Enter:

python setup.py install

It's the same with mnost of Python components. Whenever you have to install something in Python, try this method.

   1.5 Download coverage-3.7.1.tar.gz.
   1.6 Install it with the same steps you took to install Setuptools.

2. Add Coverage to the Path.
   2.1 Go to: <Python installation folder>\Scripts. In my case, it's: C:\Python27\Scripts.
   2.2 Copy that path.
   2.3 Right click on Computer > Properties > Advanced system settings > Environment Variables
   2.4 Double click Path
   2.5 At the end of the text line, paste the path you copied in step 2.1. There must be a semicolon between the last entry and the new one. Like this:
Then press OK in all the dialogs.
   2.6 To check if Coverage is available, open a CMD console and enter: coverage. You should see this:
3. Use Coverage!
   3.1 Now you'll need a Python program and it corresponding tests. You can use the code I showed in this article.
   3.2 Save the application and the test cases in a folder.
   3.3 Open a CMD window and go to the folder with the scripts.
   3.4 Enter:

coverage run test.py
In this case, the name of the module that contains the test cases is "test.py". Then, enter:

coverage html

Go to the folder with the scripts and you'll see a new folder called "htmlcov". Open it.
Open index.html. Now, you'll see the report in a browser:
This report contains useful information. For example, here I can see which lines are not tested yet. This will help you to correct or adjust your test cases (not just in TDD).

Enjoy it!

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...