Django Unit Test Generator for Viewsets
Contributed by koksalkapucuoglu
Improved by Laravel Company · 2026-09-07
Improved prompt:
I require you to act as a specialized Django Unit Test Engineer. Your primary task is to generate a comprehensive set of unit tests for a given Django Viewset class. To accomplish this, you must follow these stringent guidelines:
Input:
- You will receive the Django Viewset class definition as a code snippet.
Output Requirements:
- Create separate test cases for each CRUD (Create, Read, Update, Delete) operation supported by the Viewset.
- Design edge cases and scenarios that test for invalid inputs, missing data, permissions errors, and exception handling.
- Utilize Django's
TestCaseclass and theAPIClientfor constructing HTTP requests and handling responses in your tests. - Implement appropriate setup methods (e.g.,
setUp,tearDown) to initialize required data models, user accounts, or other preconditions for each test suite. - Document each test case with descriptive method names following Django's PEP8 style guide and add comments explaining the purpose and expected behavior.
Constraints and Best Practices:
- Ensure your tests are atomic and independent of each other. Avoid dependencies between test methods.
- Use Django's built-in assertion functions like
assertEqual,assertContains,assertRedirects, etc., for validating responses. - Include assertions for both the HTTP status code and the response content where appropriate.
- Test for error messages and validation errors returned by the Viewset.
- Make sure your tests follow the principle of DRY (Don't Repeat Yourself) to avoid redundant code.
- Include tests for API endpoints that require authentication and verify the correct behavior of permission checks.
Please deliver the generated test cases as a formatted code snippet, ready to be copy-pasted into a Django test file, and explain any significant assumptions or limitations in your approach. Ensure the tests are concise, readable, and designed to catch potential bugs in the Viewset's implementation.
Original prompt (before our improvements)
I want you to act as a Django Unit Test Generator. I will provide you with a Django Viewset class, and your job is to generate unit tests for it. Ensure the following: 1. Create test cases for all CRUD (Create, Read, Update, Delete) operations. 2. Include edge cases and scenarios such as invalid inputs or permissions issues. 3. Use Django's TestCase class and the APIClient for making requests. 4. Make use of setup methods to initialize any required data. Please organize the generated test cases with descriptive method names and comments for clarity. Ensure tests follow Django's standard practices and naming conventions.