← Back to Chapters

Testing in Django REST Framework

? Testing in Django REST Framework

? Quick Overview

Testing is an essential part of software development. In Django REST Framework (DRF), testing helps ensure that your API views and business logic are working as expected. DRF provides a rich testing framework built on Django's unittest library, making it easy to test API endpoints, model interactions, and application logic.

? Key Concepts

  • Consistency and reliability of API responses
  • Authentication and permission validation
  • Regression prevention
  • Tests as living documentation

? Syntax / Theory

DRF extends Django’s unittest framework with tools like APITestCase and APIClient to simulate HTTP requests and validate responses, status codes, and authentication behaviors.

? Code Example(s)

? View Code Example
# Testing a simple GET API endpoint
from rest_framework.test import APITestCase
from rest_framework import status
from .models import Book

class BookTests(APITestCase):
    def setUp(self):
        # Create a test book before each test
        Book.objects.create(title="Test Book", author="Test Author", price="19.99")

    def test_book_list(self):
        # Send GET request to books API
        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')

? Live Output / Explanation

This test confirms that the API returns a 200 OK response, includes exactly one book, and matches the expected title.

? Authentication Testing

? View Code Example
# Testing API with token authentication
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase
from django.contrib.auth.models import User
from rest_framework import status

class BookTests(APITestCase):
    def setUp(self):
        # Create user and assign token
        self.user = User.objects.create_user(username='testuser', password='password')
        self.token = Token.objects.create(user=self.user)
        self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)

    def test_book_list_authenticated(self):
        # Access endpoint with authentication
        response = self.client.get('/api/books/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

? Interactive Test Runner

Simulate running the test suite defined above. Click the button to initialize the test database and run checks.

// Console output will appear here...

? Use Cases

  • Validating CRUD APIs
  • Testing protected endpoints
  • Ensuring role-based access
  • Preventing production regressions

✅ Tips & Best Practices

  • Test all HTTP methods and user roles
  • Use setUp() for reusable test data
  • Cover edge cases and invalid inputs

? Try It Yourself

  • Write tests for POST, PUT, DELETE APIs
  • Experiment with different authentication methods
  • Test failure cases like missing tokens