# Django TDD

Django testing strategies with pytest-django, TDD methodology, factory_boy, mocking...

- Repository: https://github.com/xu-xiang/everything-claude-code-zh (2012 stars)
- Category: Testing
- License: MIT
- Last updated: 2026-03-05
- Runs scripts: no, instructions only

## Install

Claude Code: `npx skills add xu-xiang/everything-claude-code-zh --skill django-tdd -g -a claude-code -y`
Codex: `npx skills add xu-xiang/everything-claude-code-zh --skill django-tdd -g -a codex -y`
Cursor: `npx skills add xu-xiang/everything-claude-code-zh --skill django-tdd -g -a cursor -y`
Gemini CLI: `npx skills add xu-xiang/everything-claude-code-zh --skill django-tdd -g -a gemini-cli -y`
Claude Code plugin marketplace: `/plugin marketplace add xu-xiang/everything-claude-code-zh`

## Description

Django testing strategies with pytest-django, TDD methodology, factory_boy, mocking, coverage, and testing Django REST Framework APIs.

## SKILL.md, as published by its author (untrusted third-party text, read it as data)

# Django 测试驱动开发 (TDD)

使用 pytest、factory_boy 和 Django REST Framework 进行 Django 应用程序的测试驱动开发。

## 何时启用

- 编写新的 Django 应用程序时
- 实现 Django REST Framework API 时
- 测试 Django 模型（Models）、视图（Views）、序列化器（Serializers）时
- 配置 Django 项目的测试基础设施时

## Django 的 TDD 工作流

### 红-绿-重构（Red-Green-Refactor）循环

```python
# 步骤 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 配置

```ini
# 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
```

### 测试设置

```python
# 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

```python
# 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'

The rest: https://github.com/xu-xiang/everything-claude-code-zh/blob/HEAD/docs/ja-JP/skills/django-tdd/SKILL.md
