Appearance
Everything Claude Code 的 django-tdd Skill 为 Django 项目提供了完整的测试驱动开发(TDD)解决方案,集成 pytest-django、factory_boy、Testcontainers、mocking、覆盖率统计与 DRF API 测试等能力。它不仅极大提升了测试覆盖率和开发效率,还让 AI 编程助手能够自动生成、维护和验证高质量测试代码,成为生产级 Django 应用不可或缺的基础设施。
Everything Claude Code Django TDD Skill:pytest-django、factory_boy、Testcontainers 与 DRF API 测试
Django 作为主流 Python Web 框架,天然支持测试,但传统测试方式往往存在配置繁琐、数据准备重复、API 测试覆盖不足等痛点。Everything Claude Code 的 django-tdd Skill,结合 pytest-django、factory_boy、Testcontainers(可选)、mocking 及覆盖率工具,构建了高效、自动化、可持续演进的测试体系。无论你是初次接触 AI 编程助手,还是希望深度定制测试流程,这项 Skill 都能帮助你用最少的人力实现生产级的测试保障。
推荐阅读 Everything Claude Code 完全指南:38 Agent + 156 Skill 的生产级 AI 编程插件 了解整体架构,或参考 Claude Code 快速上手指南:Skills、Hooks、Subagents、MCP 实战配置 快速集成本 Skill。
一、django-tdd Skill 解决什么问题?
不用 Skill 时的痛点:
- 测试环境配置杂乱,难以复用和维护
- 手写测试数据冗长、易出错,难以覆盖边界场景
- API、权限、异常等关键路径测试常被遗漏
- 外部依赖(如支付、邮件、第三方 API)难以可靠 Mock
- 覆盖率低,CI/CD 无法强制质量门槛
- 新人难以理解项目测试规范,测试代码可读性弱
Skill 激活后:
- 自动生成 pytest、factory_boy、DRF API 测试骨架和常用 fixture
- 统一测试配置(数据库、邮箱、Celery、时区等),保证环境一致
- 支持一键 Mock 外部服务(如 Stripe、邮件),测试不依赖真实环境
- 强制覆盖率目标,CI/CD 质量门槛可追踪
- 所有测试用例结构清晰、可读性强,方便 AI 辅助维护和扩展
二、Skill 触发条件与常见场景
- 新建 Django 项目或模块时,AI 自动建议并生成测试配置和基础用例
- 开发新 Model、View、Serializer、API Endpoint 时,Skill 自动补全测试代码
- 需要 Mock 第三方服务、邮件或异步任务时,Skill 提供标准化 patch/fixture
- 引入新的业务流程(如支付、下单、注册)时,自动生成端到端集成测试
- CI/CD 检查覆盖率、回归测试、权限校验等质量门槛
三、完整使用流程(Step by Step)
1. 配置 pytest-django 与测试环境
在项目根目录下自动生成 pytest.ini:
ini
[pytest]
DJANGO_SETTINGS_MODULE = config.settings.test
testpaths = tests
python_files = test_*.py
addopts =
--reuse-db
--nomigrations
--cov=apps
--cov-report=html
--cov-report=term-missing
--strict-markersSkill 会自动创建 config/settings/test.py,配置内存数据库、关闭 migrations、加速密码哈希和邮件后端:
python
DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}
MIGRATION_MODULES = DisableMigrations()
PASSWORD_HASHERS = ['django.contrib.auth.hashers.MD5PasswordHasher']
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'2. 标准化测试 fixture 与工厂
Skill 自动生成 tests/conftest.py,包含常用 fixture:
python
@pytest.fixture
def user(db):
return User.objects.create_user(email='test@example.com', password='testpass123')
@pytest.fixture
def authenticated_client(client, user):
client.force_login(user)
return client
@pytest.fixture
def api_client():
from rest_framework.test import APIClient
return APIClient()
@pytest.fixture
def authenticated_api_client(api_client, user):
api_client.force_authenticate(user=user)
return api_client配合 factory_boy,Skill 生成 tests/factories.py,如:
python
class ProductFactory(factory.django.DjangoModelFactory):
class Meta:
model = Product
name = factory.Faker('sentence', nb_words=3)
price = fuzzy.FuzzyDecimal(10.00, 1000.00, 2)
stock = fuzzy.FuzzyInteger(0, 100)
category = factory.SubFactory(CategoryFactory)
created_by = factory.SubFactory(UserFactory)实际用法示例:
python
def test_product_creation():
product = ProductFactory(price=100.00, stock=50)
assert product.price == 100.00
assert product.stock == 503. 覆盖 Model、View、Serializer、API 全流程测试
Model 层测试
python
def test_product_slug_generation(db):
product = ProductFactory(name='Test Product')
assert product.slug == 'test-product'View 层测试
python
def test_product_list(client, db):
ProductFactory.create_batch(10)
response = client.get(reverse('products:list'))
assert response.status_code == 200
assert len(response.context['products']) == 10DRF Serializer 测试
python
def test_serialize_product(db):
product = ProductFactory()
serializer = ProductSerializer(product)
assert serializer.data['name'] == product.nameDRF API ViewSet 测试
python
def test_create_product_authorized(authenticated_api_client, db):
url = reverse('api:product-list')
data = {'name': 'Test Product', 'price': '99.99', 'stock': 10}
response = authenticated_api_client.post(url, data)
assert response.status_code == 201
assert response.data['name'] == 'Test Product'4. Mock 外部依赖与异步任务
Mock Stripe 支付:
python
@patch('apps.payments.services.stripe')
def test_successful_payment(mock_stripe, client, user, product):
mock_stripe.Charge.create.return_value = {'id': 'ch_123', 'status': 'succeeded'}
client.force_login(user)
response = client.post(reverse('payments:process'), {'product_id': product.id, 'token': 'tok_visa'})
assert response.status_code == 302
mock_stripe.Charge.create.assert_called_once()Mock 邮件发送:
python
@override_settings(EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend')
def test_order_confirmation_email(db, order):
order.send_confirmation_email()
assert len(mail.outbox) == 15. 集成测试与端到端流程
Skill 支持自动生成完整业务流程测试:
python
def test_guest_to_purchase_flow(client, db):
# 注册、登录、浏览商品、加购、结账、支付
...
assert Order.objects.filter(user__email='test@example.com').exists()6. 覆盖率统计与质量门槛
Skill 默认集成 coverage:
bash
pytest --cov=apps --cov-report=html --cov-report=term-missing
open htmlcov/index.html推荐覆盖率目标:
- Models/Services ≥ 90%
- Serializers ≥ 85%
- Views/APIs ≥ 80%
- Overall ≥ 80%
四、Skill 输出示例
- 自动生成的
pytest.ini、settings/test.py、conftest.py、factories.py - 针对 Model、View、Serializer、API 的标准化测试用例
- Mock Stripe、邮件等外部服务的 patch 示例
- 端到端业务流程集成测试
- 覆盖率报告(HTML/终端)
五、Skill 常见配套 Agent 与协作关系
- TDD Guide Agent:强制 80%+ 覆盖率,自动生成/补全测试用例,推动测试先行开发,详见 Everything Claude Code TDD Guide Agent
- Code Reviewer Agent:审查测试代码质量、边界用例、Mock 合理性,发现遗漏场景,详见 Code Reviewer Agent
- AI Regression Testing Skill:自动生成/回归 API 测试,检测 AI 代码生成盲点,详见 AI Regression Testing Skill
- Verification Loop Skill:集成测试、Lint、安全扫描、覆盖率检查自动化闭环,详见 Verification Loop Skill
六、最佳实践与注意事项
推荐:
- 用工厂(factory_boy)替代手写数据,提升可维护性
- 一次只测一个行为,保持测试短小聚焦
- 测试边界与权限,避免安全漏洞
- 用 fixture/patch 统一 Mock 外部依赖
- 持续追踪覆盖率,CI 阶段强制门槛
避免:
- 不要测试 Django 或第三方库内部逻辑
- 不要让测试间产生依赖,顺序可变
- 不要过度 Mock,核心业务逻辑要真实走通
- 不要用生产数据库或配置跑测试
FAQ
Q: Skill 支持哪些 Django 版本? A: 推荐 Django 3.2 及以上,兼容 pytest-django、factory_boy、DRF 3.12+,大部分配置向下兼容。
Q: 如何与 AI Agent 协同生成和维护测试? A: 启用 Skill 后,Claude Code 等 AI 助手会自动识别代码变更并补全相应测试用例,也可通过 MCP/命令显式要求生成测试。
Q: 可以集成 Testcontainers 做数据库/Redis/MQ 集成测试吗? A: Skill 支持通过扩展 fixture 集成 Testcontainers,适合需要真实服务端到端测试的场景,具体可参考官方文档和项目实践。