Skip to content

Unittest The Python builtin library for unit testing

BraveJero edited this page Oct 3, 2021 · 12 revisions

Unittest: The Python builtin library for unit testing

The unittest unit testing framework was originally inspired by JUnit and has a similar flavor as major unit testing frameworks in other languages.

The four pillars of unittest

Unittest supports some important testing concepts:

  • test fixture: represents the preparation needed to perform one or more tests, and any associated cleanup actions.

  • test case: is the individual unit of testing. It checks for a specific response to a particular set of inputs.

  • test suite: is a collection of test cases, test suites, or both. It is used to aggregate tests that should be executed together.

  • test runner: is a component which orchestrates the execution of tests and provides the outcome to the user.

Creating our first iteration

As we saw in A brief introduction of the case study, we have a class called Point that will help us to represent the points of the figures that we are going to create. So let's start by writing the necessary tests that we want the Point class to implement.

First of all, we are going to create two files: test_point.py (where we define what properties we want the Point class to have) and Point.py (where we will implement those properties).

So, our project would look similar to:

src/
    __init__.py
    Point.py
tests/
    __init__.py
    test_point.py

Red step: write a test and watch it fail

Now, let's write the first tests for the properties we want from the Point class:

# test_point.py

import unittest

from src.Point import Point

class TestPoint(unittest.TestCase):

    def setUp(self):
        """Creates a Point() object with (x, y) = (3.0, 4.0)"""
        self.point = Point(3.0, 4.0)

    def test_get_x(self):
        self.assertEqual(self.point.get_x(), 3.0)

    def test_get_y(self):
        self.assertEqual(self.point.get_y(), 4.0)
# Point.py

class Point:
    pass

Then, we run the following command (note that poetry is only to handle dependencies correctly and for that reason we do not explain it in this wiki):

$ poetry run python -m unittest -v tests/test_point.py
======================================================================
ERROR: test_get_x (tests.test_point.TestPoint)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "path_to_project/tests/test_point.py", line 8, in setUp
    self.point = Point(3.0, 4.0)
TypeError: Point() takes no arguments

======================================================================
ERROR: test_get_y (tests.test_point.TestPoint)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "path_to_project/tests/test_point.py", line 8, in setUp
    self.point = Point(3.0, 4.0)
TypeError: Point() takes no arguments

----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (errors=2)

Green step: write just enough production code to get the test to pass

Now, we add the methods required to pass the tests:

# Point.py

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def get_x(self):
        return self.x
    
    def get_y(self):
        return self.y
$ poetry run python -m  unittest -v tests/test_point.py
test_get_x (tests.test_point.TestPoint) ... ok
test_get_y (tests.test_point.TestPoint) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

Blue step: refactor the code to fix it

Now, we refactor the code:

class Point:
    def __init__(self, x: float, y: float):
        self.x = x
        self.y = y

    def get_x(self) -> float:
        return self.x
    
    def get_y(self) -> float:
        return self.y
$ poetry run python -m  unittest -v tests/test_point.py
test_get_x (tests.test_point.TestPoint) ... ok
test_get_y (tests.test_point.TestPoint) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

Iterate

Congratulations! We just finished our first iteration!

For practical purposes we are not going to show all the iterations to make the code (which can be seen finished in this repository). We prefer then, to show more in detail the tools that unittest offers us as a library.

Unittest fundamentals

Command-Line Interface

For a list of all the command-line options:

$ python -m unittest -h
Usage: python -m unittest [options] [tests]

Options:
  -h, --help       Show this message
  -v, --verbose    Verbose output
  -q, --quiet      Minimal output
  -f, --failfast   Stop on first failure
  -c, --catch      Catch control-C and display results
  -b, --buffer     Buffer stdout and stderr during test runs

Examples:
  python -m unittest test_module               - run tests from test_module
  python -m unittest module.TestClass          - run tests from module.TestClass
  python -m unittest module.Class.test_method  - run specified test method

[tests] can be a list of any number of test modules, classes and test
methods.

Alternative Usage: python -m unittest discover [options]

Options:
  -v, --verbose    Verbose output
  -f, --failfast   Stop on first failure
  -c, --catch      Catch control-C and display results
  -b, --buffer     Buffer stdout and stderr during test runs
  -s directory     Directory to start discovery ('.' default)
  -p pattern       Pattern to match test files ('test*.py' default)
  -t directory     Top level directory of project (default to
                   start directory)

For test discovery all test modules must be importable from the top
level directory of the project.

Organizing test code

The basic building blocks of unit testing are test cases — single scenarios that must be set up and checked for correctness. In unittest, test cases are represented by unittest.TestCase instances.

Note The order in which the various tests will be run is determined by sorting the test method names with respect to the built-in ordering for strings.

It is recommended that you use TestCase implementations to group tests together according to the features they test. unittest provides a mechanism for this: the test suite, represented by unittest’s TestSuite class.

For example, if we want to have a TestSuite with the tests of all the figures we would do:

# tests/test_suite.py

import unittest

from tests import test_point
from tests import test_ellipse 
from tests import test_circle
from tests import test_triangle
from tests import test_rectangle 

def suite():
    test_suite = unittest.TestSuite()
    loader = unittest.TestLoader()
    test_suite.addTests(loader.loadTestsFromModule(test_point))
    test_suite.addTests(loader.loadTestsFromModule(test_rectangle))
    test_suite.addTests(loader.loadTestsFromModule(test_triangle))
    test_suite.addTests(loader.loadTestsFromModule(test_ellipse))
    test_suite.addTests(loader.loadTestsFromModule(test_circle))
    return test_suite

runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite())
$ poetry run python -m unittest -v tests/test_suite.py
test_distanceTo (tests.test_point.TestPoint) ... ok
test_equals (tests.test_point.TestPoint) ... ok
test_get_x (tests.test_point.TestPoint) ... ok
test_get_y (tests.test_point.TestPoint) ... ok
test_str (tests.test_point.TestPoint) ... ok
test_area (tests.test_rectangle.TestRectangle) ... ok
test_base (tests.test_rectangle.TestRectangle) ... ok
test_even_area (tests.test_rectangle.TestRectangle) ... ok
test_height (tests.test_rectangle.TestRectangle) ... ok
test_is_rectangle (tests.test_rectangle.TestRectangle) ... ok
test_perimeter (tests.test_rectangle.TestRectangle) ... ok
test_str (tests.test_rectangle.TestRectangle) ... ok
test_area (tests.test_triangle.TestTriangle) ... ok
test_is (tests.test_triangle.TestTriangle) ... ok
test_perimeter (tests.test_triangle.TestTriangle) ... ok
test_str (tests.test_triangle.TestTriangle) ... ok
test_area (tests.test_ellipse.TestEllipse) ... ok
test_is (tests.test_ellipse.TestEllipse) ... ok
test_perimeter (tests.test_ellipse.TestEllipse) ... ok
test_str (tests.test_ellipse.TestEllipse) ... ok
testSkip (tests.test_circle.TestCircle) ... skipped 'This could be used to avoid a test'
test_area (tests.test_circle.TestCircle) ... Test finished!
ok
test_is (tests.test_circle.TestCircle) ... Test finished!
ok
test_perimeter (tests.test_circle.TestCircle) ... Test finished!
ok
test_perimeter_fail (tests.test_circle.TestCircle) ... Test finished!
expected failure
test_str (tests.test_circle.TestCircle) ... Test finished!
ok

----------------------------------------------------------------------
Ran 26 tests in 0.002s

OK (skipped=1, expected failures=1)

Skipping tests and expected failures

Unittest supports skipping individual test methods and even whole classes of tests. In addition, it supports marking a test as an “expected failure,” a test that will fail, but shouldn’t be counted as a failure on a TestResult.

The following decorators and exception implement test skipping and expected failures:

@unittest.skip(reason)

Unconditionally skip the decorated test. 
reason should describe why the test is being skipped.

@unittest.skipIf(condition, reason)

Skip the decorated test if condition is true.

@unittest.skipUnless(condition, reason)

Skip the decorated test unless condition is true.

@unittest.expectedFailure

Mark the test as an expected failure or error. 
If the test fails or errors in the test function itself (rather than in one of the test fixture methods) then it will be considered a success. 
If the test passes, it will be considered a failure.

exception unittest.SkipTest(reason)

This exception is raised to skip a test.

Subtests

When there are very small differences among your tests, for instance some parameters, unittest allows you to distinguish them inside the body of a test method using the subTest() context manager.

List of assert methods

Common Assertions

Method
assertTrue(x, msg=None)
assertFalse(x, msg=None)
assertIsNone(x, msg=None)
assertIsNotNone(x, msg=None)
assertEqual(a, b, msg=None)
assertNotEqual(a, b, msg=None)
assertIs(a, b, msg=None)
assertIsNot(a, b, msg=None)
assertIn(a, b, msg=None)
assertNotIn(a, b, msg=None)
assertIsInstance(a, b, msg=None)
assertNotIsInstance(a, b, msg=None)

Other Assertions

Method
assertAlmostEqual(a, b, places=7, msg=None, delta=None)
assertNotAlmostEqual(a, b, places=7, msg=None, delta=None)
assertGreater(a, b, msg=None)
assertGreaterEqual(a, b, msg=None)
assertLess(a, b, msg=None)
assertLessEqual(a, b, msg=None)
assertRegex(text, regexp, msg=None)
assertNotRegex(text, regexp, msg=None)
assertCountEqual(a, b, msg=None)
assertMultiLineEqual(a, b, msg=None)
assertSequenceEqual(a, b, msg=None)
assertListEqual(a, b, msg=None)
assertTupleEqual(a, b, msg=None)
assertSetEqual(a, b, msg=None)
assertDictEqual(a, b, msg=None)

Exceptions and warnings

Method
assertRaises(exception)
assertRaisesRegex(exception, regexp)
assertWarns(warn, fun, *args, **kwds)
assertWarnsRegex(warn, fun, *args,**kwds)

Grouping tests

Loading and running tests

Clone this wiki locally