PYTHON · PYTHON FOR EVERYONE · CHAPTER 20

Testing

Write automated tests that check your code every time you change it.

8 min readCourse: Python for EveryoneLevel: beginner

From point A to point B

Point A: you test your code by running it by hand and checking whether the output "looks right". Every change forces you to repeat that review. Point B: by the end of this chapter, you'll write automated tests with doctest and unittest, run them with a single command and read their failure reports.

In network automation, a calculation error can end up as a wrong mask on 200 routers. Tests are your safety net before you touch real devices.

Types of tests

There are many ways to verify that a program works. These 3 are the most common:

  • Unit tests: they verify a small piece, such as a function or a class, in isolation.
  • Integration tests: they verify that several pieces work together, for example your script and a controller's API.
  • Regression tests: they verify that a new change didn't break something that already worked.

This chapter focuses on unit tests. They're fast, they don't need devices or a network, and they flag the error right where it is. Python includes 2 modules for writing them: doctest and unittest.

doctest: tests inside the documentation

In the previous chapter, you wrote docstrings. doctest takes advantage of that documentation: it looks for snippets that look like an interactive session and runs them.

The rule goes like this. A line that starts with >>> is code that gets run. The following lines, without a prompt, are the expected output. The example ends at a blank line or at the end of the docstring.

"""Basic IPv4 subnet calculations."""


def usable_hosts(prefix):
    """Returns how many host addresses fit in a prefix.

    >>> usable_hosts(24)
    254
    >>> [usable_hosts(p) for p in (29, 30)]
    [6, 2]
    >>> for p in (26, 27):
    ...     print(p, usable_hosts(p))
    26 62
    27 30
    >>> usable_hosts(33)
    Traceback (most recent call last):
        ...
    ValueError: prefix out of range: 33
    """
    if not 0 <= prefix <= 32:
        raise ValueError(f"prefix out of range: {prefix}")
    if prefix >= 31:
        return 2 ** (32 - prefix)
    return 2 ** (32 - prefix) - 2


if __name__ == "__main__":
    import doctest
    doctest.testmod()

Notice 3 details in the example:

  • Statements that span several lines, like the for, continue with ... instead of >>>.
  • For an exception, all you need is the Traceback line, an ellipsis and the last line with the type and the message.
  • The /31 and /32 prefixes are special cases (point-to-point links and single hosts), so the function doesn't subtract 2.

doctest.testmod() tests the current module. If everything passes, it shows nothing. To see each test, add -v when you run the script:

$ python subnets.py
$ python subnets.py -v
Trying:
    usable_hosts(24)
Expecting:
    254
ok
…
Trying:
    usable_hosts(33)
Expecting:
    Traceback (most recent call last):
        ...
    ValueError: prefix out of range: 33
ok
1 item had no tests:
    __main__
1 item passed all tests:
   4 tests in __main__.usable_hosts
4 tests in 2 items.
4 passed.
Test passed.

You can also pass verbose=True to testmod(). And you don't need the if __name__ == "__main__" block: python -m doctest subnets.py runs the examples of any module and exits with status code 1 if any of them fails.

Reading a doctest failure

Now introduce a bug on purpose: write * (multiply) instead of ** (power).

def usable_hosts(prefix):
    """Returns how many host addresses fit in a prefix.

    >>> usable_hosts(24)
    254
    >>> usable_hosts(30)
    2
    """
    return 2 * (32 - prefix) - 2   # bug: * instead of **


if __name__ == "__main__":
    import doctest
    doctest.testmod()
**********************************************************************
File "…/subnets_error.py", line 4, in __main__.usable_hosts
Failed example:
    usable_hosts(24)
Expected:
    254
Got:
    14
**********************************************************************
1 item had failures:
   1 of   2 in __main__.usable_hosts
***Test Failed*** 1 failure.

The report tells you the file, the line, the example that failed, what you expected and what you got. Also look at what it doesn't say: the /30 test passed. By coincidence, 2 * 2 - 2 and 2 ** 2 - 2 both give 2. A single test can be right by accident; several almost never are.

Python 3.14 update. The book used print as a statement, and its doctest output said "items". Today the messages say "item" or "items" depending on the count, and since 3.13 the output is shown in color in a compatible terminal. You can turn colors off with the NO_COLOR environment variable.

unittest: test classes and results

doctest shines with short examples. When you need to prepare data, test many cases or reuse code across tests, unittest is the better fit.

unittest belongs to the xUnit family. It descends from SUnit, the Smalltalk framework created by Kent Beck, one of the drivers of eXtreme Programming. JUnit (Java) and NUnit (.NET) belong to the same family. If you know one, you'll recognize the others.

The recipe has 3 steps:

  1. Create a class that inherits from unittest.TestCase.
  2. Add methods whose names start with test. Each one is a test.
  3. Call unittest.main(), which runs all those methods in alphabetical order.

Each test ends with one of 3 results:

  • OK (.): the test passed.
  • FAIL (F): a check wasn't met and AssertionError was raised.
  • ERROR (E): some other exception was raised. It usually points to a bug in the test itself or a case you didn't consider.
import unittest


class MinimalTests(unittest.TestCase):
    def test_passes(self):
        pass

    def test_fails(self):
        raise AssertionError("the condition isn't met")

    def test_error(self):
        {}["vlan"]


if __name__ == "__main__":
    unittest.main()
EF.
======================================================================
ERROR: test_error (__main__.MinimalTests.test_error)
----------------------------------------------------------------------
Traceback (most recent call last):
  …
KeyError: 'vlan'

======================================================================
FAIL: test_fails (__main__.MinimalTests.test_fails)
----------------------------------------------------------------------
Traceback (most recent call last):
  …
AssertionError: the condition isn't met

----------------------------------------------------------------------
Ran 3 tests in 0.001s

FAILED (failures=1, errors=1)

The first line, EF., sums up the 3 tests in alphabetical order: test_error, test_fails and test_passes.

TestCase assert methods

You could write an if and raise AssertionError by hand, but TestCase gives you methods that do it for you. Also, when they fail, they show a message that compares what you expected with what you got. They all accept an optional msg argument with your own message.

MethodChecks that…
assertEqual(a, b) / assertNotEqual(a, b)a == b / a != b
assertTrue(x) / assertFalse(x)x is true / false
assertIn(a, b) / assertNotIn(a, b)a is / isn't in b
assertIsNone(x) / assertIsInstance(x, T)x is None / is of type T
assertAlmostEqual(a, b, places=7)they're equal when rounded to 7 decimal places (or the number you give)
assertNotAlmostEqual(a, b, places=7)they differ when rounded
assertRaises(Exception)the code raises that exception
fail(msg)nothing: it always fails, immediately

assertAlmostEqual exists because floating-point numbers aren't exact: 0.1 + 0.2 is 0.30000000000000004. You almost always use assertRaises as a context manager, with with:

import ipaddress
import unittest


class IpaddressTests(unittest.TestCase):
    def test_private_network(self):
        net = ipaddress.ip_network("192.168.10.0/24")
        self.assertEqual(net.prefixlen, 24)
        self.assertTrue(net.is_private)
        self.assertIn(ipaddress.ip_address("192.168.10.7"), net)

    def test_host_bits(self):
        # 10.0.0.1/24 has host bits set: it isn't a valid network
        with self.assertRaises(ValueError):
            ipaddress.ip_network("10.0.0.1/24")

    def test_floats(self):
        self.assertAlmostEqual(0.1 + 0.2, 0.3)


if __name__ == "__main__":
    unittest.main()
Python 3.14 update. The book listed aliases such as failUnless, failIf, failUnlessEqual, failUnlessRaises and assert_. They were deprecated in Python 3.1 and 3.2 and removed in 3.12. Use their equivalents: assertTrue, assertFalse, assertEqual, assertNotEqual, assertAlmostEqual and assertRaises. Today there are also more expressive methods, such as assertIn, assertIsNone or assertLogs.

Preparing the context with setUp and tearDown

Many tests need some setup first: an inventory file, a connection, sample data. In the xUnit world, that's called a test fixture.

TestCase gives you 2 methods to build it and tear it down. setUp() runs before each test in the class and tearDown() runs after each one, even if the test fails. That way, every test starts with a clean environment.

import unittest


class FixtureOrder(unittest.TestCase):
    def setUp(self):
        print("setUp: opening the session with the router")
        self.vlans = [10, 20, 30]

    def tearDown(self):
        print("tearDown: closing the session")
        del self.vlans

    def test_count(self):
        print("  test: count")
        self.assertEqual(len(self.vlans), 3)

    def test_membership(self):
        print("  test: membership")
        self.assertIn(20, self.vlans)


if __name__ == "__main__":
    unittest.main()
setUp: opening the session with the router
  test: count
tearDown: closing the session
setUp: opening the session with the router
  test: membership
tearDown: closing the session

Now for a more realistic case. You have a network.py module with subnet functions and one that reads a CSV inventory:

"""Network functions we're going to test."""


def usable_hosts(prefix):
    """Returns how many host addresses fit in a prefix."""
    if not 0 <= prefix <= 32:
        raise ValueError(f"prefix out of range: {prefix}")
    if prefix >= 31:
        return 2 ** (32 - prefix)
    return 2 ** (32 - prefix) - 2


def occupancy(used, prefix):
    """Returns the percentage of hosts in use in the subnet."""
    return used / usable_hosts(prefix) * 100


def load_inventory(path):
    """Reads a hostname,ip CSV and returns a dictionary."""
    devices = {}
    with open(path, encoding="utf-8") as csv_file:
        for line in csv_file:
            hostname, ip = line.strip().split(",")
            devices[hostname] = ip
    return devices

In the same directory, you create test_network.py. The inventory class creates a temporary file in setUp and deletes it in tearDown:

import os
import tempfile
import unittest

from network import load_inventory, occupancy, usable_hosts


class SubnetTests(unittest.TestCase):
    def test_common_prefixes(self):
        self.assertEqual(usable_hosts(24), 254)
        self.assertEqual(usable_hosts(30), 2)

    def test_invalid_prefix(self):
        with self.assertRaises(ValueError):
            usable_hosts(33)

    def test_occupancy(self):
        self.assertAlmostEqual(occupancy(1, 26), 1.6129, places=4)


class InventoryTests(unittest.TestCase):
    def setUp(self):
        # Runs before EACH test in this class
        csv_file = tempfile.NamedTemporaryFile(
            "w", suffix=".csv", delete=False, encoding="utf-8"
        )
        csv_file.write("r1-lima,10.0.0.1\nr2-quito,10.0.0.2\n")
        csv_file.close()
        self.path = csv_file.name

    def tearDown(self):
        # Runs after EACH test, even if it fails
        os.remove(self.path)

    def test_reads_all_equipment(self):
        devices = load_inventory(self.path)
        self.assertEqual(len(devices), 2)
        self.assertIn("r1-lima", devices)

    def test_correct_ip(self):
        devices = load_inventory(self.path)
        self.assertEqual(devices["r2-quito"], "10.0.0.2", "IP read incorrectly")


if __name__ == "__main__":
    unittest.main()
.....
----------------------------------------------------------------------
Ran 5 tests in 0.001s

OK
Fact. If preparing the context is expensive, such as opening a connection, you can do it just once per class with the class methods setUpClass() and tearDownClass().

Running tests with python -m unittest

Calling unittest.main() from each file works, but a real project has many test files. The unittest module is also a command-line tool:

$ python -m unittest                          # discovers test*.py in the directory
$ python -m unittest -v                       # shows each test by name
$ python -m unittest test_network             # a specific module
$ python -m unittest test_network.InventoryTests
$ python -m unittest -k correct               # only tests containing "correct"
$ python -m unittest discover -s tests -p "test_*.py"

For example, python -m unittest -v test_network.InventoryTests shows each test in that class:

test_correct_ip (test_network.InventoryTests.test_correct_ip) ... ok
test_reads_all_equipment (test_network.InventoryTests.test_reads_all_equipment) ... ok

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

OK

With no arguments, unittest goes into discover mode: it looks for files whose names start with test and runs their tests. If any test fails, the command exits with status code 1. That lets a continuous integration system stop a deployment when something breaks.

Fact. Since Python 3.14, unittest shows its output in color in a compatible terminal. Be careful with -k: it searches for the string in the full test name. -k ip would also select test_reads_all_equipment, because "equipment" contains "ip".

pytest, the third-party alternative

unittest comes built in, so you don't need to install anything. Even so, many projects use pytest, a third-party package you install with pip. Its approach: tests as plain functions and Python's assert keyword, with no special methods.

import pytest

from network import load_inventory, usable_hosts


def test_common_prefixes():
    assert usable_hosts(24) == 254
    assert usable_hosts(30) == 2


def test_invalid_prefix():
    with pytest.raises(ValueError):
        usable_hosts(33)


@pytest.fixture
def inventory(tmp_path):
    path = tmp_path / "inventory.csv"
    path.write_text("r1-lima,10.0.0.1\nr2-quito,10.0.0.2\n", encoding="utf-8")
    return path


def test_reads_inventory(inventory):
    assert load_inventory(inventory)["r1-lima"] == "10.0.0.1"
$ python -m pip install pytest
$ python -m pytest -q
...                                                                      [100%]
3 passed in 0.02s

pytest fixtures replace setUp: a test asks for what it needs as a parameter. tmp_path is a built-in fixture that gives you a temporary directory and cleans it up for you.

pytest also runs your unittest tests unchanged, and with --doctest-modules it runs the doctests. You can start with unittest and migrate when you need to.

A practical detail: if you save this file alongside the others and run python -m unittest without pytest installed, discovery will fail with an ImportError when it imports pytest. Pick one tool per project, or install pytest in the environment.

Challenge

Answer before you open the solution.

1. In a doctest, how do you write the second line of a for loop?

Starting with .... The >>> prompt opens the statement; ... continues it, just like in the interactive interpreter.

2. A test shows E instead of F. What does that tell you?

That an exception other than AssertionError was raised. A check didn't fail: the code broke before that, for example with a KeyError.

3. You're migrating an old test that uses self.failUnlessEqual(a, b). What do you write in Python 3.14?

self.assertEqual(a, b). The failUnless* aliases were removed in Python 3.12.

4. A class has 4 tests. How many times does setUp() run?

4 times. Once before each test. If you want a single setup per class, use setUpClass().

5. Your function returns the right value for /30 even though it has a bug. What's the lesson?

Test several cases. A single value can match by chance. Include common cases, edge cases (/0, /31, /32) and invalid values.

Key takeaways

  • Unit tests verify small pieces quickly and in isolation.
  • doctest runs the >>> examples in your docstrings: documentation and test at once.
  • unittest: classes that inherit from TestCase, test_* methods and OK, FAIL or ERROR results.
  • Use the assert* methods; the fail* and assert_ aliases no longer exist.
  • setUp and tearDown prepare and clean up the context before and after each test.
  • python -m unittest discovers and runs everything; pytest is the most widely used third-party alternative.

Your code is now documented and tested. In the next chapter, you'll package it so other people can install it with a single command.

Official resources

Source and credits. This course is based on the book Python para todos by Raúl González Duque, published under the Creative Commons Attribution 2.5 Spain license. The original book was written for Python 2.5. Jesús Espinoza, with AI assistance, brought it to Python 3.14: he rewrote every chapter in his own words, replaced the examples with networking cases, updated the syntax and the modules that no longer exist, fixed errors in the original and tested all the code with Python 3.14.6 against the official documentation.

Navigate