Reading history

Python Unit Testing with unittest and pytest

6 min read 0 views

Learn unit testing in Python: unittest.TestCase, assertEqual, assertRaises, assertAlmostEqual, setUp, running tests, reading failures, and pytest basics.

A unit test is a small piece of code that checks one function or class gives the right answer. Once written, tests run in seconds, so after every change you can confirm that nothing broke. Python includes the unittest framework in the standard library, and the popular third-party pytest makes tests even shorter. This lesson shows how to write tests, run them, read a failure and choose good test cases.

In this lesson you will learn

  • Writing a test case class with unittest.TestCase
  • Assertions: assertEqual, assertRaises, assertAlmostEqual
  • Preparing fresh objects with setUp
  • Running tests from the command line and reading failures
  • The same tests in pytest

Writing Tests With unittest

import unittest

def grade(marks: int) -> str:
    if not 0 <= marks <= 100:
        raise ValueError("marks must be 0-100")
    if marks >= 80:
        return "A+"
    if marks >= 60:
        return "A"
    return "F"

class TestGrade(unittest.TestCase):
    def test_top_grade(self):
        self.assertEqual(grade(95), "A+")

    def test_boundaries(self):
        self.assertEqual(grade(80), "A+")
        self.assertEqual(grade(79), "A")
        self.assertEqual(grade(60), "A")

    def test_fail(self):
        self.assertEqual(grade(10), "F")

    def test_invalid(self):
        with self.assertRaises(ValueError):
            grade(101)

if __name__ == "__main__":
    # Run the tests and print one line per test
    suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestGrade)
    tests = list(suite)                  # remember the tests before running
    result = unittest.TestResult()
    suite.run(result)
    failed = {t.id(): err for t, err in result.failures + result.errors}
    for test in tests:
        status = "FAIL" if test.id() in failed else "ok"
        print(f"{test.id().split('.')[-1]:24} {status}")
    for tid, err in failed.items():
        print(tid.split('.')[-1], "->", err.strip().splitlines()[-1])
    print(f"Ran {result.testsRun} tests, {len(failed)} failed")

Output

test_boundaries          ok
test_fail                ok
test_invalid             ok
test_top_grade           ok
Ran 4 tests, 0 failed
  • Tests live in a class that inherits from unittest.TestCase. Every method whose name starts with test is one test.
  • assertEqual(actual, expected) fails the test if the two values differ.
  • test_boundaries checks the edges where the grade changes (80, 79, 60). Bugs such as writing > instead of >= hide exactly at these boundaries.
  • with self.assertRaises(ValueError): passes only if the code inside raises that exception, so error handling is tested too.
  • The block at the bottom runs the tests and prints one line per test for this page. In your own projects, run the test file from the terminal instead, as shown below.

setUp, Floats and a Failing Test

import unittest

class Cart:
    def __init__(self):
        self.items = {}

    def add(self, name, price, qty=1):
        if price < 0:
            raise ValueError("negative price")
        self.items[name] = self.items.get(name, 0) + price * qty

    def total(self):
        return round(sum(self.items.values()), 2)

class TestCart(unittest.TestCase):
    def setUp(self):                 # runs before every test
        self.cart = Cart()

    def test_empty(self):
        self.assertEqual(self.cart.total(), 0)

    def test_add_twice(self):
        self.cart.add("pen", 20, 2)
        self.cart.add("pen", 20)
        self.assertEqual(self.cart.total(), 60)

    def test_float_total(self):
        self.cart.add("tea", 0.1)
        self.cart.add("milk", 0.2)
        self.assertAlmostEqual(self.cart.total(), 0.3)

    def test_wrong_on_purpose(self):
        self.cart.add("bag", 950)
        self.assertEqual(self.cart.total(), 900)   # this test fails

if __name__ == "__main__":
    # Run the tests and print one line per test
    suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestCart)
    tests = list(suite)                  # remember the tests before running
    result = unittest.TestResult()
    suite.run(result)
    failed = {t.id(): err for t, err in result.failures + result.errors}
    for test in tests:
        status = "FAIL" if test.id() in failed else "ok"
        print(f"{test.id().split('.')[-1]:24} {status}")
    for tid, err in failed.items():
        print(tid.split('.')[-1], "->", err.strip().splitlines()[-1])
    print(f"Ran {result.testsRun} tests, {len(failed)} failed")

Output

test_add_twice           ok
test_empty               ok
test_float_total         ok
test_wrong_on_purpose    FAIL
test_wrong_on_purpose -> AssertionError: 950 != 900
Ran 4 tests, 1 failed
  • setUp runs before each test, giving every test a new empty cart, so tests cannot affect one another. tearDown is its counterpart for cleanup.
  • Floating-point results such as 0.1 + 0.2 are not exact, so assertAlmostEqual compares them to 7 decimal places.
  • test_wrong_on_purpose expects the wrong total. The failure message, 950 != 900, shows the actual value first and the expected one second, which tells you exactly what went wrong.

Running Tests

python -m unittest test_cart.py        # one file
python -m unittest discover            # every test_*.py in the folder
python -m unittest -v test_cart.py     # verbose: one line per test

The same Cart tests in pytest are plain functions with plain assert statements:

import pytest

def test_add_twice():
    cart = Cart()
    cart.add("pen", 20, 2)
    cart.add("pen", 20)
    assert cart.total() == 60

def test_negative_price():
    with pytest.raises(ValueError):
        Cart().add("pen", -5)

Install pytest in a virtual environment with python -m pip install pytest and run pytest; it also runs existing unittest classes.

AssertionChecks
assertEqual(a, b)a == b
assertTrue(x) / assertFalse(x)Truth value
assertIn(item, container)Membership
assertIsNone(x)x is None
assertAlmostEqual(a, b)Floats are close
assertRaises(Error)The code raises Error

Common Mistakes

  1. Test method names not starting with test, so they are silently skipped.
  2. Tests that depend on each other or on run order; give each test its own data with setUp.
  3. Only testing the “happy path”; include boundaries, empty input and invalid input.
  4. Comparing floats with assertEqual.

Practice Exercises

Exercise 1. Write a test for a function is_even(n) that checks 4, 7 and 0.

Show answer
class TestEven(unittest.TestCase):
    def test_values(self):
        self.assertTrue(is_even(4))
        self.assertFalse(is_even(7))
        self.assertTrue(is_even(0))

Exercise 2. Add a test that adding an item with a negative price to Cart raises ValueError.

Show answer
    def test_negative_price(self):
        with self.assertRaises(ValueError):
            self.cart.add("pen", -5)

Frequently Asked Questions

Should I use unittest or pytest?

unittest needs no installation and is fine for learning and small projects. pytest is the most common choice in professional Python work because tests are shorter and its failure reports are more detailed.

What is test-driven development?

TDD means writing a failing test first, then the simplest code that makes it pass, then tidying the code while keeping the tests green. It keeps every feature covered by tests from the start.

Summary

  • Unit tests check small pieces of code automatically and quickly.
  • In unittest, subclass TestCase and name methods test_....
  • Use the right assertion, and setUp for fresh test data.
  • Run tests with python -m unittest or pytest after every change.

Next: Python match-case Statement.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *