$npx -y skills add skateddu/claude-code-python-setup --skill django-tddDjango testing strategies with pytest-django, TDD methodology, factory_boy, mocking, coverage, and testing Django REST Framework APIs.
| 1 | # Django Testing with TDD |
| 2 | |
| 3 | Test-driven development for Django applications using pytest, factory_boy, and Django REST Framework. |
| 4 | |
| 5 | ## When to Activate |
| 6 | |
| 7 | - Writing new Django applications |
| 8 | - Implementing Django REST Framework APIs |
| 9 | - Testing Django models, views, and serializers |
| 10 | - Setting up testing infrastructure for Django projects |
| 11 | |
| 12 | ## TDD Workflow for Django |
| 13 | |
| 14 | ### Red-Green-Refactor Cycle |
| 15 | |
| 16 | ```python |
| 17 | # Step 1: RED - Write failing test |
| 18 | def test_user_creation(): |
| 19 | user = User.objects.create_user(email='test@example.com', password='testpass123') |
| 20 | assert user.email == 'test@example.com' |
| 21 | assert user.check_password('testpass123') |
| 22 | assert not user.is_staff |
| 23 | |
| 24 | # Step 2: GREEN - Make test pass |
| 25 | # Create User model or factory |
| 26 | |
| 27 | # Step 3: REFACTOR - Improve while keeping tests green |
| 28 | ``` |
| 29 | |
| 30 | ## Setup |
| 31 | |
| 32 | ### pytest Configuration |
| 33 | |
| 34 | ```ini |
| 35 | # pytest.ini |
| 36 | [pytest] |
| 37 | DJANGO_SETTINGS_MODULE = config.settings.test |
| 38 | testpaths = tests |
| 39 | python_files = test_*.py |
| 40 | python_classes = Test* |
| 41 | python_functions = test_* |
| 42 | addopts = |
| 43 | --reuse-db |
| 44 | --nomigrations |
| 45 | --cov=apps |
| 46 | --cov-report=html |
| 47 | --cov-report=term-missing |
| 48 | --strict-markers |
| 49 | markers = |
| 50 | slow: marks tests as slow |
| 51 | integration: marks tests as integration tests |
| 52 | ``` |
| 53 | |
| 54 | ### Test Settings |
| 55 | |
| 56 | ```python |
| 57 | # config/settings/test.py |
| 58 | from .base import * |
| 59 | |
| 60 | DEBUG = True |
| 61 | DATABASES = { |
| 62 | 'default': { |
| 63 | 'ENGINE': 'django.db.backends.sqlite3', |
| 64 | 'NAME': ':memory:', |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | # Disable migrations for speed |
| 69 | class DisableMigrations: |
| 70 | def __contains__(self, item): |
| 71 | return True |
| 72 | |
| 73 | def __getitem__(self, item): |
| 74 | return None |
| 75 | |
| 76 | MIGRATION_MODULES = DisableMigrations() |
| 77 | |
| 78 | # Faster password hashing |
| 79 | PASSWORD_HASHERS = [ |
| 80 | 'django.contrib.auth.hashers.MD5PasswordHasher', |
| 81 | ] |
| 82 | |
| 83 | # Email backend |
| 84 | EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' |
| 85 | |
| 86 | # Celery always eager |
| 87 | CELERY_TASK_ALWAYS_EAGER = True |
| 88 | CELERY_TASK_EAGER_PROPAGATES = True |
| 89 | ``` |
| 90 | |
| 91 | ### conftest.py |
| 92 | |
| 93 | ```python |
| 94 | # tests/conftest.py |
| 95 | import pytest |
| 96 | from django.utils import timezone |
| 97 | from django.contrib.auth import get_user_model |
| 98 | |
| 99 | User = get_user_model() |
| 100 | |
| 101 | @pytest.fixture(autouse=True) |
| 102 | def timezone_settings(settings): |
| 103 | """Ensure consistent timezone.""" |
| 104 | settings.TIME_ZONE = 'UTC' |
| 105 | |
| 106 | @pytest.fixture |
| 107 | def user(db): |
| 108 | """Create a test user.""" |
| 109 | return User.objects.create_user( |
| 110 | email='test@example.com', |
| 111 | password='testpass123', |
| 112 | username='testuser' |
| 113 | ) |
| 114 | |
| 115 | @pytest.fixture |
| 116 | def admin_user(db): |
| 117 | """Create an admin user.""" |
| 118 | return User.objects.create_superuser( |
| 119 | email='admin@example.com', |
| 120 | password='adminpass123', |
| 121 | username='admin' |
| 122 | ) |
| 123 | |
| 124 | @pytest.fixture |
| 125 | def authenticated_client(client, user): |
| 126 | """Return authenticated client.""" |
| 127 | client.force_login(user) |
| 128 | return client |
| 129 | |
| 130 | @pytest.fixture |
| 131 | def api_client(): |
| 132 | """Return DRF API client.""" |
| 133 | from rest_framework.test import APIClient |
| 134 | return APIClient() |
| 135 | |
| 136 | @pytest.fixture |
| 137 | def authenticated_api_client(api_client, user): |
| 138 | """Return authenticated API client.""" |
| 139 | api_client.force_authenticate(user=user) |
| 140 | return api_client |
| 141 | ``` |
| 142 | |
| 143 | ## Factory Boy |
| 144 | |
| 145 | ### Factory Setup |
| 146 | |
| 147 | ```python |
| 148 | # tests/factories.py |
| 149 | import factory |
| 150 | from factory import fuzzy |
| 151 | from datetime import datetime, timedelta |
| 152 | from django.contrib.auth import get_user_model |
| 153 | from apps.products.models import Product, Category |
| 154 | |
| 155 | User = get_user_model() |
| 156 | |
| 157 | class UserFactory(factory.django.DjangoModelFactory): |
| 158 | """Factory for User model.""" |
| 159 | |
| 160 | class Meta: |
| 161 | model = User |
| 162 | |
| 163 | email = factory.Sequence(lambda n: f"user{n}@example.com") |
| 164 | username = factory.Sequence(lambda n: f"user{n}") |
| 165 | password = factory.PostGenerationMethodCall('set_password', 'testpass123') |
| 166 | first_name = factory.Faker('first_name') |
| 167 | last_name = factory.Faker('last_name') |
| 168 | is_active = True |
| 169 | |
| 170 | class CategoryFactory(factory.django.DjangoModelFactory): |
| 171 | """Factory for Category model.""" |
| 172 | |
| 173 | class Meta: |
| 174 | model = Category |
| 175 | |
| 176 | name = factory.Faker('word') |
| 177 | slug = factory.LazyAttribute(lambda obj: obj.name.lower()) |
| 178 | description = factory.Faker('text') |
| 179 | |
| 180 | class ProductFactory(factory.django.DjangoModelFactory): |
| 181 | """Factory for Product model.""" |
| 182 | |
| 183 | class Meta: |
| 184 | model = Product |
| 185 | |
| 186 | name = factory.Faker('sentence', nb_words=3) |
| 187 | slug = factory.LazyAttribute(lambda obj: obj.name.lower().replace(' ', '-')) |
| 188 | description = factory.Faker('text') |
| 189 | price = fuzzy.FuzzyDecimal(10.00, 1000.00, 2) |
| 190 | stock = fuzzy.FuzzyInteger(0, 100) |
| 191 | is_active = True |
| 192 | category = factory.SubFactory(CategoryFactory) |
| 193 | created_by = factory.SubFactory(UserFactory) |
| 194 | |
| 195 | @factory.post_generation |
| 196 | def tags(self, create, extracted, **kwargs): |
| 197 | """Add tags to product.""" |
| 198 | if not create: |
| 199 | return |
| 200 | if extracted: |
| 201 | for tag in extracted: |
| 202 | self.tag |