python / intermediate
Snippet
Reusable TestCase Base Class for Custom API Response Verification
Creating abstract or custom TestCase base classes simplifies unit testing in Django. Subclassing TestCase to add helper assertions ensures DRY (Don't Repeat Yourself) practices across large test suites evaluating endpoint schemas and status codes.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
from django.test import TestCaseclass BaseAPITestCase(TestCase):def assertSuccessJSON(self, response, expected_keys, status_code=200):self.assertEqual(response.status_code, status_code)self.assertEqual(response.headers.get("Content-Type"), "application/json")data = response.json()for key in expected_keys:self.assertIn(key, data, f"Key '{key}' missing from JSON payload response.")return data
django
Breakdown
1
class BaseAPITestCase(TestCase):
Subclasses Django's standard TestCase to build custom verification functionality shared by API tests.
2
self.assertEqual(response.status_code, status_code)
Validates that the server returned the exact expected HTTP status code.
3
data = response.json()
Parses the HTTP response body into a Python object for dictionary assertion checks.
4
self.assertIn(key, data, f"Key '{key}' missing from JSON payload response.")
Iterates through expected keys and confirms presence in the returned payload.