Designing
Edge Case Tests
Learn to write tests that probe the boundaries and limits of your Python code: where bugs hide and programs break.
What Are Edge Cases?
An edge case is an input or scenario that sits at the extreme boundary of what a function is expected to handle. These are the values most likely to expose hidden bugs: empty collections, zero, negative numbers, maximum values, and unusual data types.
Understanding Boundary Conditions
A boundary condition is the exact point where behavior changes. For a function that accepts values in a range \([a, b]\), the boundaries are the values at, just inside, and just outside \(a\) and \(b\).
Why Edge Cases Matter
The Edge Case Taxonomy
The Boundary Value Rule
For any input with a valid range, always test these five values:
Edge Cases vs. Corner Cases
| Edge Case | Corner Case | |
|---|---|---|
| Definition | One parameter at its boundary | Multiple parameters at boundaries simultaneously |
| Example | Empty list input | Empty list + zero divisor |
| Frequency | Common, easier to identify | Rare, harder to anticipate |
| Risk Level | High: causes most bugs | Very high: causes catastrophic failures |
| Analogy | Edge of a square | Corner where two edges meet |
How to Design Edge Case Tests
Example 1: Testing find_max
Edge Case Tests for find_max
Example 2: Testing is_palindrome
Complete Tests for is_palindrome
Example 3: Testing safe_divide
Common Mistakes
Edge Case Checklist
| Input Type | Edge Cases to Test | Example |
|---|---|---|
| List / Array | Empty, single element, all same, very large | [], [1], [5,5,5] |
| String | Empty, single char, spaces only, special chars | "", "a", " " |
| Integer | Zero, negative, very large, min/max | 0, -1, \(2^{31}-1\) |
| Float | Zero, negative, infinity, NaN, tiny | 0.0, -0.0, float('inf') |
| Boolean | Both True and False, truthy/falsy equivalents | True, False, 0, "" |
| Dictionary | Empty, missing keys, None values | {}, {"k": None} |
Question 1 of 5
Which of the following is the best edge case test for a function get_first(lst) that returns the first element of a list?
Question 2 of 5
A function clamp(x, low, high) should return x if \(low \leq x \leq high\), otherwise return the nearest bound. Which test set best covers boundary conditions?
Question 3 of 5
What is the difference between an edge case and a corner case?
Question 4 of 5
Consider this function:
def average(numbers):
return sum(numbers) / len(numbers)
A student writes these tests:
assert average([1, 2, 3]) == 2.0
assert average([10, 20]) == 15.0
assert average([5]) == 5.0
Which critical edge case is missing from these tests?
Question 5 of 5
You are testing a function binary_search(arr, target) that returns the index of target in a sorted list, or \(-1\) if not found. Which test case catches a common off-by-one error?