Chapter 14 · 10 min read
Testing Basics
Testing Basics
Automated tests are small programs that check your site still works after you change it. They give you the confidence to improve code without fear. Django builds on Python's unittest and adds tools for databases and web requests.
What you will learn
- Why testing matters and what to test.
- How to write tests with
django.test.TestCase. - How to use the test client to request pages, post forms and log in.
- How to run all tests or just one.
How Django tests work
- Test classes subclass
django.test.TestCase. Each method whose name starts withtestis one test. - When you run the tests, Django creates a temporary empty database, runs every test, then destroys it. Your real data in
db.sqlite3is never touched. TestCasewraps each test in a transaction that is rolled back afterwards, so tests do not affect each other.self.clientis a fake browser. It canget()pages,post()data andlogin(). It does not needrunserver.
Tests live in blog/tests.py (or a tests/ package). Run them with:
python manage.py test
Step by step
Replace blog/tests.py:
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from .models import Post
User = get_user_model()
class PostModelTests(TestCase):
def test_str_returns_title(self):
user = User.objects.create_user("sam", password="pass12345")
post = Post.objects.create(title="Hello", body="World", author=user)
self.assertEqual(str(post), "Hello")
class PostViewTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.user = User.objects.create_user("sam", password="pass12345")
cls.post = Post.objects.create(title="First", body="Body", author=cls.user)
def test_list_page_shows_post(self):
response = self.client.get(reverse("blog:home"))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "First")
def test_create_requires_login(self):
response = self.client.get(reverse("blog:create"))
self.assertEqual(response.status_code, 302)
self.assertIn("/accounts/login/", response.url)
def test_logged_in_user_can_create_post(self):
self.client.login(username="sam", password="pass12345")
response = self.client.post(
reverse("blog:create"),
{"title": "New post", "body": "Text", "published": "on"},
)
self.assertEqual(Post.objects.count(), 2)
self.assertEqual(response.status_code, 302)
def test_other_user_cannot_edit(self):
User.objects.create_user("eve", password="pass12345")
self.client.login(username="eve", password="pass12345")
response = self.client.get(reverse("blog:edit", args=[self.post.pk]))
self.assertEqual(response.status_code, 403)
Walkthrough:
create_user()hashes the password properly, unlikeUser.objects.create().setUpTestDataruns once per class and creates shared data efficiently.reverse("blog:home")builds the address from the URL name, so tests survive URL changes.assertContains(response, "First")checks the status code is 200 and the text appears in the page.response.status_code == 302means a redirect.response.urlis where it points.- The post to
blog:createincludes"published": "on", exactly how browsers send a ticked checkbox. - A logged-in non-author gets
403because ofUserPassesTestMixin.
Run the tests
python manage.py test
python manage.py test blog
python manage.py test blog.tests.PostViewTests.test_list_page_shows_post
You should see:
Found 5 test(s).
...
Ran 5 tests in 1.0s
OK
Useful assertions
| Assertion | Checks |
|---|---|
assertEqual(a, b) | a == b |
assertTrue(x) / assertFalse(x) | Truthiness |
assertIn(a, b) | a is inside b |
assertContains(response, text) | Status 200 and text present |
assertNotContains(response, text) | Text absent |
assertRedirects(response, url) | A redirect to url |
assertRaises(Error) | Code raises the exception (use with) |
assertTemplateUsed(response, name) | A template was rendered |
What to test
- Behaviour you would hate to break: login rules, permissions, money calculations.
- Every bug you fix, to stop it returning.
- Not Django itself: do not test that
CharFieldstores text.
Check it works
- The command ends with
Ran 5 testsandOK. - Rename a URL on purpose and watch tests fail with a clear message. Rename it back.
Exercises with solutions
Exercise 1: drafts are hidden
Test that a post with published=False does not appear on the home page.
Solution. Add to PostViewTests:
def test_unpublished_post_not_listed(self):
Post.objects.create(
title="Secret draft", body="x", author=self.user, published=False
)
response = self.client.get(reverse("blog:home"))
self.assertNotContains(response, "Secret draft")
Exercise 2: sign-up works
Test that posting valid data to the sign-up page creates a user.
Solution.
class SignUpTests(TestCase):
def test_signup_creates_user(self):
response = self.client.post(
reverse("signup"),
{
"username": "newuser",
"password1": "Tr0ub4dor&3xyz",
"password2": "Tr0ub4dor&3xyz",
},
)
self.assertRedirects(response, reverse("login"))
self.assertTrue(User.objects.filter(username="newuser").exists())
Exercise 3: validation
Test that a title shorter than five characters is rejected by the form.
Solution.
from .forms import PostForm
class PostFormTests(TestCase):
def test_short_title_invalid(self):
form = PostForm(data={"title": "Hi", "body": "Text", "published": True})
self.assertFalse(form.is_valid())
self.assertIn("title", form.errors)
Common mistakes
- Method names not starting with
test. The test never runs. - Expecting your real data in tests. Each run uses a fresh temporary database.
- Forgetting
self.client.login()for a protected page. You get a redirect instead of the page. - Wrong form field names in
post(). Use the names from your form. - Using
User.objects.create()with a password. The password is stored unhashed and login fails. Usecreate_user.
Key takeaways
- Tests protect you from breaking things when you change code.
TestCasegives each test a clean database;self.clientsimulates a browser.- Run
python manage.py testoften, and one test at a time while debugging. - Test behaviour you care about, not Django's own features.
Official links
- Testing in Django: https://docs.djangoproject.com/en/6.1/topics/testing/overview/
- Testing tools: https://docs.djangoproject.com/en/6.1/topics/testing/tools/
- Tutorial part 5: https://docs.djangoproject.com/en/6.1/intro/tutorial05/
