Thuta Learning
Python
AdvancedProgrammingBeginner

Unit Testing

PythonLesson 5240 min

What you'll walk away with

  • Write a unittest.TestCase subclass with test_ methods using assertEqual and assertRaises
  • Structure a test in the three Arrange-Act-Assert steps
  • Cover normal, boundary and invalid inputs as a table with subTest or pytest.mark.parametrize
  • Explain how python -m unittest and pytest find and run tests
  • Replace an outside dependency such as the network with unittest.mock so tests stay fast and stable

Explain it simply

Unit testing in plain language

A unit test is a short piece of code that gives one small part of your program, a function or a method, an input and checks that the expected output comes back. Unlike checking print() output by eye, tests rerun with a single command, thousands of times, and tell you exactly where something broke.

It is like quality control in a car factory: each brake is tested on its own rig before it goes into a car, which is much faster than hunting for the fault in a finished car. Run the tests after every change, and within seconds you know that what used to work still works.

Problem → Why → Solution

The problem: checking only the happy path by eye

You write divide(), see print(divide(10, 2)) show 5.0, and call it done. Two weeks later a teammate removes the zero check, thinking it is unnecessary, and nobody tries divide(10, 0) again, so you find out when production raises ZeroDivisionError. The real problem is not the code; it is that the checking lived in someone's memory.

manual_check.py
def divide(a, b):
    return a / b          # someone removed: if b == 0: raise ValueError(...)

print(divide(10, 2))      # 5.0 -- "looks right", so ship it
# divide(10, 0) is never tried again, and nothing fails until production

What automated tests change

A test writes the rule 'divide(10, 0) must raise ValueError' down as code. A commit that removes the rule makes the test fail immediately, and CI blocks the merge. Tests are also documentation that runs: they show by example what the function is supposed to do.

Core concept: TestCase, assertions and test discovery

In the standard library's unittest, tests live in a class that subclasses unittest.TestCase. Every method whose name starts with test_ is a test; the runner ignores other names. Each method runs on a fresh instance of the class, so self attributes changed by one test do not leak into the next. A setUp() method, if present, runs before every test to prepare the same starting state.

Shape each test in three steps, Arrange-Act-Assert: prepare the data and objects (arrange), call the function under test once (act), and check the result (assert). When an assertion fails, the test is a FAIL and shows the expected and the actual value. An unexpected exception inside a test is reported separately as an ERROR.

AssertionChecks
assertEqual(a, b)a == b, showing both values on failure
assertTrue(x) / assertIn(a, b)x is truthy / a is inside b
assertAlmostEqual(a, b)two floats agree to 7 decimal places
with assertRaises(Error):the block must raise that exception

python -m unittest searches the current folder for test*.py files (test discovery) and runs the TestCase classes inside. Tests within a class run in alphabetical order of their names, so tests must never depend on each other's order. The third-party package pytest runs unittest tests too, and also allows shorter test functions that use a plain assert.

What to test matters as much as how. For each function, think of three kinds of case: a normal input such as (10, 4), a boundary input such as 0, an empty list or the largest allowed value, and an invalid input such as dividing by zero or a malformed string. Most bugs hide at the boundaries. Name tests after the behaviour, like test_divide_by_zero, so a failure report tells you what broke just from the name.

The life of one test
  1. Runner finds a test_ method
  2. New instance, then setUp()
  3. Arrange -> Act -> Assert
  4. Record ok, FAIL or ERROR

Read FAIL as 'the code gave a wrong answer' (an assertion failed) and ERROR as 'the test itself blew up' (an unexpected exception).

General pattern

python
import unittest

class TestThing(unittest.TestCase):
    def setUp(self):
        self.data = make_fresh_data()            # Arrange (runs before each test)

    def test_behaviour(self):
        result = function_under_test(self.data)  # Act
        self.assertEqual(result, expected)       # Assert

if __name__ == "__main__":
    unittest.main()

One TestCase subclass, and in each test_ method one act and one assert: that is the shape of most tests. unittest.main() runs every test in the file when you execute it directly.

Worked example: four tests for add() and divide()

Printing 'OK' lines with print() only pretends to run tests; this script really runs them. unittest's report includes a timing such as 'Ran 4 tests in 0.001s' that changes on every run, so the report goes into a buffer and only the numbers from the result object are printed. On your own machine, running with unittest.main() or python -m unittest is the normal way.

test_math.py
import io
import unittest


def add(a, b):
    return a + b


def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b


class TestMathFunctions(unittest.TestCase):
    def test_add_positive_numbers(self):
        self.assertEqual(add(5, 3), 8)

    def test_add_negative_numbers(self):
        self.assertEqual(add(-5, -3), -8)

    def test_divide_normal(self):
        self.assertEqual(divide(10, 4), 2.5)

    def test_divide_by_zero(self):
        with self.assertRaises(ValueError):
            divide(10, 0)


if __name__ == "__main__":
    # unittest.main() also works; here the report goes to a buffer so the
    # timing line ("Ran 4 tests in 0.001s") does not change the output.
    suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestMathFunctions)
    result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
    for name in unittest.defaultTestLoader.getTestCaseNames(TestMathFunctions):
        print(name)
    print(f"ran {result.testsRun}, failures {len(result.failures)}, "
          f"errors {len(result.errors)}")
    print("all passed:", result.wasSuccessful())

Code breakdown

  1. A test classclass TestMathFunctions(unittest.TestCase):

    Subclassing TestCase gives you assertion methods such as assertEqual and tells the runner this class holds tests.

  2. One behaviour per test self.assertEqual(divide(10, 4), 2.5)

    10 / 4 is chosen because the answer is not a whole number: if someone swaps / for //, the result becomes 2 and this test fails. 2.5 is exactly representable as a float, so assertEqual is safe here.

  3. Expecting an exception with self.assertRaises(ValueError):

    The test passes only if a ValueError is raised inside the with block. No exception, or a different type such as ZeroDivisionError, makes it fail, which is how the deleted zero check gets caught.

  4. Running without timing noise result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)

    TextTestRunner writes its report into a StringIO buffer and returns a TestResult. testsRun, failures, errors and wasSuccessful() give the same values on every run.

  5. Discovery order for name in unittest.defaultTestLoader.getTestCaseNames(TestMathFunctions):

    The loader returns the test_ method names in alphabetical order. Notice in the output that test_add_negative_numbers comes before the positive one, which is not the order in the file.

You should see
test_add_negative_numbers
test_add_positive_numbers
test_divide_by_zero
test_divide_normal
ran 4, failures 0, errors 0
all passed: True

pytest and table-driven tests

pytest is installed with pip install pytest. It needs no class: plain functions whose names start with test_ use a plain assert, and on failure it shows the values inside the expression in detail. @pytest.mark.parametrize runs each case as a separate test, so one failing case does not hide the others.

test_pricing.py
import pytest


def apply_discount(price, percent):
    if not 0 <= percent <= 100:
        raise ValueError("percent must be 0-100")
    return round(price * (1 - percent / 100), 2)


@pytest.mark.parametrize("price, percent, expected", [
    (100, 10, 90.0),     # normal
    (59.99, 0, 59.99),   # boundary: no discount
    (20, 100, 0.0),      # boundary: free
])
def test_apply_discount(price, percent, expected):
    assert apply_discount(price, percent) == expected


def test_rejects_bad_percent():
    with pytest.raises(ValueError, match="0-100"):
        apply_discount(100, 150)
bash
python -m unittest            # discover and run test*.py with unittest
python -m unittest -v         # one line per test
pytest -q                     # run with pytest, quiet summary
pytest -k discount            # only tests whose name contains "discount"

When code calls something outside your program, such as the network, a database or the clock, replace that dependency with a fake in unit tests. The function below accepts its HTTP function as a parameter, so the test passes in a Mock, controls the data it returns and checks how it was called.

test_weather.py
import unittest
from unittest import mock


def fetch_temperature(city, http_get):
    data = http_get(f"https://api.example.com/weather?city={city}")
    return round(data["temp_c"])


class TestWeather(unittest.TestCase):
    def test_rounds_the_temperature(self):
        fake_get = mock.Mock(return_value={"temp_c": 31.6})
        self.assertEqual(fetch_temperature("Yangon", fake_get), 32)
        fake_get.assert_called_once_with("https://api.example.com/weather?city=Yangon")

In real projects

Testing in real projects

Teams split tests into three kinds. Unit tests check single functions in milliseconds and are the most numerous. Integration tests check the places where code meets a database, files or an outside API. End-to-end tests drive a browser through a whole user flow; they are slow, so there are only a few of them.

  • CI: a service such as GitHub Actions runs pytest on every pull request and blocks the merge when anything fails.
  • Business rules such as price calculations are protected by parametrized table tests covering normal, boundary (0 and 100 percent) and invalid cases.
  • Code that writes files is tested inside tempfile.TemporaryDirectory or pytest's tmp_path fixture so nothing is left behind.
  • Every bug fix starts with a regression test that reproduces the bug, and only then the fix.

Common mistakes

Common mistakes with testing

Passing an already-called function to assertRaises

In self.assertRaises(ValueError, divide(10, 0)), divide(10, 0) runs before assertRaises is even called, so the exception escapes the test and you get an ERROR. Use a with self.assertRaises(ValueError): block, or pass the function and its arguments separately: self.assertRaises(ValueError, divide, 10, 0).

Tests that depend on order or shared state

If test_create appends to a module-level list and test_count assumes that item is there, test_count fails when it runs alone. Every test should build its own data in setUp() or a fixture, so the result is the same in any order.

Calling a live API from unit tests

On the day the internet drops, the API rate limit hits or the weather data changes, the test fails although your code is fine. Flaky tests like this teach a team to ignore failures. Replace the dependency with a mock in unit tests and call the real API only in a few integration tests.

Mini challenge

Mini challenge: test parse_price

Write a parse_price() function that turns text like '1,250.50 MMK' into a float, plus a unittest test class for it. Check the valid cases as a table with subTest, check that bad input raises ValueError, and finally print how many tests ran and whether they passed.

  • parse_price removes commas, a trailing 'MMK' and spaces, then returns a float
  • Raise ValueError for empty text and for negative prices
  • Check at least three valid cases with subTest, including the boundary 0
  • Check four invalid inputs ('', 'MMK', '-5', 'abc') with assertRaises
test_parse_price.py
import io
import unittest


def parse_price(text):
    """Turn '1,250.50 MMK' style text into a float; reject bad input."""
    # TODO: clean the text, convert to float, reject empty and negative values
    ...


class TestParsePrice(unittest.TestCase):
    def test_valid_prices(self):
        cases = []  # TODO: (text, expected) pairs, including a zero price
        for text, expected in cases:
            with self.subTest(text=text):
                ...  # TODO: assert

    def test_rejects_bad_input(self):
        # TODO: each bad input must raise ValueError
        ...


if __name__ == "__main__":
    # TODO: run the suite with a buffered runner and print the results
    ...

Expected: It prints 'tests run: 2', 'failures: 0, errors: 0' and 'OK'. The subTest cases live inside two test methods, so testsRun is 2.

Show hint

str.removesuffix("MMK") (Python 3.9+) removes the suffix only when it is there. float("abc") already raises ValueError on its own. subTest keeps checking the remaining cases after one fails and names the failing text in the report.

Show solution
test_parse_price.py
import io
import unittest


def parse_price(text):
    """Turn '1,250.50 MMK' style text into a float; reject bad input."""
    cleaned = text.replace(",", "").strip().removesuffix("MMK").strip()
    if not cleaned:
        raise ValueError("empty price")
    value = float(cleaned)
    if value < 0:
        raise ValueError("negative price")
    return value


class TestParsePrice(unittest.TestCase):
    def test_valid_prices(self):
        cases = [("1,250.50 MMK", 1250.5), ("99", 99.0), (" 0 MMK", 0.0)]
        for text, expected in cases:
            with self.subTest(text=text):
                self.assertEqual(parse_price(text), expected)

    def test_rejects_bad_input(self):
        for text in ["", "MMK", "-5", "abc"]:
            with self.subTest(text=text):
                with self.assertRaises(ValueError):
                    parse_price(text)


if __name__ == "__main__":
    suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestParsePrice)
    result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
    print(f"tests run: {result.testsRun}")
    print(f"failures: {len(result.failures)}, errors: {len(result.errors)}")
    print("OK" if result.wasSuccessful() else "FAILED")

Quick quiz 1 / 3

A TestCase class has three methods: test_add, check_divide and testSubtract. How many tests does unittest run?

Quick quiz 2 / 3

A test contains self.assertRaises(ValueError, divide(10, 0)), and divide correctly raises ValueError. What is the test result?

Quick quiz 3 / 3

A unit test for a weather function calls the real API and sometimes fails. What is the best fix?

What to remember

  • A unit test checks one small piece of code automatically, in the Arrange-Act-Assert shape.
  • unittest runs the methods with the test prefix of a TestCase subclass, each on a fresh instance, in alphabetical order.
  • Check exceptions with with self.assertRaises(...), and cover normal, boundary and invalid cases as a table with subTest or parametrize.
  • Mock outside dependencies such as the network in unit tests, and never let tests depend on order or shared state.

Python Standard Library — unittest — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Unit Testing | Thuta Learning