Short Hand Series: unittest

Test-Driven Development is a software development process that uses test cases to aid in the process of development. The test is described, allowed to successfully fail. The Minimal functional code is written that pass the test. It is then important to refactor the code for optimization, readability, and documentation.

+-----------------------------------+
| |
| define test +-------> fail test |
| ^ + |
| | | |
| | | |
| + Write Code |
| pass test | |
| ^ | |
| | | |
| + v |
| refactor <----------+ pass test |
| |
+-----------------------------------+
simple representation of the TDD

The process is then repeated for each added feature in that particular stage of the project stage . This manner of development focuses on features rather than code volume, therefore making it highly compatible with the Agile Software Development Cycle


In Python, tests are defined using the packageunittest. The specified test cases are run using nosetests from the nose package. The minimum requirement to create a test is a class extending unittest.TestCase class and a function defined the prefix test_ as the name. The test should include input, expected output and a comparison function between the current output and expected output of the function, given the defined input

Comparison between the function output and expected output is done using Assert statements. The most commonly used Assert statements include: assertEqual/assertNotEqual, assertTrue/assertFalse, assertIn/assertNotIn and assertIsInstance/assertIsNotInstance.

Sample directory layout:

app
+
+-+ __init__.py
|
+-+ buildings.py
+
tests
+
+-+ __init__.py
|
+-+ test_buildings.py

Sample unittest class:

import unittest

from app.buildings import CommercialBuilding, BaseBuilding

class TypeOfBuildingTest(unittest.TestCase):

def test_building_is_instance_of_object(self):
bld = BaseBuilding()
self.assertIsInstance(bld, object,
msg='BaseBuilding should be an instance of object')

def test_commercial_instance_of_building(self):
bld = CommercialBuilding()
self.assertIsInstance(bld, BaseBuilding,
msg='Commercial should be an instance of BaseBuilding')

Some considerations:

  • Include empty __init__.py file in each sub-directory of the package. this enable the python interpreter access the folder as a package
  • Install rednose package to have colored output.
  • Ensure the test function definition start with test_ for the test package to identify and run the test
  • The failure message should be specific and should describe the expected output on valid input from the test case
  • Include tests that should successfully fail to confirm the accuracy of the input validation program
  • Include edge cases i.e unexpected input, invalid input and test for appropriate action by the function

More information on unittest from Python docs

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.