
Django TDD
Django testing strategies with pytest-django, TDD methodology, factory_boy, mocking...
Install
npx skills add xu-xiang/everything-claude-code-zh --skill django-tdd -g -a claude-code -y- Repository
- xu-xiang/everything-claude-code-zh2k
- Category
- Testing
- Updated
- 8mo ago
- License
- MIT
- Context cost
- Mediumabout 3,000 tokens
- Runs scripts
- No, instructions only
What it does
Django testing strategies with pytest-django, TDD methodology, factory_boy, mocking, coverage, and testing Django REST Framework APIs.
Django 测试驱动开发 (TDD)
使用 pytest、factory_boy 和 Django REST Framework 进行 Django 应用程序的测试驱动开发。
何时启用
- 编写新的 Django 应用程序时
- 实现 Django REST Framework API 时
- 测试 Django 模型(Models)、视图(Views)、序列化器(Serializers)时
- 配置 Django 项目的测试基础设施时
Django 的 TDD 工作流
红-绿-重构(Red-Green-Refactor)循环
# 步骤 1: RED - 编写一个失败的测试
def test_user_creation():
user = User.objects.create_user(email='test@example.com', password='testpass123')
assert user.email == 'test@example.com'
assert user.check_password('testpass123')
assert not user.is_staff
# 步骤 2: GREEN - 使测试通过
# 创建 User 模型或 Factory
# 步骤 3: REFACTOR - 在保持测试通过的同时进行改进
设置
pytest 配置
# 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:',
}
}
# 禁用迁移以加快速度
class DisableMigrations:
def __contains__(self, item):
return True
def __getitem__(self, item):
return None
MIGRATION_MODULES = DisableMigrations()
# 更快的密码哈希
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.MD5PasswordHasher',
]
# 邮件后端
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Celery 始终为 eager 模式
CELERY_TASK_ALWAYS_EAGER = True
CELERY_TASK_EAGER_PROPAGATES = True
conftest.py
# 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):
"""确保时区一致。"""
settings.TIME_ZONE = 'UTC'


