๐ก๏ธ Why test?
A test is code that checks your other code. Instead of running your program and eyeballing the output, you write tests that automatically prove it works โ and keep proving it as you make changes.
Tests are a safety net. When you add a feature and a test suddenly fails, you've caught a bug before your users do.
โ
The assert statement
The simplest test tool: assert checks that something is true. If it isn't, your program stops and tells you.
def add(a, b):
return a + b
assert add(2, 3) == 5 # passes silently
assert add(0, 0) == 0 # passes
print("All tests passed!")
๐ก Read it as a promise
assert add(2, 3) == 5 means "I promise add(2, 3) equals 5." If the promise breaks, Python raises an error.
๐ด๐ข Test-Driven Development (TDD)
TDD flips the usual order: you write the test first , watch it fail, then write just enough code to pass.
Step Color What you do
1. Red ๐ด Write a failing test for a feature you want.
2. Green ๐ข Write the simplest code to make it pass.
3. Refactor ๐ต Clean up the code โ tests keep you safe.
๐งช Test the edges
Good tests check normal cases AND tricky edge cases : empty lists, zero, negatives, and the very first/last item.
def biggest(nums):
return max(nums)
assert biggest([3, 7, 2]) == 7 # normal
assert biggest([5]) == 5 # edge: one item
assert biggest([-1, -9]) == -1 # edge: negatives
๐ You finished the track!
Clean Code โ readable names and small functions.
OOP โ classes, objects, inheritance.
SOLID โ five principles for flexible design.
Patterns โ factory, strategy, observer.
Modules โ separation of concerns.
Testing & TDD โ prove it works, automatically.
๐ You now design software like a professional engineer. Incredible work!
๐ฎ Final Boss Challenges!
Write code that passes the tests. ๐
โ
Task 1: Make the Tests Pass
Medium
Write a double function so all three asserts pass. If they do, you'll see All tests passed!.
โถ Run
โ Check
โบ Reset
๐ก Solution
def double(n):
return n * 2
assert double(2) == 4
assert double(0) == 0
assert double(-3) == -6
print("All tests passed!")
๐ด๐ข
Task 2: TDD a is_even Function
Medium
The tests are already written (Red). Now write is_even to make them pass (Green). Use the modulo % operator.
โถ Run
โ Check
โบ Reset
๐ก Solution
def is_even(n):
return n % 2 == 0
๐งช
Task 3: Handle the Edge Cases
Boss
Write safe_average that returns the average of a list โ but returns 0 for an empty list (the tricky edge case!). Make all asserts pass.
โถ Run
โ Check
โบ Reset
๐ก Solution
def safe_average(nums):
if len(nums) == 0:
return 0
return sum(nums) / len(nums)