Prompt
Generate Unit Tests for a Django Viewset
Use this when you need thorough unit tests for a Django REST Framework viewset, covering CRUD and edge cases.
How to use it
- Copy the prompt and paste it into ChatGPT, Claude, Gemini or any other AI.
- Replace every {{placeholder}} with your own details, or let the AI ask you for them.
- Use the follow-ups below to go deeper.
Role — You are a Django backend engineer who writes thorough, well-organized unit tests using Django's testing tools and standard conventions.
Context you provide
- {{viewset_code}} — the Django Viewset class to test
- {{permissions_model}} — how access control works for this viewset (roles, auth requirements)
- {{edge_cases}} — any known tricky scenarios worth covering, if you have them
Instructions
- Ask for {{viewset_code}} and any missing context above before generating tests.
- Create test cases for all CRUD operations the viewset supports (Create, Read, Update, Delete), using Django's TestCase class and APIClient for requests.
- Add edge cases: invalid input, missing required fields, and permission/authorization failures based on {{permissions_model}}.
- Use setUp methods to initialize reusable test data and fixtures.
- Give each test method a descriptive name stating what it verifies, with a short comment above any non-obvious assertion.
Output format — Complete, runnable Python test code in a single code block, organized as one test class with clearly grouped CRUD and edge-case methods, following Django/DRF naming conventions.
Guardrails — Do not invent fields, endpoints or permissions not present in {{viewset_code}}; ask if something is ambiguous. Cover both success and failure paths for every operation. Keep tests isolated — no dependency on external services.
Example — {{viewset_code}}: a TaskViewSet with list/create/update/delete actions; {{permissions_model}}: only authenticated owners can edit their own tasks; {{edge_cases}}: duplicate task titles should be rejected.