← Back to Chapters

Testing Models, Views & Forms in DRF

? Testing Models, Views & Forms in DRF

? Quick Overview

Testing in Django REST Framework ensures reliability of business logic, API endpoints, and form validation. By testing models, views, and forms, you can confidently detect issues early and maintain stable APIs.

? Key Concepts

  • Model validation and database integrity
  • API request and response testing
  • Form validation and error handling

? Syntax / Theory

  • Model Tests: Verify fields, methods, and relationships
  • View Tests: Validate HTTP status codes and response data
  • Form Tests: Ensure valid and invalid inputs are handled correctly

? Testing Models

? View Code Example
# Testing Book model creation and string representation
from django.test import TestCase
from .models import Book

class BookModelTest(TestCase):
def test_create_book(self):
book = Book.objects.create(title="Test Book", author="Test Author", price="19.99")
self.assertEqual(book.title, "Test Book")
self.assertEqual(book.author, "Test Author")
self.assertEqual(str(book), "Test Book")

? Testing Views

? View Code Example
# Testing GET request for book list API
from rest_framework.test import APITestCase
from rest_framework import status
from .models import Book

class BookViewSetTest(APITestCase):
def setUp(self):
Book.objects.create(title="Test Book", author="Test Author", price="19.99")

def test_book_list(self):
response = self.client.get('/api/books/')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 1)
self.assertEqual(response.data[0]['title'], 'Test Book')

? Testing Forms

? View Code Example
# Testing form validation for BookForm
from django import forms
from django.test import TestCase
from .models import Book

class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ['title', 'author', 'price']

class BookFormTest(TestCase):
def test_form_valid(self):
form = BookForm(data={'title':'Test Book','author':'Test Author','price':'19.99'})
self.assertTrue(form.is_valid())

def test_form_invalid(self):
form = BookForm(data={'title':'','author':'Test Author','price':'19.99'})
self.assertFalse(form.is_valid())

? Interactive Test Simulator

Simulate running a Unit Test for creating a Book. Validates that Title is present and Price is positive.

Ready to test... waiting for input.

? Live Output / Explanation

  • Models confirm correct field storage and behavior
  • Views ensure API endpoints respond accurately
  • Forms validate user input and display errors properly

? Use Cases

  • API reliability testing
  • Preventing regression bugs
  • Validating user input workflows

✅ Tips & Best Practices

  • Test both success and failure cases
  • Use setup methods to avoid duplication
  • Keep tests isolated and deterministic

? Try It Yourself

  • Write tests for custom model methods
  • Test authenticated vs unauthenticated API access
  • Add form tests for edge-case inputs