Unit Testing - Testing Individual Components
flowchart TD A["end-to-end -- a few"] --> B["slow, brittle, but proves the whole thing works"] C["integration -- some"] --> D["real boundaries: database, HTTP, files"] E["unit -- many"] --> F["milliseconds, no I/O, a failure names the function"] G["inverted: mostly end-to-end"] --> H["slow suite, vague failures, people stop running it"]
What is a “unit”?
Section titled “What is a “unit”?”A unit is the smallest testable piece of your code.
Usually:
- a function
- a method
- a small class
What unit tests should be
Section titled “What unit tests should be”- fast (no DB, no network)
- deterministic (same input → same output)
- focused (one behavior per test)
What unit tests should avoid
Section titled “What unit tests should avoid”- real HTTP calls
- real databases
- time-dependent behavior (unless controlled)
Example unit logic
Section titled “Example unit logic”def apply_discount(price: float, percent: float) -> float:
if percent < 0 or percent > 100:
raise ValueError("percent must be between 0 and 100")
return round(price * (1 - percent / 100), 2)A unit test for this function is small and has no dependencies.
Key takeaway
Section titled “Key takeaway”Unit tests are your fastest safety net for refactoring.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Write a unittest TestCase
Section titled “Exercise 1 – Write a unittest TestCase”Exercise 2 – assertRaises
Section titled “Exercise 2 – assertRaises”Exercise 3 – setUp and tearDown
Section titled “Exercise 3 – setUp and tearDown”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading