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
A test is a small program that checks your program. In seconds it finds what you would otherwise have to click through by hand.
Almost every test has three parts: prepare the data, perform the action, check the result.
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.
The most popular testing library for Python. It finds test_*.py files and test_* functions by itself.
pip install pytest
pytest
pytest -k vat
pytest -x
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.
The test client sends requests to the app without a server or a browser.
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 creates a separate temporary database, so your real data is not affected.
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)
python manage.py test
python manage.py test tasks
The goal is not 100% coverage but protecting what matters.
Save a working version of your code before new changes.