Unit 8 • Lesson 6

Writing and Running Tests

Overview

Testing ensures that your code works correctly before it's deployed. You'll learn to write simple test functions, use assertions, and understand how automated testing prevents future bugs, establishing a foundation for reliable software development.

Beginner 20–25 min

What You Will Learn in This Lesson

By the end of this lesson, you will know:

  • What testing is: Verifying code works correctly.
  • Writing test functions: Creating functions that test your code.
  • Using assertions: Checking that results match expectations.
  • Running tests: Executing tests and interpreting results.
  • Test organization: Structuring tests effectively.

What Is Testing?

Testing is the process of verifying that your code works correctly. Instead of manually checking your program every time you change it, you write automated tests that do the checking for you.

Why Write Tests?

  • Catch bugs before users do
  • Verify code works after changes
  • Document how code should behave
  • Save time in the long run
  • Build confidence in your code
Example: Simple Test
# Function to test
def add_numbers(a, b):
    return a + b

# Test function
def test_add_numbers():
    assert add_numbers(2, 3) == 5
    assert add_numbers(0, 0) == 0
    assert add_numbers(-1, 1) == 0
    print("All tests passed!")

# Run the test
test_add_numbers()

Using Assertions

The assert statement checks if a condition is true. If it's false, Python raises an AssertionError.

Assert Statement
# Basic assertion
assert 2 + 2 == 4  # Passes silently

# Assertion with message
assert 2 + 2 == 5, "Math is broken!"  # Raises AssertionError

# In tests
def test_calculation():
    result = calculate(10, 5)
    assert result == 15, f"Expected 15, got {result}"

Assert Best Practices

Use descriptive messages in assertions. Instead of assert x == y, use assert x == y, f"Expected {y}, got {x}" to make failures easier to understand.

Writing Test Functions

Test functions follow a simple pattern:

1

Name Your Test

Start with test_ so it's clear it's a test

2

Call Your Function

Run the function with test inputs

3

Check the Result

Use assert to verify the output

Complete Test Example
def find_max(numbers):
    if not numbers:
        return None
    return max(numbers)

def test_find_max():
    # Test normal case
    assert find_max([1, 5, 3]) == 5
    
    # Test with negative numbers
    assert find_max([-1, -5, -3]) == -1
    
    # Test with single element
    assert find_max([42]) == 42
    
    # Test empty list
    assert find_max([]) == None
    
    print("All tests passed!")

test_find_max()

Summary

In this lesson, you learned:

  • Testing: Verifying code works correctly
  • Test functions: Functions that test your code
  • Assertions: Checking results match expectations
  • Running tests: Execute tests to verify code
  • Benefits: Catch bugs early, save time

Remember

Writing tests might seem like extra work, but it saves time in the long run. Tests catch bugs before they reach users and give you confidence when making changes!

End-of-Lesson Exercises

Think about these questions to reinforce what you've learned:

Exercise 1: Testing

What is testing and why is it important? How do assertions help with testing?

Exercise 2: Writing Tests

What are the steps to writing a test function? Give an example.