Learn / Frameworks / Django / Testing Django Apps

Django · Lesson 10 of 15

Testing Django Apps

TestCase, the test client, fixtures and asserting on the database.

  • Intermediate
  • 16 min read
  • 3 objectives

Before this lessonLesson 9: Middleware, Signals and Settings

What you will learn

  • Write a model test
  • Post through the client
  • Use a fixture

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

Django's TestCase wraps each test in a transaction, gives you a test client, and creates a throwaway database.

Model and view tests

from django.test import TestCase
from django.urls import reverse
from .models import Post

class PostTests(TestCase):
    def setUp(self):
        self.post = Post.objects.create(title="Hello", body="Hi", published=True)

    def test_str(self):
        self.assertEqual(str(self.post), "Hello")

    def test_list_shows_published(self):
        res = self.client.get(reverse("post-list"))
        self.assertContains(res, "Hello")
        self.assertEqual(res.status_code, 200)

    def test_create_requires_login(self):
        res = self.client.post(reverse("post-create"), {"title": "x", "body": "y"})
        self.assertEqual(res.status_code, 302)   # redirect to login

The test client and a user

from django.contrib.auth.models import User

self.user = User.objects.create_user("ada", password="pass-pass")
self.client.login(username="ada", password="pass-pass")
res = self.client.post(reverse("post-create"), {"title": "New", "body": "Body"})

Fixtures vs factories

JSON fixtures are brittle. Prefer creating objects in setUp or using factory_boy. Mark tests that hit an external API with @override_settings and mock the call.

python manage.py test
python manage.py test blog.tests.test_views.PostTests.test_str
Up next · Lesson 11Static Files, Media and Cachingcollectstatic, user uploads, WhiteNoise and the cache framework.