How to unit test your python modules

      No Comments on How to unit test your python modules

Recently I’ve coded couple of modules for my data visualisation project and I wanted to ensure all my methods and classes are working as they should.

I had this structure of project


Now I wanted to write unit test for modules in package pkg. Here is what to do :

1] Create __init__.py

1st of all, there must exist __init__.py in the pkg. You can find out more about what this file does and how is it important if you google. For our purporose, it can be just empty.

2] Directory and your tests in the package

3] Write the tests and handle the imports

Now this is code for our moduleA.py we want to test

And this would be our unit test test_moduleA.py

So the important parts here are :
– We need to import python module unittest for unit testing
– Import our moduleA correctly
– The unit test methods must start with prefix test otherwise they won’t be runned

This is the file structure we have

4] Run your unit tests all at once

Now when our test is done, let’s run it ! Go to the pkg directory and run

This will search for all unit tests in current directory and all subdirectories and execute them

You can download the example files and file structure here :

codeUnitTests

Leave a Reply

Your email address will not be published. Required fields are marked *