How to change code without breaking it

A test is a small program that checks your program. In seconds it finds what you would otherwise have to click through by hand.

A lab assistant loads samples into a test chamber. A photo from the 1910–1920 report of the US Forest Products Laboratory

How a test is built

Almost every test has three parts: prepare the data, perform the action, check the result.

The simplest checks with assert
def add_vat(price, rate=0.12):
    return round(price * (1 + rate), 2)

def test_add_vat():
    assert add_vat(100) == 112.0

def test_custom_rate():
    assert add_vat(200, rate=0.2) == 240.0

test_add_vat()
test_custom_rate()
print("All tests passed")

Change the expected value in the example and run it again: you will see what a failing test looks like.

pytest

The most popular testing library for Python. It finds test_*.py files and test_* functions by itself.

Terminal
pip install pytest
pytest
pytest -k vat
pytest -x
test_prices.py
import pytest

from prices import add_vat

@pytest.mark.parametrize("price, expected", [
    (100, 112.0),
    (0, 0.0),
    (19.99, 22.39),
])
def test_add_vat(price, expected):
    assert add_vat(price) == expected

def test_negative_price():
    with pytest.raises(ValueError):
        add_vat(-1)

parametrize runs one test with different data. raises checks that the code reports an error correctly. In the second test the function must reject a negative price itself.

Flask tests

The test client sends requests to the app without a server or a browser.

Flask: checking a page and the API
from flask import Flask

app = Flask(__name__)

@app.get("/")
def home():
    return "Home"

@app.get("/api/ping")
def ping():
    return {"status": "ok"}

def test_home():
    response = app.test_client().get("/")
    assert response.status_code == 200
    assert "Home" in response.text

def test_ping():
    assert app.test_client().get("/api/ping").json == {"status": "ok"}

def test_unknown_page():
    assert app.test_client().get("/nope").status_code == 404

test_home()
test_ping()
test_unknown_page()
print("All tests passed")

In a real project these functions live in test_app.py, and the pytest command runs them.

Django tests

Django creates a separate temporary database, so your real data is not affected.

tasks/tests.py
from django.test import TestCase
from django.urls import reverse

from .models import Task

class TaskTests(TestCase):
    def test_list_shows_task(self):
        Task.objects.create(title="Check the tests")
        response = self.client.get(reverse("index"))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Check the tests")

    def test_add_task(self):
        response = self.client.post(reverse("index"), {"title": "New"})
        self.assertRedirects(response, reverse("index"))
        self.assertEqual(Task.objects.count(), 1)
Terminal
python manage.py test
python manage.py test tasks

What to test first

The goal is not 100% coverage but protecting what matters.

Worth checking

  • The main scenario: create, change, delete
  • Invalid and empty data
  • Access: other people's data and pages without login
  • Every bug you find: first a test, then the fix

You can skip

  • The framework's own code
  • Simple settings without logic
  • The exact position of elements on the page

Sources

Links checked on .

Next: Git

Save a working version of your code before new changes.