Build robust Django tests with pytest-django, TDD, mocks, factories, and API coverage.
Copy the install command and let the AI configure it · recommended for beginners
Please install the "django-tdd" skill from askskill: 1. Download https://raw.githubusercontent.com/affaan-m/ECC/main/skills/django-tdd/SKILL.md 2. Save it as ~/.claude/skills/django-tdd/SKILL.md 3. Reload skills and tell me it's ready
Using pytest-django, design a TDD test plan for a Django app with an Article model. Cover creation, field validation, unique constraints, and custom methods, and use factory_boy for test data.
A clear model testing approach, sample test code, and recommended factory definitions.
Write pytest tests for a Django REST Framework user API. Cover list, detail, create, permission checks, unauthenticated failures, and error responses, and explain how to organize APIClient fixtures.
A complete API test structure, key assertions, and fixture organization guidance.
I have a Django service that calls an external payment API. Using a TDD approach, explain how to mock external dependencies with pytest, avoid real requests, and provide coverage configuration and test layering recommendations.
Mocking examples, test layering advice, and a checklist for coverage configuration and improvement.
Test-driven development for Django applications using pytest, factory_boy, and Django REST Framework.
# Step 1: RED - Write failing test
def test_user_creation():
user = User.objects.create_user(email='[email protected]', password='testpass123')
assert user.email == '[email protected]'
assert user.check_password('testpass123')
assert not user.is_staff
# Step 2: GREEN - Make test pass
# Create User model or factory
# Step 3: REFACTOR - Improve while keeping tests green
# pytest.ini
[pytest]
DJANGO_SETTINGS_MODULE = config.settings.test
testpaths = tests
python_files = test_*.py
python_classes = Test*
python_functions = test_*
addopts =
--reuse-db
--nomigrations
--cov=apps
--cov-report=html
--cov-report=term-missing
--strict-markers
markers =
slow: marks tests as slow
integration: marks tests as integration tests
# config/settings/test.py
from .base import *
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
# Disable migrations for speed
class DisableMigrations:
def __contains__(self, item):
return True
def __getitem__(self, item):
return None
MIGRATION_MODULES = DisableMigrations()
# Faster password hashing
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.MD5PasswordHasher',
]
# Email backend
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Celery always eager
CELERY_TASK_ALWAYS_EAGER = True
CELERY_TASK_EAGER_PROPAGATES = True
# tests/conftest.py
import pytest
from django.utils import timezone
from django.contrib.auth import get_user_model
User = get_user_model()
@pytest.fixture(autouse=True)
def timezone_settings(settings):
"""Ensure consistent timezone."""
settings.TIME_ZONE = 'UTC'
@pytest.fixture
def user(db):
"""Create a test user."""
return User.objects.create_user(
email='[email protected]',
password='testpass123',
username='testuser'
)
@pytest.fixture
def admin_user(db):
"""Create an admin user."""
return User.objects.create_superuser(
email='[email protected]',
password='adminpass123',
username='admin'
)
@pytest.fixture
def authenticated_client(client, user):
"""Return authenticated client."""
client.force_login(user)
return client
@pytest.fixture
def api_client():
"""Return DRF API client."""
from rest_framework.test import APIClient
return APIClient()
@pytest.fixture
def authenticated_api_client(api_client, user):
"""Return authenticated API client."""
api_client.force_authenticate(user=user)
return api_client
# tests/factories.py
import factory
from factory import fuzzy
from datetime import datetime, timedelta
from django.contrib.auth import get_user_model
from apps.products.models import Product, Category
User = get_user_model()
class UserFactory(factory.django.DjangoModelFactory):
"""Factory for User model."""
class Meta:
model = User
email = factory.Sequence(lambda n: f"user{n}@example.com")
username = factory.Sequence(lambda n: f"user{n}")
password = factory.PostGenerationMethodCall('set_password', 'testpass123')
first_name = factory.Faker('first_name')
last_name = factory.Faker('last_name')
is_active = True
class CategoryFactory(factory.django.DjangoModelFactory):
"""Factory for Category model."""
class Meta:
model = Category
name = factory.Faker('word')
…
Handle returns, refunds, fraud checks, and warranty claim decisions efficiently.
Use Bun for runtime, bundling, testing, packages, and Node migration decisions.
Use the correct Ethereum Keccak-256 hashing in Node.js and TypeScript.
Apply Nuxt 4 patterns for SSR safety, performance, and data fetching.
Generate images, videos, and audio with one unified AI media workflow.
Design Quarkus 3 backend patterns for messaging, APIs, data, and async workflows.
Build robust Python test suites with pytest, TDD, mocking, and coverage.
Practice test-driven development for Spring Boot features, fixes, and refactoring.
Learn Rust testing patterns and TDD to improve code quality and reliability.
Learn Laravel TDD and automated testing with modern practical techniques.
Use test-first development to improve code quality and maintainability.
Learn Django architecture, DRF API design, and production-ready development practices.