Skip to content
Python Basics: Testing a Function with unittest

Python Basics: Testing a Function with unittest

October 11, 2026

Python’s standard-library unittest module checks behavior automatically. Use Python 3.12 or newer on Linux. Run the shell commands in order in the same shell, starting in a fresh directory so the example files cannot overwrite your work:

cd "$(mktemp -d)"

Stop if this setup command fails.

Write a small function

Save as labels.py:

def make_label(name):
    cleaned_name = name.strip()
    if not cleaned_name:
        raise ValueError("name is required")
    return f"Hello, {cleaned_name}!"

The function removes surrounding whitespace and rejects an empty name.

Test results and exceptions

Save as test_labels.py:

import unittest
from labels import make_label


class LabelTests(unittest.TestCase):
    def test_greeting(self):
        self.assertEqual(make_label("Ada"), "Hello, Ada!")

    def test_surrounding_spaces(self):
        self.assertEqual(make_label("  Ada  "), "Hello, Ada!")

    def test_blank_name(self):
        with self.assertRaises(ValueError):
            make_label("   ")

Run:

python3 -m unittest -v test_labels

The runner reports three passing tests and finishes with OK. Its timing line varies. Check the command’s status immediately afterward:

printf 'exit=%s\n' "$?"

Output:

exit=0

Methods beginning with test are tests. assertEqual() compares actual and expected results. assertRaises() fails if the expected exception is not raised.

Discover tests in the directory

python3 -m unittest discover -v

This also runs three tests. Discovery normally looks for test*.py files starting in the current directory. A filename such as checks.py would not match that default pattern.

See a failure safely

Leave the working tests alone and run a separate, deliberately wrong expectation. Use an ordinary shell without set -e so the final printf runs after the intentional failure:

Save as wrong_expectation.py:

import unittest
from labels import make_label


class WrongExpectation(unittest.TestCase):
    def test_greeting(self):
        self.assertEqual(make_label("Ada"), "Goodbye, Ada!")


unittest.main()

Run:

python3 wrong_expectation.py
printf 'exit=%s\n' "$?"

The runner prints a failure showing the two different strings to standard error. The final line on standard output is:

exit=1

A failed assertion is a failure; an unexpected exception is reported as an error. Both make this test command exit unsuccessfully.

Reference

Python unittest documentation

Acknowledgements

This post was created with assistance from AI.

Last updated on