← Back to Chapters

Unit Testing with unittest & pytest in DRF

? Unit Testing with unittest & pytest in DRF

? Quick Overview

Unit testing ensures the correctness of your Django REST Framework APIs. You can test views, serializers, and models using Python’s built-in unittest or the popular pytest framework.

? Key Concepts

  • Testing APIs in isolation
  • Validating HTTP responses
  • Database interaction during tests
  • Automated regression testing

? Syntax & Theory

Django provides TestCase and DRF extends it with APITestCase. Pytest offers decorators, fixtures, and simpler assertions.

? Code Example – unittest

? View Code Example
# Testing API views using DRF APITestCase
from rest_framework.test import APITestCase
from rest_framework import status
from .models import Book

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

    def test_book_list(self):
        # Verify GET request for book list
        response = self.client.get('/api/books/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data), 1)

    def test_create_book(self):
        # Verify POST request for creating a book
        data = {'title': 'New Book','author':'New Author','price':'29.99'}
        response = self.client.post('/api/books/', data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

? Code Example – pytest

? View Code Example
# Pytest style testing for DRF APIs
import pytest
from rest_framework import status
from .models import Book

@pytest.mark.django_db
def test_book_list(client):
    # Arrange test data
    Book.objects.create(title="Test Book", author="Test Author", price="19.99")
    response = client.get('/api/books/')
    assert response.status_code == status.HTTP_200_OK

@pytest.mark.django_db
def test_create_book(client):
    # Create a book using POST request
    data = {'title':'New Book','author':'New Author','price':'29.99'}
    response = client.post('/api/books/', data, format='json')
    assert response.status_code == status.HTTP_201_CREATED

? Live Output / Explanation

Successful tests return HTTP 200 or 201 responses. Any failure produces detailed error output in the terminal.

? Interactive Concept

Think of each test as a simulation of a real client request validating your API endpoints automatically.

?️ Simulator: "Create Book" Test Case

Try running the test. If you leave the Title empty, the test will FAIL (just like in DRF).

> Waiting for test execution..._

? Use Cases

  • Testing CRUD APIs
  • Validating authentication & permissions
  • Ensuring backward compatibility
  • CI/CD pipeline automation

✅ Tips & Best Practices

  • Prefer pytest for cleaner syntax
  • Test edge cases & invalid inputs
  • Use fixtures to avoid repetition

? Try It Yourself

  • Write tests for all HTTP methods
  • Compare unittest vs pytest syntax
  • Explore DRF test client features