Django Tests
Django provides TestCase with database isolation and a test client for HTTP requests.
Django provides TestCase with database isolation and a test client for HTTP requests.
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/")
Django TestCase wraps each test in a transaction and rolls back — fast and isolated.