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
Automated API Tests0%
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 DjangoAutomated API Tests
Swagger UI Integration

Automated API Tests

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

Automated API Integration Tests and Model Factories

As test suites grow from tens to hundreds of test cases, manual Model.objects.create(...) calls result in fragile, verbose, and difficult-to-maintain test setups. Using factory_boy and faker provides clean, dynamic mock fixtures, while end-to-end integration tests verify complete business workflows.


1. Setting Up factory_boy for DRF Models

factory_boy generates realistic model instances with foreign keys, default attributes, and sequence counters.

1pip install factory_boy faker

Create store/factories.py:

1import factory
2from django.contrib.auth import get_user_model
3from store.models import Category, Product, Order, OrderItem
4 
5User = get_user_model()
6 
7class UserFactory(factory.django.DjangoModelFactory):
8 class Meta:
9 model = User
10 
11 username = factory.Faker('user_name')
12 email = factory.Faker('email')
13 first_name = factory.Faker('first_name')
14 last_name = factory.Faker('last_name')
15 
16class CategoryFactory(factory.django.DjangoModelFactory):
17 class Meta:
18 model = Category
19 
20 name = factory.Sequence(lambda n: f'Category {n}')
21 slug = factory.Sequence(lambda n: f'category-{n}')
22 
23class ProductFactory(factory.django.DjangoModelFactory):
24 class Meta:
25 model = Product
26 
27 category = factory.SubFactory(CategoryFactory)
28 title = factory.Faker('catch_phrase')
29 sku = factory.Sequence(lambda n: f'SKU-{n:05d}')
30 price = factory.Faker('pydecimal', left_digits=3, right_digits=2, positive=True)
31 inventory = 50

2. Using Factories in API Integration Tests

Notice how concise and expressive test setup becomes:

1from rest_framework.test import APITestCase
2from rest_framework import status
3from store.factories import UserFactory, ProductFactory, CategoryFactory
4 
5class ProductSearchIntegrationTests(APITestCase):
6 def setUp(self):
7 self.user = UserFactory()
8 self.cat_laptops = CategoryFactory(name='Laptops')
9 self.cat_audio = CategoryFactory(name='Audio')
10
11 # Batch create products
12 self.macbook = ProductFactory(category=self.cat_laptops, title='Apple MacBook Pro 16')
13 self.dell = ProductFactory(category=self.cat_laptops, title='Dell XPS 15')
14 self.headphones = ProductFactory(category=self.cat_audio, title='Sony WH-1000XM5 Headphones')
15 
16 def test_filter_by_category_returns_matching_products(self):
17 response = self.client.get('/api/v1/products/', {'category': self.cat_laptops.id})
18 self.assertEqual(response.status_code, status.HTTP_200_OK)
19 self.assertEqual(response.data['count'], 2)
20 titles = [p['title'] for p in response.data['results']]
21 self.assertIn('Apple MacBook Pro 16', titles)
22 self.assertIn('Dell XPS 15', titles)
23 self.assertNotIn('Sony WH-1000XM5 Headphones', titles)

3. End-to-End Workflow Testing: Order Checkout

Integration tests should test multi-step workflows representing real client interactions:

1class CheckoutWorkflowTests(APITestCase):
2 def setUp(self):
3 self.customer = UserFactory()
4 self.product = ProductFactory(price=100.00, inventory=10)
5 
6 def test_complete_checkout_workflow(self):
7 self.client.force_authenticate(user=self.customer)
8
9 # Step 1: Create Cart
10 cart_res = self.client.post('/api/v1/carts/', format='json')
11 self.assertEqual(cart_res.status_code, status.HTTP_201_CREATED)
12 cart_id = cart_res.data['id']
13 
14 # Step 2: Add item to cart
15 item_res = self.client.post(
16 f'/api/v1/carts/{cart_id}/items/',
17 {'product': self.product.id, 'quantity': 2},
18 format='json'
19 )
20 self.assertEqual(item_res.status_code, status.HTTP_201_CREATED)
21 
22 # Step 3: Checkout order
23 checkout_res = self.client.post(
24 '/api/v1/orders/',
25 {'cart_id': cart_id, 'shipping_address': '123 Tech Lane, San Francisco, CA'},
26 format='json'
27 )
28 self.assertEqual(checkout_res.status_code, status.HTTP_201_CREATED)
29 self.assertEqual(checkout_res.data['total_price'], '200.00')
30 
31 # Step 4: Verify stock deduction
32 self.product.refresh_from_db()
33 self.assertEqual(self.product.inventory, 8)

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What primary benefit does factory_boy provide in Django test suites?
Question 2
What is factory.SubFactory() used for in factory_boy?
Question 3
How does factory.Sequence() prevent database uniqueness constraint collisions?
Question 4
What distinguishes an integration test from an isolated unit test in DRF?
Question 5
In an end-to-end order placement test, why must product.refresh_from_db() be called?
Next Lesson

Swagger UI Integration

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

Related Lessons

Previous LessonNext Lesson
Using Django Test ClientSwagger UI Integration

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