Testing

Unit Testing

Use Django's built-in test framework for unit tests. Place tests in each app's tests.py or a tests/ folder. Test individual functions, methods, and models in isolation.

Example:

from django.test import TestCase
from .models import User

class UserModelTest(TestCase):
    def test_full_name(self):
        user = User(name='John Doe')
        self.assertEqual(user.name, 'John Doe')

Integration Testing

Test interactions between multiple components (e.g., models, views, forms). Use Django's test client for HTTP requests and response validation.

Example:

from django.test import TestCase
from django.urls import reverse

class UserViewTest(TestCase):
    def test_user_list_view(self):
        response = self.client.get(reverse('user_list'))
        self.assertEqual(response.status_code, 200)

Feature Testing

Test end-to-end workflows and user scenarios. Use fixtures or factories for test data.

Mocking

Use Python's unittest.mock or third-party libraries (e.g., pytest-mock) to mock external dependencies and isolate tests.

Example:

from unittest.mock import patch

class ExternalServiceTest(TestCase):
    @patch('app.services.send_email')
    def test_email_sent(self, mock_send_email):
        mock_send_email.return_value = True
        # ...test logic...

Best Practices

  • Write tests for all new features and bug fixes.
  • Use descriptive test names and group related tests.
  • Run tests automatically in CI/CD pipelines.
  • Aim for high code coverage, but prioritize meaningful tests.
  • Document test structure and conventions for new team members.