Lesson 48/48 ยท ๐Ÿš€ Leveling Up
๐Ÿš€ Leveling UpLesson 48/48
Phase 9 ยท Leveling Up20 min

Testing with assert

Write tests that catch bugs before your users do

Testing is writing code that checks your code. It sounds circular but it's the single most effective way to prevent bugs in production.
The assert statementpython
# assert checks that something is True. If not: AssertionError
def add(a, b):
    return a + b

# Tests
assert add(2, 3) == 5, "2 + 3 should equal 5"
assert add(0, 0) == 0, "0 + 0 should equal 0"
assert add(-1, 1) == 0, "-1 + 1 should equal 0"
print("All tests passed!")   # This only prints if all asserts succeed
Test-driven thinking: write the test FIRST
Before writing a function, write what you expect it to do. This forces you to understand the problem.
Test-driven development in actionpython
# Step 1: Write the test first
def test_is_palindrome():
    assert is_palindrome("racecar") == True
    assert is_palindrome("hello") == False
    assert is_palindrome("") == True   # edge case: empty string
    assert is_palindrome("a") == True  # edge case: single char
    print("is_palindrome: all tests passed!")

# Step 2: Write the function to make tests pass
def is_palindrome(s):
    return s == s[::-1]

# Step 3: Run tests
test_is_palindrome()
The pattern for each test:1. Call the function with a specific input2. Assert the output equals what you expect3. Include edge cases (empty, single, negative, maximum)
๐ŸŒIn the Real World...

Every production Python codebase uses pytest, a professional testing framework. But pytest tests are just functions with asserts. Once you understand assert-based tests, pytest is just a better runner.

๐ŸŽฏ

Phase Complete!

Leveling Up

You've reached the end of Python Foundations! What's the most important thing you've learned? What will you build first with your new Python skills?

0/500

Practice Exercises

0/2 solved
Exercise 1 of 2easy
โฑ 00:00

Test a Max Function

Write a function find_max(lst) that returns the largest number.Then write 3 assert tests for it.
Expected output: All tests passed!
solution.py
1 / 2
Exercise 2 of 2easyTrace
โฑ 00:00

Fix the Failing Test

The function below has a bug. The test reveals it. Fix the function so all tests pass.
Expected output: All tests passed!
solution.py
2 / 2
Solve all 2 exercises to unlock completion