Python Unit Test

Unit testing is pretty awesome in the world of programming.

In short: write test conditions that check the code. If the code fails to meet the specified conditions, errors are raised to indicate that something bad or unexpected happened.

Python comes with a built in unit testing framework called… (cue drumroll) … unittest.

Test File #

There are common conventions to naming and positioning test scripts.

Options include:

  1. Place the test script in the same directory as the main code, and prepend “test_” to the test script.
  2. Same as the first option, but append “_test” instead.
  3. Place all the test scripts in a test/ directory.

Test Code #

The body of the code usually starts with:

import unittest
import <whatever modules that will be needed>

Within the test script, create the class to perform tests.

class Test<something descriptive to indicate what is being tested>(unittest.TestCase):
  def test_<function to be tested>(self):
    result = <function with parameters>
    self.assert<condition>

Note the methods in the test script need to start with “test_”. This is a strict convention.

There are numerous assert conditions. It’s probably best to check the documentation for more details.

Running the tests #

To run a specific test script, navigate to the script directory, then run:

python3 -m unittest <test script>.py

To run all available tests, which will be found through test discovery:

python3 -m unittest

To run a specific test script without having to include the -m unitest bit, modify the test script to include the following at the end:

if __name__ == '__main__':
  unittest.main()