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
1 2 3 |
. └── pkg └── moduleA.py |
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.
1 2 3 4 5 |
. . └── pkg ├── __init__.py └── moduleA.py |
2] Directory and your tests in the package
1 2 3 4 5 6 7 |
. └── pkg ├── __init__.py ├── moduleA.py └── tests ├── __init__.py └── test_moduleA.py |
3] Write the tests and handle the imports
Now this is code for our moduleA.py
we want to test
1 2 |
def ReturnBack(ret): return ret |
And this would be our unit test test_moduleA.py
1 2 3 4 5 6 7 8 9 10 |
import pkg.moduleA import unittest class test_moduleA(unittest.TestCase): def test_passingTest(self): self.assertTrue(True) self.assertEquals( pkg.moduleA.ReturnBack("A"), "A" ) def test_passingNotTest(self): self.assertTrue(False) |
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
1 2 3 4 5 6 7 |
. └── pkg ├── __init__.py ├── moduleA.py └── tests ├── __init__.py └── test_moduleA.py |
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
1 |
python -m unittest discover . |
This will search for all unit tests in current directory and all subdirectories and execute them
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
stasp:code PatrikStas$ python -m unittest discover . F. ====================================================================== FAIL: test_passingNotTest (pkg.tests.test_moduleA.test_moduleA) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/PatrikStas/pyunittest/code/pkg/tests/test_moduleA.py", line 10, in test_passingNotTest self.assertTrue(False) AssertionError: False is not true ---------------------------------------------------------------------- Ran 2 tests in 0.000s FAILED (failures=1) |
You can download the example files and file structure here :