Python Basics: Testing a Function with unittest
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_labelsThe 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=0Methods 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 -vThis 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=1A failed assertion is a failure; an unexpected exception is reported as an error. Both make this test command exit unsuccessfully.
Reference
Acknowledgements
This post was created with assistance from AI.