unittest Testing Framework

Qualified supports the unittest unit testing framework.

From Python 3.7, solution module is no longer imported implicitly to avoid confusing error messages. Tests must import solution from the solution module and any preloaded code is available in the preloaded module.

Basic Example

The following notes are adopted from unittest — Basic Example..

The unittest module provides a rich set of tools for constructing and running tests. This section demonstrates that a small subset of the tools suffice to get started.

Here is a short script to test three string methods:

import unittest

# The name of the test case class is not limited to "Test" and test module can have multiple classes.
class Test(unittest.TestCase):

  def test_upper(self):
      self.assertEqual('foo'.upper(), 'FOO')

  def test_isupper(self):
      self.assertTrue('FOO'.isupper())
      self.assertFalse('Foo'.isupper())

  def test_split(self):
      s = 'hello world'
      self.assertEqual(s.split(), ['hello', 'world'])
      # check that s.split fails when the separator is not a string
      with self.assertRaises(TypeError):
          s.split(2)

Tests

In the example, the three individual tests are defined with methods whose names start with the letters test. This naming convention informs the test runner about which methods represent tests.

Assertions

The crux of each test is a call to assertEqual() to check for an expected result; assertTrue() or assertFalse() to verify a condition; or assertRaises() to verify that a specific exception gets raised. These methods are used instead of the assert statement so the test runner can accumulate all test results and produce a report.

Setup and Tear Down

The setUp() and tearDown() methods allow you to define instructions that will be executed before and after each test method.

Learn More

You can learn how to use it on the Python Website: