Writing Your First Characterization Test
You'll learn: How to write a test that documents exactly what legacy code does right now, bugs and all.
The Core Idea
A characterization test is like taking a photograph of your code's current behavior. You're not testing what the code should do—you're testing what it actually does. Even if that behavior includes bugs or quirks, you capture it faithfully. This creates a safety net: any changes you make later will break this test if they alter behavior, alerting you to unintended side effects.
The Process
Step 1: Choose a small piece of code to characterize. Pick a function or method you need to understand or modify.
Step 2: Call it with some inputs and observe the output. Run the code and see what happens. Don't assume—actually execute it.
Step 3: Write a test asserting that exact behavior. Whatever you observed becomes your assertion, even if it seems wrong:
def test_calculate_discount():
# This function currently returns 0 for negative prices
# That's probably a bug, but we're documenting current behavior
result = calculate_discount(price=-10, discount=0.2)
assert result == 0 # Current behavior, not ideal behavior
Step 4: Run your test to confirm it passes. If it fails, you misunderstood the current behavior. Adjust until it passes.
Step 5: Repeat with different inputs. Cover various scenarios to build confidence you understand the behavior.
Think of it like creating a burglar alarm for your code: you're not fixing the house yet, just making sure you'll know if something changes.
Key Takeaway: Characterization tests document reality, not ideals—they freeze current behavior so you can refactor safely, even when that behavior includes bugs you plan to fix later.