Writing Your First Unit Test
You'll learn: How to write a concrete unit test for a pure function using a modern testing framework.
The Core Idea
A unit test is executable code that verifies a small piece of your program (usually one function) behaves correctly. Since you've already learned about pure functions—functions with no side effects that always return the same output for the same input—they're perfect candidates for your first tests.
A typical unit test follows this structure (which you learned in "Anatomy of a Unit Test"): Arrange (set up inputs), Act (call the function), Assert (check the result matches expectations).
A Concrete Example
Let's test a pure function that adds two numbers:
# The function we want to test
def add(a, b):
return a + b
Here's your first unit test using a framework like pytest:
def test_add_positive_numbers():
# Arrange
x = 3
y = 5
# Act
result = add(x, y)
# Assert
assert result == 8
That's it! The test has a descriptive name, sets up inputs, calls add(), and checks the output is correct. If result isn't 8, the test fails and alerts you to a problem.
You might write additional tests for different scenarios:
def test_add_negative_numbers():
assert add(-2, -3) == -5
def test_add_zero():
assert add(5, 0) == 5
Each test validates one specific behavior using equivalence partitioning and boundary value analysis principles you've learned.
Key Takeaway: Your first unit test exercises a pure function by arranging inputs, calling the function, and asserting the output matches expected behavior—giving you automated confidence that your code works correctly.