Python Testing with unittest
What you will learn
- Why automated tests are worth writing
- Writing a
TestCasewith assert methods - Running tests and reading the results
- Testing exceptions, using
setUp,subTest, skipping - Replacing parts of a program with
unittest.mock
1. Why test automatically?
You can check code by running it and looking at the output. That works once. An automated test is a small program that runs your code with chosen inputs and checks the results by itself. Then, every time you change something, you re-run the tests in seconds and know whether anything broke.
Benefits:
- Confidence to change code ("refactoring") without fear.
- Bugs are found early, close to the change that caused them.
- Tests act as examples of how the code should behave.
- A bug you fixed gets a test, so it cannot silently return (lesson 18.1).
The standard library includes unittest; lesson 18.3 covers pytest, which many people prefer. The ideas are the same.
2. The code to test
Here is a module shop.py:
def add(a, b):
return a + b
def divide(a, b):
if b == 0:
raise ValueError("cannot divide by zero")
return a / b
def is_palindrome(text):
cleaned = [c.lower() for c in text if c.isalnum()]
return cleaned == cleaned[::-1]
class Cart:
def __init__(self):
self.items = {}
self.prices = {}
def add(self, name, price, qty=1):
if qty < 1:
raise ValueError("qty must be at least 1")
self.items[name] = self.items.get(name, 0) + qty
self.prices[name] = price
def total(self):
return round(sum(self.prices[n] * q for n, q in self.items.items()), 2)
(prices is created in __init__ here; the version used to check this lesson built it on first use, which behaves the same for the tests below.)
3. A first test file
By convention tests live in files named test_*.py. A test is a method whose name starts with test, inside a class that inherits from unittest.TestCase:
import unittest
from shop import add, divide
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
def test_add_negative(self):
self.assertEqual(add(-1, 1), 0)
def test_divide(self):
self.assertAlmostEqual(divide(1, 3), 0.3333, places=4)
def test_divide_by_zero(self):
with self.assertRaises(ValueError) as cm:
divide(1, 0)
self.assertIn("zero", str(cm.exception))
if __name__ == "__main__":
unittest.main()
Each test calls the code and uses an assert method to say what must be true. If an assertion fails, that test fails and the others still run.
Assert methods
| Method | Passes when |
|---|---|
assertEqual(a, b) |
a == b |
assertNotEqual(a, b) |
a != b |
assertTrue(x) / assertFalse(x) |
bool(x) is true / false |
assertIs(a, b) / assertIsNone(x) |
identity, or x is None |
assertIn(a, b) |
a in b |
assertAlmostEqual(a, b, places=7) |
numbers equal to some decimal places (floats, lesson 3.4) |
assertGreater(a, b), assertLess(a, b) |
comparisons |
assertIsInstance(x, T) |
isinstance(x, T) |
assertRaises(Error) |
the block raises Error (used with with) |
assertCountEqual(a, b) |
same items, any order |
Prefer the specific method (assertEqual, assertIn) to a bare assertTrue(a == b): on failure it prints both values.
Quick check: why `assertAlmostEqual(divide(1, 3), 0.3333, places=4)` and not `assertEqual`?
1 / 3 is 0.3333333333333333, which is not exactly 0.3333; floats should be compared to a number of decimal places.
4. Running tests
From the project folder:
python -m unittest
(unittest discovers every test*.py file.) You can also run the file directly (python test_shop.py, thanks to unittest.main()), a single test (python -m unittest test_shop.TestMath.test_add), or add -v for a list of tests. The full test file of this lesson (shown in the worked example) printed:
..s.........
----------------------------------------------------------------------
Ran 12 tests in 0.001s
OK (skipped=1)
Each dot is a passing test, s a skipped one. With -v, every test is listed:
test_add_more (test_shop.TestCart.test_add_more) ... ok
test_bad_qty (test_shop.TestCart.test_bad_qty) ... ok
test_future (test_shop.TestCart.test_future) ... skipped 'not ready'
...
Tests run in alphabetical order, and must not depend on each other.
5. Reading a failure
A failing test says what was expected and what happened. Here are three broken tests:
class T(unittest.TestCase):
def test_wrong(self):
self.assertEqual(add(2, 2), 5)
def test_list(self):
self.assertEqual([1, 2, 3], [1, 2, 4])
def test_error(self):
add("a", 1)
def test_ok(self):
self.assertEqual(add(1, 1), 2)
Result (file paths shortened, and the traceback's marker lines trimmed):
EF.F
======================================================================
ERROR: test_error (test_fail.T.test_error)
...
TypeError: can only concatenate str (not "int") to str
======================================================================
FAIL: test_list (test_fail.T.test_list)
...
AssertionError: Lists differ: [1, 2, 3] != [1, 2, 4]
First differing element 2:
3
4
...
======================================================================
FAIL: test_wrong (test_fail.T.test_wrong)
...
AssertionError: 4 != 5
----------------------------------------------------------------------
Ran 4 tests in 0.002s
FAILED (failures=2, errors=1)
F(failure): an assertion was false: the code ran, but gave a wrong answer.E(error): the code raised an unexpected exception: something is broken (or the test is wrong).- The summary line counts failures and errors; the exit code of the command is non-zero, which is how automated systems notice.
assertEqualon lists shows the first difference.
6. Organising tests
setUp and tearDown
Tests need a fresh starting state. setUp runs before each test, and tearDown after each (for cleanup such as removing files):
class TestCart(unittest.TestCase):
def setUp(self):
self.cart = Cart()
self.cart.add("pen", 1.5, 2)
def test_total(self):
self.assertEqual(self.cart.total(), 3.0)
def test_add_more(self):
self.cart.add("book", 10)
self.assertEqual(self.cart.total(), 13.0)
def test_bad_qty(self):
with self.assertRaises(ValueError):
self.cart.add("x", 1, 0)
Because setUp builds a new Cart for every test, test_add_more does not disturb test_total. (setUpClass / tearDownClass run once per class, for expensive setup.)
subTest
To test one thing with many inputs, loop with subTest; a failure reports which input failed without stopping the others:
def test_many(self):
for text, expected in [("racecar", True), ("ab", False), ("Aa", True)]:
with self.subTest(text=text):
self.assertEqual(is_palindrome(text), expected)
Skipping
@unittest.skip("reason") skips a test; @unittest.skipIf(condition, "reason") skips conditionally; @unittest.expectedFailure marks a known bug.
7. Replacing parts with mock
Tests should be fast and repeatable, so they should not call real websites, send emails, use the clock or random numbers. unittest.mock provides stand-ins ("mocks") that you control, and that record how they were used:
from unittest import mock
def greet(get_name):
return f"Hello, {get_name()}!"
def fetch_price(client, item):
data = client.get(item)
return data["price"] * 2
class TestMock(unittest.TestCase):
def test_fake_function(self):
fake = mock.Mock(return_value="Rina")
self.assertEqual(greet(fake), "Hello, Rina!")
fake.assert_called_once_with()
def test_fake_client(self):
client = mock.Mock()
client.get.return_value = {"price": 5}
self.assertEqual(fetch_price(client, "pen"), 10)
client.get.assert_called_once_with("pen")
def test_patch(self):
with mock.patch("random.randint", return_value=4) as m:
import random
self.assertEqual(random.randint(1, 6), 4)
m.assert_called_with(1, 6)
All three passed. Mock(return_value=...) is a callable that returns a fixed value; client.get.return_value sets what a method returns; assert_called_once_with checks how it was called; mock.patch("module.name") temporarily replaces a real thing and restores it when the with block ends. This is why passing a dependency in as an argument makes code easy to test (lesson 13.9).
8. What to test
| Aim | Example |
|---|---|
| the normal case | add(2, 3) == 5 |
| edge cases | empty list, one item, zero, negative numbers, very large values |
| errors | the right exception for bad input |
| bugs you fixed | the failing input from the bug report |
| one behaviour per test | a clear name: test_divide_by_zero |
Keep tests small, independent, fast, and readable: a test name should say what is expected. Test the behaviour (results) rather than the inner details, so that the code can be improved without rewriting tests. Run the tests often, before every commit; when a test fails, fix the code or (if the requirement changed) the test, never just delete it.
Worked example: the complete test file
The tests for shop.py in one file, test_shop.py:
import unittest
from shop import add, divide, is_palindrome, Cart
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
def test_add_negative(self):
self.assertEqual(add(-1, 1), 0)
def test_divide(self):
self.assertAlmostEqual(divide(1, 3), 0.3333, places=4)
def test_divide_by_zero(self):
with self.assertRaises(ValueError) as cm:
divide(1, 0)
self.assertIn("zero", str(cm.exception))
class TestPalindrome(unittest.TestCase):
def test_true(self):
self.assertTrue(is_palindrome("A man, a plan, a canal: Panama"))
def test_false(self):
self.assertFalse(is_palindrome("hello"))
def test_empty(self):
self.assertTrue(is_palindrome(""))
def test_many(self):
for text, expected in [("racecar", True), ("ab", False), ("Aa", True)]:
with self.subTest(text=text):
self.assertEqual(is_palindrome(text), expected)
class TestCart(unittest.TestCase):
def setUp(self):
self.cart = Cart()
self.cart.add("pen", 1.5, 2)
def test_total(self):
self.assertEqual(self.cart.total(), 3.0)
def test_add_more(self):
self.cart.add("book", 10)
self.assertEqual(self.cart.total(), 13.0)
def test_bad_qty(self):
with self.assertRaises(ValueError):
self.cart.add("x", 1, 0)
@unittest.skip("not ready")
def test_future(self):
self.fail()
if __name__ == "__main__":
unittest.main()
Running python -m unittest in that folder:
..s.........
----------------------------------------------------------------------
Ran 12 tests in 0.001s
OK (skipped=1)
| Test | Idea |
|---|---|
test_add_negative, test_empty |
edge cases beyond the obvious |
test_divide_by_zero |
the error case, including its message |
test_many with subTest |
one test, several inputs |
setUp |
every cart test starts with the same cart |
test_future |
skipped, so it is visible but does not fail |
The shop data is made up. Next, try breaking is_palindrome on purpose and see which tests fail; this shows how a test suite catches mistakes.
Common mistakes
- Tests that depend on each other or on the order they run in.
- Tests that use real files, networks or the clock without control.
- Comparing floats with
assertEqual. - A test with no assertion (it can only fail with an error).
- Testing too much in one test, so a failure is unclear.
- Test names that do not start with
test(they are silently not run). - Never running the tests, or deleting a failing test to get a green result.
- Writing tests that copy the code's logic instead of stating expected results.
Key takeaways
- Automated tests check your code in seconds and protect against breakage.
- With
unittest, write aTestCaseclass withtest_*methods andself.assert...calls; run withpython -m unittest. Fmeans a wrong result,Ean unexpected exception; read the message for the expected and actual values.- Use
setUpfor fresh state,assertRaisesfor errors,subTestfor many inputs. unittest.mockreplaces slow or unpredictable parts so tests stay fast and repeatable.- Test normal cases, edge cases, errors and every bug you fix.
Practice
1. What must a test method's name start with?
Show answer
test (for example test_add). Otherwise unittest does not run it.
2. How do you check that int("x") raises ValueError?
Show answer
with self.assertRaises(ValueError):
int("x")
3. What is the difference between F and E in the output?
Show answer
F: an assertion failed (wrong result). E: the code raised an unexpected exception.
4. Why does setUp create a new object for every test?
Show answer
So tests are independent: one test's changes cannot affect another.
5. How would you test code that uses random.randint so the result is predictable?
Show answer
Use mock.patch("random.randint", return_value=4) inside the test, so the call always returns 4.
6. Name three kinds of cases worth testing for a function that averages a list.
Show answer
A normal list, a single-item list, an empty list (expecting an error), negative numbers, and non-numeric input.