Unit test

A small automated check that verifies one piece of code behaves as expected.

A unit test runs a small part of your program with known inputs and checks the result. The simplest form is an assert statement: it raises an error if a condition isn't true and stays silent when it is. Testing pure helper functions lets you verify logic without touching real files or servers.

Python ships with the unittest module, and the popular third-party tool pytest lets you write tests as plain functions and runs them for you.

Example
def clean(name):
    return name.strip().lower()

# Quick checks before trusting it:
assert clean("  Ada ") == "ada"
assert clean("BO") == "bo"
print("All tests passed")
Output
All tests passed

Where this shows up in real Python

Unit tests prove a function works and catch regressions when you change code later — essential before trusting a script that touches real files.

Commonly used Unit test tools

  • assert result == expected — the simplest check
  • pytest — find and run test files
  • def test_thing(): — pytest collects functions named test_*
  • pytest.raises(ValueError) — assert that an error is raised

Official documentation: Python Library Reference: unittest