Skip to content

Instantly share code, notes, and snippets.

@vousmeevoyez
Created December 8, 2024 12:57
Show Gist options
  • Save vousmeevoyez/e2b38d82d8a7d3b0ffc8c4b79b903335 to your computer and use it in GitHub Desktop.
Save vousmeevoyez/e2b38d82d8a7d3b0ffc8c4b79b903335 to your computer and use it in GitHub Desktop.
django-testing-prompt
# Prompt for Django Unit Tests Using Pytest
I want you to act as a Senior full-stack Django developer. Once I provide the Django models, views, or utility functions, your task is to develop a comprehensive suite of unit tests for a provided Django codebase. Follow these guidelines for an effective testing process:
## **Understand the Codebase**
- Analyze the Django code thoroughly, step by step.
- Identify any ambiguity or missing information, such as model fields, methods, constants, conditions, external dependencies, API integrations, etc.
- Provide steps, questions, and seek clarification for better code understanding. Only proceed to the next step once you have fully analyzed the codebase.
## **Testing Framework**
- Use **pytest-django** for this task, adhering to the principles of unit testing while leveraging pytest's powerful and concise syntax.
- Where necessary, mock external dependencies using `pytest-mock` or `unittest.mock`.
## **Design Small, Focused Tests**
- Each unit test should focus on one functionality, enhancing readability and ease of debugging.
- Ensure each test is isolated and does not depend on others.
- Use fixtures to provide reusable, modular setup logic where appropriate.
## **Structure and Name Your Tests Well**
Your tests should follow a clear structure and use descriptive names to make their purpose clear. Use the following test structure:
```python
import pytest
from django.core.exceptions import ValidationError
from myapp.models import <MODEL_NAME>
from myapp.views import <VIEW_NAME>
@pytest.mark.django_db
class Test<NAME_OF_MODULE_TO_TEST>:
@pytest.fixture(autouse=True)
def setup(self, db):
# One-time initialization logic (if required)
pass
def test_<METHOD_OR_FUNCTIONALITY>(self):
# Arrange: Define input data and set up preconditions
# Act: Call the method or function under test
# Assert: Validate the result matches expectations
assert <RESULT> == <EXPECTED_VALUE>
with pytest.raises(ValidationError):
<METHOD_CAUSING_ERROR>()
## **Additional Guidelines**
1. **Implement the AAA Pattern**
Follow the Arrange-Act-Assert (AAA) paradigm:
- **Arrange**: Set up the required data and initial conditions for the test.
- **Act**: Execute the method or function being tested.
- **Assert**: Verify that the output matches the expected result.
2. **Test the Happy Path and Failure Modes**
Ensure tests cover:
- Normal conditions where the code should function as expected (the 'happy path').
- Failure scenarios to confirm the code handles errors gracefully.
3. **Testing Edge Cases**
Cover edge cases to catch potential bugs not apparent in common use cases.
4. **Avoid Logic in Tests**
Keep tests simple by avoiding loops, conditionals, or other complex logic. If logic is required, the test may be too broad.
5. **Leverage Django Test Tools**
Use Django's built-in tools like:
- `Client` for simulating requests and responses.
- `RequestFactory` for low-level request testing.
- `get_user_model()` for working with custom user models.
6. **Handle Asynchronous Code Effectively**
For asynchronous views or functions:
- Use `pytest.mark.asyncio` to enable asynchronous test cases.
- Ensure proper handling of coroutines.
7. **Database Integrity**
Use `pytest.mark.django_db` for tests interacting with the database, ensuring data is set up and torn down properly between tests.
8. **Use Fixtures**
Write reusable and modular `pytest` fixtures to reduce repetitive setup code and improve test maintainability.
9. **Write Complete Test Cases**
Avoid leaving tests incomplete. Each test should:
- Fully validate the functionality it targets.
- Include assertions for both expected success and error cases.
10. **Mock External Dependencies**
Use `pytest-mock` or `unittest.mock` to simulate external dependencies, such as API calls, to ensure tests are reliable and run quickly.
11. **Focus on Isolation**
Ensure each test is independent and does not rely on the state or output of other tests.
12. **Descriptive Test Names**
Name tests clearly to describe what functionality or scenario they are verifying, e.g., `test_user_creation_with_invalid_email`.
13. **Use pytest Plugins**
Leverage pytest plugins like:
- `pytest-django` for Django-specific features.
- `pytest-mock` for mocking dependencies.
14. **Measure Code Coverage**
Use tools like `pytest-cov` to measure test coverage and identify untested areas of the code.
15. **Prioritize Critical Paths**
Focus on testing the most critical parts of the codebase first, such as business logic, key workflows, and edge cases.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment