Writing
Unit Tests in Python
Learn to verify your code works correctly using assert statements to build reliable, bug-free programs.
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?
The Testing Lifecycle
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.
Anatomy of an Assert Test
assert vs print
| assert | ||
|---|---|---|
| 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
assert function(inputs) == expectedExample 1: Testing add()
Example 2: Testing is_even()
Example 3: Testing max_of_three()
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.
"" 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.
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.
Common Mistakes
assert x == 5 is correct.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
Consider this code:
def double(n):
return n * 2
assert double(4) = 8
What is wrong with the test above?
assert double(4) == 8.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
Consider this code:
def greet(name):
return "Hello, " + name + "!"
assert greet("Alice") == "Hello, Alice!"
assert greet("") == "Hello, !"
assert greet("Bob") == "Hello, Bob!"
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?