5. Files, Errors & Testing

Testing Your Code (assert & pytest)

Learn how professional developers prove their code works: write quick automated checks with assert, build test files for pytest, and catch edge-case bugs early.

3 min readUpdated 2026-11-29
In This Lesson
  • Write fast automated checks using assert statements
  • Organize test_*.py files and test_* functions for pytest
  • Test normal cases, boundary values, and expected errors

Imagine you write a calculate_discount(price, percent) function. How do you know it actually works?

Most beginners run the program and type 100 and 10 by hand. Later, they tweak one line—and forget to re-test 0%, 100%, or negative numbers, accidentally shipping a bug!

Instead of testing manually every time, programmers write automated unit tests that verify your code in 0.1 seconds!

Your First Automated Test (assert)

Read assert condition as: "I insist this MUST be True—if it isn't, crash immediately and tell me!"

python
def square(n):
    return n * n

assert square(3) == 9
assert square(-4) == 16
assert square(0) == 0
print("All checks passed!")

Notice if square(n) accidentally had a typo like return n + n, running those lines immediately stops at assert square(3) == 9 with AssertionError—catching the bug on the spot!

Testing Edge Cases (Think Like a Skeptic)

Good tests check 3 kinds of inputs:

  1. Normal inputs (e.g., $100 with 10% discount → $90)
  2. Boundary / Edge inputs ($0, 0%, 100%)
  3. Invalid inputs (like negative price raising ValueError!)

Using pytest in Real Projects

On your computer, pytest is Python's most popular testing tool (installed inside .venv with pip install pytest).

Create two files side by side:

1. calculator.py

python
def apply_discount(price, percent):
    if price < 0 or not (0 <= percent <= 100):
        raise ValueError("Invalid price or discount percentage")
    return round(price * (1 - percent / 100), 2)

2. test_calculator.py (start the filename and test functions with test_!)

python
import pytest
from calculator import apply_discount

def test_normal_discounts():
    assert apply_discount(100, 10) == 90.0
    assert apply_discount(50, 50) == 25.0

def test_edge_cases():
    assert apply_discount(100, 0) == 100.0
    assert apply_discount(100, 100) == 0.0

def test_invalid_inputs():
    with pytest.raises(ValueError):
        apply_discount(-10, 10)

Run pytest in your terminal:

bash
pytest

pytest automatically finds every test_*.py file, runs every test_* function, and shows crisp green passes or exact failure diffs!

Testing Multiple Inputs Cleanly with @pytest.mark.parametrize

Instead of copy-pasting 5 nearly identical test functions, pass a table of (input, expected) pairs into one clean parameterized test:

python
import pytest
from calculator import apply_discount

@pytest.mark.parametrize("price, percent, expected", [
    (100, 10, 90.0),
    (50, 50, 25.0),
    (80, 0, 80.0),
])
def test_discounts(price, percent, expected):
    assert apply_discount(price, percent) == expected
Keep Tests Independent

Each test_* function should build its own fresh inputs and never depend on the execution order of other tests—so you can run a single failing test in isolation with pytest -k test_edge_cases.

Spot & Fix a Bug Using assert

The function is_adult(age) below has a subtle off-by-one bug! Click Run Code to watch the assert catch it, then fix line 2 so all tests pass:

Python 3Try It Live: Catch a Bug with Unit Tests
Output

Click “Run Code” to execute this snippet right in your browser.

Quick Checkpoints

Check Your Understanding

What happens when an assert statement evaluates to False?

Check Your Understanding

By convention, how should you name test files and test functions so pytest discovers them automatically?