MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Using Django Test Client0%
Study Materials
REST API Development with DjangoProgress 0%
1.1REST Principles1.2HTTP Methods Overview1.3Status Codes
8.1Unit Testing API Endpoints8.2Using Django Test Client8.3Automated API Tests
HomeTutorialsREST API Development with DjangoUsing Django Test Client
Automated API Tests

Using Django Test Client

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Testing DRF Authentication and Permissions

Testing security boundaries is paramount for any enterprise REST API. You must verify that unauthenticated users are rejected with 401 Unauthorized, unauthorized authenticated users are blocked with 403 Forbidden, and role-based or object-level permissions strictly isolate tenant data.


1. force_authenticate() vs Direct Token Generation

DRF's APIClient provides the force_authenticate() utility. It bypasses the cryptographic validation of headers or tokens and directly attaches the requested user and auth credentials to request.user:

1from rest_framework.test import APITestCase
2from rest_framework import status
3from django.contrib.auth import get_user_model
4 
5User = get_user_model()
6 
7class AuthenticationSecurityTests(APITestCase):
8 def setUp(self):
9 self.regular_user = User.objects.create_user(username='alice', password='password123')
10 self.admin_user = User.objects.create_superuser(username='superadmin', password='adminpassword')
11 self.protected_url = '/api/v1/admin-analytics/'
12 
13 def test_unauthenticated_request_rejected(self):
14 # Default client is anonymous
15 response = self.client.get(self.protected_url)
16 self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
17 
18 def test_regular_user_forbidden(self):
19 # Alice is logged in, but not an admin
20 self.client.force_authenticate(user=self.regular_user)
21 response = self.client.get(self.protected_url)
22 self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
23 
24 def test_admin_user_allowed(self):
25 self.client.force_authenticate(user=self.admin_user)
26 response = self.client.get(self.protected_url)
27 self.assertEqual(response.status_code, status.HTTP_200_OK)
28 
29 def test_unauthenticate_resets_client(self):
30 self.client.force_authenticate(user=self.admin_user)
31 self.client.force_authenticate(user=None) # Reset to anonymous
32 response = self.client.get(self.protected_url)
33 self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

2. Testing Real Token & JWT Authentication Flows

While force_authenticate is ideal for view logic, you also need tests that verify token generation and parsing:

1from rest_framework_simplejwt.tokens import RefreshToken
2 
3class JWTHeaderTests(APITestCase):
4 def setUp(self):
5 self.user = User.objects.create_user(username='charlie', password='mypassword')
6 refresh = RefreshToken.for_user(self.user)
7 self.access_token = str(refresh.access_token)
8 
9 def test_jwt_bearer_header_authorization(self):
10 url = '/api/v1/user/profile/'
11 # Test valid bearer token
12 response = self.client.get(
13 url,
14 HTTP_AUTHORIZATION=f'Bearer {self.access_token}'
15 )
16 self.assertEqual(response.status_code, status.HTTP_200_OK)
17 
18 def test_invalid_bearer_token_fails(self):
19 url = '/api/v1/user/profile/'
20 response = self.client.get(
21 url,
22 HTTP_AUTHORIZATION='Bearer invalid.corrupted.token'
23 )
24 self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

3. Testing Object-Level Permissions (IsOwnerOrReadOnly)

Ensure user A cannot edit or delete user B's records:

1from store.models import Review
2 
3class ObjectLevelPermissionTests(APITestCase):
4 def setUp(self):
5 self.user_a = User.objects.create_user(username='userA', password='pwd')
6 self.user_b = User.objects.create_user(username='userB', password='pwd')
7 self.review_a = Review.objects.create(author=self.user_a, content="Great product!", rating=5)
8 
9 def test_user_b_cannot_modify_user_a_review(self):
10 self.client.force_authenticate(user=self.user_b)
11 url = f'/api/v1/reviews/{self.review_a.id}/'
12 response = self.client.patch(url, {'content': 'Hacked review'}, format='json')
13 self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
14
15 self.review_a.refresh_from_db()
16 self.assertEqual(self.review_a.content, "Great product!")
17 
18 def test_user_a_can_modify_own_review(self):
19 self.client.force_authenticate(user=self.user_a)
20 url = f'/api/v1/reviews/{self.review_a.id}/'
21 response = self.client.patch(url, {'content': 'Updated review'}, format='json')
22 self.assertEqual(response.status_code, status.HTTP_200_OK)
23
24 self.review_a.refresh_from_db()
25 self.assertEqual(self.review_a.content, 'Updated review')

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What does client.force_authenticate(user=None) do in an APITestCase?
Question 2
Which HTTP header parameter is passed in self.client.get() to simulate an authorization token header in Django tests?
Question 3
When testing an endpoint protected by IsAdminUser, what response status code should a standard authenticated non-staff user receive?
Question 4
Why is testing object-level permissions critical for multi-tenant SaaS or community APIs?
Question 5
What is the main advantage of force_authenticate over issuing real tokens in unit tests?
Next Lesson

Automated API Tests

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Unit Testing API EndpointsAutomated API Tests

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master REST API Development with Django with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext