SyntaxStudy
Sign Up
Python Testing Django Applications
Python Intermediate 4 min read

Testing Django Applications

Django Tests

Django provides TestCase with database isolation and a test client for HTTP requests.

Example
from django.test import TestCase, Client
from myapp.models import User

class UserViewTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.user = User.objects.create_user(username="alice", password="pass123")

    def test_login(self):
        resp = self.client.post("/login/", {"username": "alice", "password": "pass123"})
        self.assertEqual(resp.status_code, 302)

    def test_profile_requires_auth(self):
        resp = self.client.get("/profile/")
        self.assertRedirects(resp, "/login/?next=/profile/")
Pro Tip

Django TestCase wraps each test in a transaction and rolls back — fast and isolated.