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
Test & Document API0%
Study Materials
REST API Development with DjangoProgress 0%
1.1REST Principles1.2HTTP Methods Overview1.3Status Codes
10.1Build REST API for E-commerce App10.2CRUD, Authentication, Filtering, Pagination10.3Test & Document API
HomeTutorialsREST API Development with DjangoTest & Document API

Test & Document API

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

DRF Capstone: Automated Test Suite and Production Swagger Docs

To complete our capstone E-Commerce REST API, we implement comprehensive automated test coverage for the entire checkout flow and configure production-grade OpenAPI documentation.


1. Full E-Commerce Test Suite

Create store/tests/test_ecommerce_flow.py:

1from rest_framework.test import APITestCase
2from rest_framework import status
3from django.contrib.auth import get_user_model
4from store.models import Category, Product, Cart, CartItem, Order
5 
6User = get_user_model()
7 
8class ECommerceAPITests(APITestCase):
9 def setUp(self):
10 self.user = User.objects.create_user(username='john_doe', password='secretpassword123')
11 self.category = Category.objects.create(name='Hardware', slug='hardware')
12 self.product = Product.objects.create(
13 category=self.category,
14 title='4K Ultra HD Monitor',
15 slug='4k-ultra-hd-monitor',
16 description='Crisp 3840x2160 IPS panel',
17 price=399.99,
18 inventory=10
19 )
20 
21 def test_complete_e2e_shopping_flow(self):
22 # 1. Anonymous user creates a cart
23 cart_res = self.client.post('/api/v1/carts/', format='json')
24 self.assertEqual(cart_res.status_code, status.HTTP_201_CREATED)
25 cart_id = cart_res.data['id']
26 
27 # 2. Add product to cart
28 add_item_url = f'/api/v1/carts/{cart_id}/items/'
29 item_res = self.client.post(
30 add_item_url,
31 {'product_id': self.product.id, 'quantity': 2},
32 format='json'
33 )
34 self.assertEqual(item_res.status_code, status.HTTP_201_CREATED)
35 
36 # 3. Verify unauthenticated checkout fails
37 order_url = '/api/v1/orders/'
38 unauth_order_res = self.client.post(
39 order_url,
40 {'cart_id': cart_id, 'shipping_address': '100 Main St, Austin, TX'},
41 format='json'
42 )
43 self.assertEqual(unauth_order_res.status_code, status.HTTP_401_UNAUTHORIZED)
44 
45 # 4. Authenticate user and checkout
46 self.client.force_authenticate(user=self.user)
47 order_res = self.client.post(
48 order_url,
49 {'cart_id': cart_id, 'shipping_address': '100 Main St, Austin, TX'},
50 format='json'
51 )
52 self.assertEqual(order_res.status_code, status.HTTP_201_CREATED)
53 
54 # 5. Verify database state
55 self.product.refresh_from_db()
56 self.assertEqual(self.product.inventory, 8) # 10 - 2
57 self.assertFalse(Cart.objects.filter(id=cart_id).exists()) # Cart flushed
58 self.assertEqual(Order.objects.filter(customer=self.user).count(), 1)

2. Verifying Stock Depletion Fails Gracefully

1 def test_checkout_fails_when_quantity_exceeds_stock(self):
2 # Create cart and add more than available inventory (15 > 10)
3 cart = Cart.objects.create()
4 CartItem.objects.create(cart=cart, product=self.product, quantity=15)
5 
6 self.client.force_authenticate(user=self.user)
7 response = self.client.post(
8 '/api/v1/orders/',
9 {'cart_id': str(cart.id), 'shipping_address': '200 Oak Ave'},
10 format='json'
11 )
12 self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
13 self.product.refresh_from_db()
14 self.assertEqual(self.product.inventory, 10) # Stock untouched

3. Production OpenAPI Documentation Verification

Run the spectacular schema check management command:

1python manage.py spectacular --validate --file schema.yml

This verifies that:

  1. 1
    Every serializer field has a valid OpenAPI primitive or component type.
  2. 2
    All custom filters and paginators are documented.
  3. 3
    There are zero schema generator warnings.

4. Summary of DRF Mastery

DomainKey Skills Mastered
FoundationsREST statelessness, HTTP status codes, serializers, serialization/deserialization
Views & RoutingAPIView, Generic Views, ViewSets, DefaultRouter, ModelViewSet
AuthenticationTokenAuth, SimpleJWT, Refresh Tokens, Custom Permissions, Object Permissions
Data Optimizationdjango-filter, SearchFilter, OrderingFilter, PageNumber/Cursor Pagination, select_related
TestingAPITestCase, APIClient, force_authenticate, factory_boy, E2E workflows
Documentationdrf-spectacular, OpenAPI 3.0, Swagger UI, Redoc, @extend_schema

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What does python manage.py spectacular --validate do?
Question 2
In an e-commerce API test, what does self.product.refresh_from_db() guarantee after an order checkout?
Question 3
Why should unauthenticated users be blocked from placing orders (401 Unauthorized)?
Question 4
What happens if a customer attempts to purchase more units than are in stock?
Question 5
What is the main benefit of providing both Swagger UI and Redoc documentation endpoints in production?

Related Lessons

Previous LessonNext Lesson
CRUD, Authentication, Filtering, PaginationNone

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
Previous
PreviousPrevNext