01 / 20

Writing
Unit Tests in Python

Learn to verify your code works correctly using assert statements to build reliable, bug-free programs.

Python

What Is a Unit Test?

A unit test is a small piece of code that checks whether a single "unit" of your program (usually one function) produces the expected output for a given input. Think of it as an automated spell-checker, but for logic instead of grammar.

Why Write Tests?

✓ Catch Bugs Early
Tests find mistakes the moment you make them, not after you ship your code.
✓ Confidence to Change
When you edit code, tests confirm you did not accidentally break something else.
✓ Document Behavior
Tests serve as living documentation: they show exactly what inputs and outputs your function supports.

The Testing Lifecycle

Write Function Write Test Run Test Pass or Fix fix & re-run

The assert Statement

Python's built-in assert keyword is the simplest way to write a test. It checks whether a condition is True. If it is, nothing happens. If it is False, Python raises an AssertionError.

# Syntax assert condition, "optional error message" # Example assert 2 + 2 == 4 # passes silently assert 2 + 2 == 5, "Math is broken" # AssertionError!

Anatomy of an Assert Test

assert add ( 3 , 5 ) == 8 keyword actual result (call your function) equals expected result (what you know is correct)

assert vs print

assert print
Checks automatically ✓ Yes ✕ No
Stops on failure ✓ Yes ✕ No
You must read output ✕ Not needed ✓ Every time
Scales to 100+ tests ✓ Easily ✕ Painful
Suitable for grading ✓ Yes ✕ No

How to Write a Unit Test

1
Identify the function you want to test and understand what it should return.
2
Choose test inputs: pick a simple case where you already know the correct answer.
3
Write the assert: assert function(inputs) == expected
4
Add edge cases: test with zero, negative numbers, empty strings, or boundary values.
5
Run and verify: execute the file. Silence means all tests passed.

Example 1: Testing add()

def add(a, b): return a + b # Tests assert add(2, 3) == 5 assert add(0, 0) == 0 assert add(-1, 1) == 0 assert add(-5, -3) == -8 print("All tests passed!")

Example 2: Testing is_even()

def is_even(n): return n % 2 == 0 # Tests assert is_even(4) == True assert is_even(7) == False assert is_even(0) == True assert is_even(-2) == True print("All tests passed!")

Example 3: Testing max_of_three()

def max_of_three(a, b, c): if a >= b and a >= c: return a elif b >= c: return b return c # Tests assert max_of_three(1, 2, 3) == 3 assert max_of_three(9, 5, 1) == 9 assert max_of_three(4, 4, 4) == 4 # all equal assert max_of_three(-1, -5, -2) == -1

Testing Edge Cases

Edge cases are unusual or extreme inputs that often reveal hidden bugs. Always include tests for these alongside your "normal" test cases.

Zero
Does your function handle 0 correctly? Many formulas break at zero.
Negatives
A function expecting positive numbers may crash or return wrong results with negatives.
Empty Input
Empty strings "" or empty lists [] are common sources of errors.

Adding Error Messages

You can add an optional message after the condition. If the assert fails, Python includes this message in the error, making it easy to identify which test broke.

def square(n): return n * n assert square(3) == 9, "square(3) should be 9" assert square(0) == 0, "square(0) should be 0" assert square(-4) == 16, "square(-4) should be 16"

Organizing Tests in Functions

As your project grows, group related asserts inside test functions. Name them with a test_ prefix so they are easy to find and run.

def add(a, b): return a + b def test_add_positive(): assert add(2, 3) == 5 assert add(10, 20) == 30 def test_add_edge_cases(): assert add(0, 0) == 0 assert add(-1, 1) == 0 # Run all tests test_add_positive() test_add_edge_cases() print("All tests passed!")

Common Mistakes

✕ Using = Instead of ==
A single = is assignment, not comparison. assert x == 5 is correct.
✕ Testing Only Happy Path
Only testing normal inputs misses bugs. Always include edge cases: zero, negatives, empty values.
✕ Forgetting to Call the Function
Writing assert add == 5 tests the function object, not its return value. Use add(2, 3).

Summary Cheat Sheet

Concept Syntax / Example Purpose
Basic assert assert f(x) == y Check one result
With message assert f(x) == y, "msg" Identify failures
Test function def test_foo(): ... Organize tests
Edge case assert f(0) == ... Catch hidden bugs
Run tests test_foo(); print("OK") Verify all pass

Question 1 of 5

What happens when an assert statement's condition evaluates to False?

Question 2 of 5

What is wrong with the test above?

Question 3 of 5

Which of the following is the best set of test cases for a function absolute_value(n) that returns the absolute value of a number?

Question 4 of 5

When you run the code above, what happens?

Question 5 of 5

Why is it better to use assert statements for testing instead of print statements?