Django's test client is a powerful tool for testing views and HTTP responses within your application. It simulates user interactions by making HTTP requests to the views you want to test without needing a real browser.
The test client is accessed using self.client inside classes that inherit from django.test.TestCase.
# Test GET request for book list
from django.test import TestCase
from rest_framework import status
from .models import Book
class BookTests(TestCase):
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')
# Test POST request to create book
class BookCreateTests(TestCase):
def test_create_book(self):
url = '/api/books/'
data = {'title': 'New Book', 'author': 'New Author', 'price': '29.99'}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data['title'], data['title'])
# Test authenticated POST request
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
class BookAuthTests(TestCase):
def setUp(self):
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_create_book_authenticated(self):
url = '/api/books/'
data = {'title': 'Authenticated Book', 'author': 'Auth Author', 'price': '29.99'}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data['title'], data['title'])
# Update existing book
class BookUpdateTests(TestCase):
def setUp(self):
self.book = Book.objects.create(title="Test Book", author="Test Author", price="19.99")
def test_update_book(self):
url = f'/api/books/{self.book.id}/'
data = {'title': 'Updated Book', 'author': 'Updated Author', 'price': '39.99'}
response = self.client.put(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['title'], data['title'])
# Delete existing book
class BookDeleteTests(TestCase):
def setUp(self):
self.book = Book.objects.create(title="Test Book", author="Test Author", price="19.99")
def test_delete_book(self):
url = f'/api/books/{self.book.id}/'
response = self.client.delete(url)
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
Configure a mock request to see how the Test Client responds. Try using GET for a list, or POST to create data.