☼
⌃
☰

Testing

Table of Contents

Testing is the practice of verifying that code behaves as intended, both now and after future changes. It's the practical implementation of quality assurance referenced in the Software Development Life Cycle — this note covers how, not just where it fits in the process.

Related: Software Development Life Cycle Control Flow Side Effects Python

Test Levels

Level Scope Speed Example
Unit Single function/method, isolated Fast Does add(2, 3) return 5?
Integration Multiple components together Medium Does the API call the DB correctly?
End-to-end (E2E) Full system, user-facing flow Slow Can a user sign up and log in?

Unit tests should make up the bulk of a test suite (fast, cheap, pinpoint failures precisely). Integration and E2E tests catch what unit tests can't — component interaction and real-world flow — but cost more to write and run, so use them more sparingly.

pytest — Core Usage

pytest is the standard Python testing framework — less boilerplate than the built-in unittest module, plain assert statements instead of special assertion methods.

PYTHON
# test_calculator.py — pytest auto-discovers files/functions
# matching test_*.py / *_test.py and def test_*()

def add(a, b):
    return a + b

def test_add_positive():
    assert add(2, 3) == 5

def test_add_negative():
    assert add(-1, -1) == -2
SHELL
pytest                    # run all tests in the current directory
pytest test_calculator.py # run a specific file
pytest -k "positive"      # run tests matching a name pattern
pytest -v                 # verbose — show each test name and result
pytest -x                 # stop at first failure
pytest --lf               # rerun only tests that failed last time

Fixtures — Shared Setup

Fixtures provide reusable setup/teardown, injected into test functions as arguments.

PYTHON
import pytest

@pytest.fixture
def sample_data():
    return {"id": 1, "name": "test"}

def test_uses_fixture(sample_data):
    assert sample_data["name"] == "test"

# Fixture with teardown (code after yield runs after the test)
@pytest.fixture
def db_connection():
    conn = create_connection()
    yield conn
    conn.close()

Parametrize — Run One Test Against Many Inputs

PYTHON
import pytest

@pytest.mark.parametrize("a,b,expected", [
    (2, 3, 5),
    (-1, 1, 0),
    (0, 0, 0),
])
def test_add(a, b, expected):
    assert add(a, b) == expected

Mocking — Isolating Units from Dependencies

Replace a real dependency (API call, DB, filesystem) with a controlled stand-in so the unit test doesn't depend on external state.

PYTHON
from unittest.mock import Mock, patch

def test_with_mock():
    mock_api = Mock()
    mock_api.get_user.return_value = {"id": 1, "name": "test"}
    result = mock_api.get_user()
    assert result["name"] == "test"

# Patch a function at the point it's imported, not where it's defined
@patch("mymodule.requests.get")
def test_api_call(mock_get):
    mock_get.return_value.status_code = 200
    mock_get.return_value.json.return_value = {"status": "ok"}
    # code under test calls requests.get() here — receives the mock instead

Testing Exceptions

PYTHON
import pytest

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

def test_divide_by_zero_raises():
    with pytest.raises(ValueError, match="Cannot divide by zero"):
        divide(10, 0)

Test-Driven Development (TDD)

Write the test before the implementation. The cycle:

  1. Red — write a failing test for behaviour that doesn't exist yet
  2. Green — write the minimum code to make it pass
  3. Refactor — clean up the implementation while the test keeps passing as a safety net

The value isn't ceremony — it forces you to define expected behaviour precisely before writing code, and gives you a regression suite for free as a side effect of the process, rather than as a separate task done (or skipped) afterward.

Coverage

Coverage measures what percentage of your code executes during the test suite — not whether the code is correct, only whether it ran.

SHELL
pip install pytest-cov --break-system-packages
pytest --cov=mymodule --cov-report=term-missing

High coverage doesn't guarantee good tests — a test can execute a line without meaningfully asserting anything about its behaviour. Treat coverage as a tool for finding untested code, not as a quality target in itself.

Test Doubles — Terminology

Term Behaviour
Dummy Passed but never actually used
Stub Returns fixed/canned responses
Fake Working but simplified implementation (e.g. in-memory DB)
Mock Verifies it was called correctly (arguments, call count)
Spy Wraps a real object, records calls, still delegates through

In practice "mock" is used loosely to mean any of these — precise terminology matters more in discussion than in day-to-day code.

Tips

  • Name tests for the behaviour they verify, not the implementation detail — test_add_returns_sum_of_two_positive_numbers ages better than test_add_1
  • One logical assertion focus per test — multiple unrelated asserts in one test make failures ambiguous about what actually broke
  • Test edge cases explicitly: empty input, zero, negative numbers, None/null, maximum size — these are where real bugs live, not in the happy path
  • Prefer fixtures over repeated setup code at the top of every test function — reduces duplication and centralises the change point when setup logic needs to update
  • Fast unit test suites get run constantly; slow ones get skipped. Keep unit tests fast by mocking I/O (network, disk, DB) rather than hitting real services
  • A red test that stays red after your fix means the fix is wrong or the test was wrong — don't assume the test itself is broken and delete it without checking which one is actually correct