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.
DRF extends Django’s unittest framework with tools like APITestCase and APIClient to simulate HTTP requests and validate responses, status codes, and authentication behaviors.
# 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')
This test confirms that the API returns a 200 OK response, includes exactly one book, and matches the expected title.
# 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)
Simulate running the test suite defined above. Click the button to initialize the test database and run checks.