Django TDD
affaan-m/ECC
Django testing strategies with pytest-django, TDD methodology, factoryboy, mocking, coverage, and testing Django REST Framework APIs.
使用 pytest-django 进行 Django 测试的策略、TDD 方法论、factoryboy、Mock 模拟、测试覆盖率以及测试 Django REST Framework API。
$ npx skills add xu-xiang/everything-claude-code-zh --skill django-tdd -a claude-codeProject install by default; add -g for ~/.claude/skills/.
$ gh skill install xu-xiang/everything-claude-code-zh django-tdd --agent claude-codeProject scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).
$ git clone --depth 1 https://github.com/xu-xiang/everything-claude-code-zh.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/django-tdd .claude/skills/django-tdd && rm -rf skills-srcUse ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.
Claude Code skills documentation · loads skills from .claude/skills/
Install the "django-tdd" agent skill from https://github.com/xu-xiang/everything-claude-code-zh/tree/main/skills/django-tdd into .claude/skills/django-tdd/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "django-tdd", then confirm the skill loads.Claude Code copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$skill-installer install https://github.com/xu-xiang/everything-claude-code-zh/tree/main/skills/django-tddType this inside Codex. $skill-installer <name> installs a curated skill from openai/skills. The installer writes to $CODEX_HOME/skills (default ~/.codex/skills). Restart Codex if the skill does not show up.
$ npx skills add xu-xiang/everything-claude-code-zh --skill django-tdd -a codexProject install goes to .agents/skills/; add -g for ~/.codex/skills/.
$ gh skill install xu-xiang/everything-claude-code-zh django-tdd --agent codexProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/xu-xiang/everything-claude-code-zh.git skills-src && mkdir -p .agents/skills && cp -r skills-src/skills/django-tdd .agents/skills/django-tdd && rm -rf skills-srcUse ~/.agents/skills/ instead of .agents/skills for a personal install.
Codex skills documentation · loads skills from .agents/skills/
Install the "django-tdd" agent skill from https://github.com/xu-xiang/everything-claude-code-zh/tree/main/skills/django-tdd into .agents/skills/django-tdd/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "django-tdd", then confirm the skill loads.Codex copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add xu-xiang/everything-claude-code-zh --skill django-tdd -a cursorProject install goes to .agents/skills/; add -g for ~/.cursor/skills/.
$ gh skill install xu-xiang/everything-claude-code-zh django-tdd --agent cursorProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/xu-xiang/everything-claude-code-zh.git skills-src && mkdir -p .cursor/skills && cp -r skills-src/skills/django-tdd .cursor/skills/django-tdd && rm -rf skills-srcUse ~/.cursor/skills/ instead of .cursor/skills for a personal install.
Cursor skills documentation · loads skills from .cursor/skills/, .agents/skills/, .claude/skills/, .codex/skills/
Install the "django-tdd" agent skill from https://github.com/xu-xiang/everything-claude-code-zh/tree/main/skills/django-tdd into .cursor/skills/django-tdd/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "django-tdd", then confirm the skill loads.Cursor copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gemini skills install https://github.com/xu-xiang/everything-claude-code-zh.git --path skills/django-tdd--scope user (default) or --scope workspace; --path is the subfolder of the repo that holds the skill; --consent skips the security confirmation prompt.
$ npx skills add xu-xiang/everything-claude-code-zh --skill django-tdd -a gemini-cliProject install goes to .agents/skills/; add -g for ~/.gemini/skills/.
$ gh skill install xu-xiang/everything-claude-code-zh django-tdd --agent gemini-cliProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/xu-xiang/everything-claude-code-zh.git skills-src && mkdir -p .gemini/skills && cp -r skills-src/skills/django-tdd .gemini/skills/django-tdd && rm -rf skills-srcUse ~/.gemini/skills/ instead of .gemini/skills for a personal install, then run /skills reload.
Gemini CLI skills documentation · loads skills from .gemini/skills/, .agents/skills/
Install the "django-tdd" agent skill from https://github.com/xu-xiang/everything-claude-code-zh/tree/main/skills/django-tdd into .gemini/skills/django-tdd/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "django-tdd", then confirm the skill loads.Gemini CLI copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gh skill install xu-xiang/everything-claude-code-zh django-tddInstalls for Copilot at project scope by default; add --scope user for a personal install. Preview a skill first with gh skill preview. Needs GitHub CLI 2.90.0 or later (public preview).
$ npx skills add xu-xiang/everything-claude-code-zh --skill django-tdd -a github-copilotProject install goes to .agents/skills/; add -g for ~/.copilot/skills/.
$ git clone --depth 1 https://github.com/xu-xiang/everything-claude-code-zh.git skills-src && mkdir -p .github/skills && cp -r skills-src/skills/django-tdd .github/skills/django-tdd && rm -rf skills-srcUse ~/.copilot/skills/ instead of .github/skills for a personal install. Commit .github/skills so cloud agent and code review can use it.
GitHub Copilot skills documentation · loads skills from .github/skills/, .claude/skills/, .agents/skills/
Install the "django-tdd" agent skill from https://github.com/xu-xiang/everything-claude-code-zh/tree/main/skills/django-tdd into .github/skills/django-tdd/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "django-tdd", then confirm the skill loads.GitHub Copilot copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add xu-xiang/everything-claude-code-zh --skill django-tdd -a opencodeOpenCode documents no install command of its own. Project install goes to .agents/skills/; add -g for ~/.config/opencode/skills/.
$ gh skill install xu-xiang/everything-claude-code-zh django-tdd --agent opencodeProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/xu-xiang/everything-claude-code-zh.git skills-src && mkdir -p .opencode/skills && cp -r skills-src/skills/django-tdd .opencode/skills/django-tdd && rm -rf skills-srcUse ~/.config/opencode/skills/ instead of .opencode/skills for a personal install.
OpenCode skills documentation · loads skills from .opencode/skills/, .claude/skills/, .agents/skills/
Install the "django-tdd" agent skill from https://github.com/xu-xiang/everything-claude-code-zh/tree/main/skills/django-tdd into .opencode/skills/django-tdd/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "django-tdd", then confirm the skill loads.OpenCode copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
django-tdd使用 pytest-django 进行 Django 测试的策略、TDD 方法论、factoryboy、Mock 模拟、测试覆盖率以及测试 Django REST Framework API。
Django TDD is an agent skill from xu-xiang/everything-claude-code-zh. 使用 pytest-django 进行 Django 测试的策略、TDD 方法论、factoryboy、Mock 模拟、测试覆盖率以及测试 Django REST Framework API。
Its SKILL.md is about 4.7k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.
It sits in Testing & QA, covering Backend development, Test-driven development and Unit testing. It works with Django and pytest. The repository describes itself as: everything-claude-code 中文翻译项目:完整的 Claude Code 配置集合(agents, skills, hooks, commands, rules, MCPs)。源自 Anthropic 黑客松获胜者的实战配置,助力中文工程师高效理解与使用 Claude Code。 The licence is MIT.
Read from SKILL.md and the folder at commit dfbf946. It shows what the files ask for, not the result of running them.
Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.
From allowed-tools in the SKILL.md frontmatter.
Shell commands in SKILL.md call:
pytestFrom the folder's file list and the shell code blocks in SKILL.md.
No URLs in SKILL.md.
From URLs in SKILL.md, links to its own repository left out.
Names no API keys, tokens, secrets or passwords.
From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.
Django TDD loads about 4.7k tokens when it runs. Until then it costs about 27 tokens; SKILL.md has 156 words of instructions outside code blocks.
Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.
The automated check found no risky patterns in SKILL.md.
Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.
The full file from xu-xiang/everything-claude-code-zh at commit dfbf946, republished under its MIT licence (© xu-xiang). 156 words, ~4,731 tokens.
.claude/skills/django-tdd/SKILL.md (or your agent's skills folder).使用 pytest、factory_boy 和 Django REST Framework 对 Django 应用程序进行测试驱动开发(TDD)。
# 步骤 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 模型或工厂
# 步骤 3: 重构(REFACTOR) - 在保持测试通过的同时改进代码# 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: 标记为慢速测试
integration: 标记为集成测试# 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 设置为同步执行
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):
"""确保时区一致。"""
settings.TIME_ZONE = 'UTC'
@pytest.fixture
def user(db):
"""创建一个测试用户。"""
return User.objects.create_user(
email='test@example.com',
password='testpass123',
username='testuser'
)
@pytest.fixture
def admin_user(db):
"""创建一个管理员用户。"""
return User.objects.create_superuser(
email='admin@example.com',
password='adminpass123',
username='admin'
)
@pytest.fixture
def authenticated_client(client, user):
"""返回已认证的客户端。"""
client.force_login(user)
return client
@pytest.fixture
def api_client():
"""返回 DRF API 客户端。"""
from rest_framework.test import APIClient
return APIClient()
@pytest.fixture
def authenticated_api_client(api_client, user):
"""返回已认证的 API 客户端。"""
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):
"""User 模型的工厂类。"""
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):
"""Category 模型的工厂类。"""
class Meta:
model = Category
name = factory.Faker('word')
slug = factory.LazyAttribute(lambda obj: obj.name.lower())
description = factory.Faker('text')
class ProductFactory(factory.django.DjangoModelFactory):
"""Product 模型的工厂类。"""
class Meta:
model = Product
name = factory.Faker('sentence', nb_words=3)
slug = factory.LazyAttribute(lambda obj: obj.name.lower().replace(' ', '-'))
description = factory.Faker('text')
price = fuzzy.FuzzyDecimal(10.00, 1000.00, 2)
stock = fuzzy.FuzzyInteger(0, 100)
is_active = True
category = factory.SubFactory(CategoryFactory)
created_by = factory.SubFactory(UserFactory)
@factory.post_generation
def tags(self, create, extracted, **kwargs):
"""为产品添加标签。"""
if not create:
return
if extracted:
for tag in extracted:
self.tags.add(tag)# tests/test_models.py
import pytest
from tests.factories import ProductFactory, UserFactory
def test_product_creation():
"""测试使用工厂创建产品。"""
product = ProductFactory(price=100.00, stock=50)
assert product.price == 100.00
assert product.stock == 50
assert product.is_active is True
def test_product_with_tags():
"""测试带有标签的产品。"""
tags = [TagFactory(name='electronics'), TagFactory(name='new')]
product = ProductFactory(tags=tags)
assert product.tags.count() == 2
def test_multiple_products():
"""测试创建多个产品。"""
products = ProductFactory.create_batch(10)
assert len(products) == 10# tests/test_models.py
import pytest
from django.core.exceptions import ValidationError
from tests.factories import UserFactory, ProductFactory
class TestUserModel:
"""测试 User 模型。"""
def test_create_user(self, db):
"""测试创建普通用户。"""
user = UserFactory(email='test@example.com')
assert user.email == 'test@example.com'
assert user.check_password('testpass123')
assert not user.is_staff
assert not user.is_superuser
def test_create_superuser(self, db):
"""测试创建超级用户。"""
user = UserFactory(
email='admin@example.com',
is_staff=True,
is_superuser=True
)
assert user.is_staff
assert user.is_superuser
def test_user_str(self, db):
"""测试用户的字符串表示。"""
user = UserFactory(email='test@example.com')
assert str(user) == 'test@example.com'
class TestProductModel:
"""测试 Product 模型。"""
def test_product_creation(self, db):
"""测试创建产品。"""
product = ProductFactory()
assert product.id is not None
assert product.is_active is True
assert product.created_at is not None
def test_product_slug_generation(self, db):
"""测试自动生成 slug。"""
product = ProductFactory(name='Test Product')
assert product.slug == 'test-product'
def test_product_price_validation(self, db):
"""测试价格不能为负数。"""
product = ProductFactory(price=-10)
with pytest.raises(ValidationError):
product.full_clean()
def test_product_manager_active(self, db):
"""测试 active 管理器方法。"""
ProductFactory.create_batch(5, is_active=True)
ProductFactory.create_batch(3, is_active=False)
active_count = Product.objects.active().count()
assert active_count == 5
def test_product_stock_management(self, db):
"""测试库存管理。"""
product = ProductFactory(stock=10)
product.reduce_stock(5)
product.refresh_from_db()
assert product.stock == 5
with pytest.raises(ValueError):
product.reduce_stock(10) # 库存不足# tests/test_views.py
import pytest
from django.urls import reverse
from tests.factories import ProductFactory, UserFactory
class TestProductViews:
"""测试产品视图。"""
def test_product_list(self, client, db):
"""测试产品列表视图。"""
ProductFactory.create_batch(10)
response = client.get(reverse('products:list'))
assert response.status_code == 200
assert len(response.context['products']) == 10
def test_product_detail(self, client, db):
"""测试产品详情视图。"""
product = ProductFactory()
response = client.get(reverse('products:detail', kwargs={'slug': product.slug}))
assert response.status_code == 200
assert response.context['product'] == product
def test_product_create_requires_login(self, client, db):
"""测试创建产品需要身份认证。"""
response = client.get(reverse('products:create'))
assert response.status_code == 302
assert response.url.startswith('/accounts/login/')
def test_product_create_authenticated(self, authenticated_client, db):
"""测试已认证用户创建产品。"""
response = authenticated_client.get(reverse('products:create'))
assert response.status_code == 200
def test_product_create_post(self, authenticated_client, db, category):
"""测试通过 POST 创建产品。"""
data = {
'name': 'Test Product',
'description': 'A test product',
'price': '99.99',
'stock': 10,
'category': category.id,
}
response = authenticated_client.post(reverse('products:create'), data)
assert response.status_code == 302
assert Product.objects.filter(name='Test Product').exists()# tests/test_serializers.py
import pytest
from rest_framework.exceptions import ValidationError
from apps.products.serializers import ProductSerializer
from tests.factories import ProductFactory
class TestProductSerializer:
"""测试 ProductSerializer。"""
def test_serialize_product(self, db):
"""测试序列化产品。"""
product = ProductFactory()
serializer = ProductSerializer(product)
data = serializer.data
assert data['id'] == product.id
assert data['name'] == product.name
assert data['price'] == str(product.price)
def test_deserialize_product(self, db):
"""测试反序列化产品数据。"""
data = {
'name': 'Test Product',
'description': 'Test description',
'price': '99.99',
'stock': 10,
'category': 1,
}
serializer = ProductSerializer(data=data)
assert serializer.is_valid()
product = serializer.save()
assert product.name == 'Test Product'
assert float(product.price) == 99.99
def test_price_validation(self, db):
"""测试价格验证。"""
data = {
'name': 'Test Product',
'price': '-10.00',
'stock': 10,
}
serializer = ProductSerializer(data=data)
assert not serializer.is_valid()
assert 'price' in serializer.errors
def test_stock_validation(self, db):
"""测试库存不能为负数。"""
data = {
'name': 'Test Product',
'price': '99.99',
'stock': -5,
}
serializer = ProductSerializer(data=data)
assert not serializer.is_valid()
assert 'stock' in serializer.errors# tests/test_api.py
import pytest
from rest_framework.test import APIClient
from rest_framework import status
from django.urls import reverse
from tests.factories import ProductFactory, UserFactory
class TestProductAPI:
"""测试产品 API 端点。"""
@pytest.fixture
def api_client(self):
"""返回 API 客户端。"""
return APIClient()
def test_list_products(self, api_client, db):
"""测试列出产品。"""
ProductFactory.create_batch(10)
url = reverse('api:product-list')
response = api_client.get(url)
assert response.status_code == status.HTTP_200_OK
assert response.data['count'] == 10
def test_retrieve_product(self, api_client, db):
"""测试获取单个产品。"""
product = ProductFactory()
url = reverse('api:product-detail', kwargs={'pk': product.id})
response = api_client.get(url)
assert response.status_code == status.HTTP_200_OK
assert response.data['id'] == product.id
def test_create_product_unauthorized(self, api_client, db):
"""测试未授权创建产品。"""
url = reverse('api:product-list')
data = {'name': 'Test Product', 'price': '99.99'}
response = api_client.post(url, data)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
def test_create_product_authorized(self, authenticated_api_client, db):
"""测试已认证用户创建产品。"""
url = reverse('api:product-list')
data = {
'name': 'Test Product',
'description': 'Test',
'price': '99.99',
'stock': 10,
}
response = authenticated_api_client.post(url, data)
assert response.status_code == status.HTTP_201_CREATED
assert response.data['name'] == 'Test Product'
def test_update_product(self, authenticated_api_client, db):
"""测试更新产品。"""
product = ProductFactory(created_by=authenticated_api_client.user)
url = reverse('api:product-detail', kwargs={'pk': product.id})
data = {'name': 'Updated Product'}
response = authenticated_api_client.patch(url, data)
assert response.status_code == status.HTTP_200_OK
assert response.data['name'] == 'Updated Product'
def test_delete_product(self, authenticated_api_client, db):
"""测试删除产品。"""
product = ProductFactory(created_by=authenticated_api_client.user)
url = reverse('api:product-detail', kwargs={'pk': product.id})
response = authenticated_api_client.delete(url)
assert response.status_code == status.HTTP_204_NO_CONTENT
def test_filter_products_by_price(self, api_client, db):
"""测试按价格过滤产品。"""
ProductFactory(price=50)
ProductFactory(price=150)
url = reverse('api:product-list')
response = api_client.get(url, {'price_min': 100})
assert response.status_code == status.HTTP_200_OK
assert response.data['count'] == 1
def test_search_products(self, api_client, db):
"""测试搜索产品。"""
ProductFactory(name='Apple iPhone')
ProductFactory(name='Samsung Galaxy')
url = reverse('api:product-list')
response = api_client.get(url, {'search': 'Apple'})
assert response.status_code == status.HTTP_200_OK
assert response.data['count'] == 1# tests/test_views.py
from unittest.mock import patch, Mock
import pytest
class TestPaymentView:
"""测试使用了 Mock 模拟支付网关的支付视图。"""
@patch('apps.payments.services.stripe')
def test_successful_payment(self, mock_stripe, client, user, product):
"""测试使用 Mock Stripe 的成功支付流程。"""
# 配置 Mock
mock_stripe.Charge.create.return_value = {
'id': 'ch_123',
'status': 'succeeded',
'amount': 9999,
}
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()
@patch('apps.payments.services.stripe')
def test_failed_payment(self, mock_stripe, client, user, product):
"""测试支付失败。"""
mock_stripe.Charge.create.side_effect = Exception('Card declined')
client.force_login(user)
response = client.post(reverse('payments:process'), {
'product_id': product.id,
'token': 'tok_visa',
})
assert response.status_code == 302
assert 'error' in response.url# tests/test_email.py
from django.core import mail
from django.test import override_settings
@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) == 1
assert order.user.email in mail.outbox[0].to
assert 'Order Confirmation' in mail.outbox[0].subject# tests/test_integration.py
import pytest
from django.urls import reverse
from tests.factories import UserFactory, ProductFactory
class TestCheckoutFlow:
"""测试完整的结账流程。"""
def test_guest_to_purchase_flow(self, client, db):
"""测试从游客到购买的完整流程。"""
# 步骤 1: 注册
response = client.post(reverse('users:register'), {
'email': 'test@example.com',
'password': 'testpass123',
'password_confirm': 'testpass123',
})
assert response.status_code == 302
# 步骤 2: 登录
response = client.post(reverse('users:login'), {
'email': 'test@example.com',
'password': 'testpass123',
})
assert response.status_code == 302
# 步骤 3: 浏览产品
product = ProductFactory(price=100)
response = client.get(reverse('products:detail', kwargs={'slug': product.slug}))
assert response.status_code == 200
# 步骤 4: 添加到购物车
response = client.post(reverse('cart:add'), {
'product_id': product.id,
'quantity': 1,
})
assert response.status_code == 302
# 步骤 5: 结账
response = client.get(reverse('checkout:review'))
assert response.status_code == 200
assert product.name in response.content.decode()
# 步骤 6: 完成购买
with patch('apps.checkout.services.process_payment') as mock_payment:
mock_payment.return_value = True
response = client.post(reverse('checkout:complete'))
assert response.status_code == 302
assert Order.objects.filter(user__email='test@example.com').exists()test_user_cannot_delete_others_post--reuse-db 和 --nomigrations# 运行带有覆盖率报告的测试
pytest --cov=apps --cov-report=html --cov-report=term-missing
# 生成 HTML 报告
open htmlcov/index.html| 组件 | 目标覆盖率 |
|---|---|
| 模型 (Models) | 90%+ |
| 序列化器 (Serializers) | 85%+ |
| 视图 (Views) | 80%+ |
| 服务 (Services) | 90%+ |
| 工具类 (Utilities) | 80%+ |
| 整体 | 80%+ |
| 模式 | 用法 |
|---|---|
@pytest.mark.django_db | 启用数据库访问 |
client | Django 测试客户端 |
api_client | DRF API 客户端 |
factory.create_batch(n) | 创建多个对象 |
patch('module.function') | 模拟外部依赖 |
override_settings | 临时更改设置 |
force_authenticate() | 在测试中绕过身份认证 |
assertRedirects | 检查重定向 |
assertTemplateUsed | 验证模板使用情况 |
mail.outbox | 检查已发送的邮件 |
记住:测试即文档。良好的测试能够解释代码应该如何工作。保持测试简单、易读且易于维护。
© xu-xiang, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file
Just SKILL.md in skills/django-tdd of xu-xiang/everything-claude-code-zh.
Open the folder on GitHubat commit dfbf946
Django TDD next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.
| Skill | Stars | Used in | Tokens | Auto-check | Licence | Repo updated |
|---|---|---|---|---|---|---|
| Django TDD this skillxu-xiang/everything-claude-code-zh | 2k | — | ~4.7k | Automated safety check: Pass | MIT | |
| Django TDDaffaan-m/ECC | 277k | 7 repos | ~5.3k | Automated safety check: Pass | MIT | |
| Django TDDaffaan-m/ECC | 277k | 3 repos | ~4.9k | Automated safety check: Pass | MIT | |
| Dj Pytestdvf/opinionated-django | 109 | — | ~4.3k | Automated safety check: Notes | MIT | |
| Write Backend Unit Testbaserow/baserow | 6.1k | — | ~1.8k | Automated safety check: Pass | Custom licence | |
| Pytestmathiasertl/django-ca | 158 | — | ~924 | Automated safety check: Pass | GPL-3.0 |
affaan-m/ECC
Django testing strategies with pytest-django, TDD methodology, factoryboy, mocking, coverage, and testing Django REST Framework APIs.
affaan-m/ECC
Django 测试策略,包括 pytest-django、TDD 方法、factoryboy、模拟、覆盖率以及测试 Django REST Framework API。
dvf/opinionated-django
Set up and write pytest tests for an op-django project — pytest-django configuration, two-sided Celery testing (patched dispatch sites + plain-function task bodies, never eager mode), freezegun for…
baserow/baserow
Write or update Baserow backend tests for core, premium, or enterprise code using pytest, Django, DRF APIClient, and the repo's shared fixture patterns.
mathiasertl/django-ca
Instructions for running, writing, and maintaining tests in this project
aropan/clist
Choose and run focused checks after changing CLIST Python code: Django tests, standalone pytest tests, offline parser fixtures, Ruff, or a relevant management-command check.
xu-xiang/everything-claude-code-zh
Everything Claude Code 的交互式安装程序 — 引导用户选择并安装技能和规则到用户级或项目级目录,验证路径,并可选择优化已安装文件。
xu-xiang/everything-claude-code-zh
基于本能(Instinct)的学习系统,通过钩子(hooks)观察会话,创建带有置信度评分的原子本能,并将其演化为技能(Skills)、命令(Commands)或智能体(Agents)。v2.1 版本增加了项目作用域(project-scoped)的本能,以防止跨项目污染。
xu-xiang/everything-claude-code-zh
生产级 API 的 REST API 设计模式,包括资源命名、状态码、分页、过滤、错误响应、版本控制和速率限制. An agent skill from xu-xiang/everything-claude-code-zh.
xu-xiang/everything-claude-code-zh
后端架构模式、API 设计、数据库优化以及适用于 Node.js、Express 和 Next.js API 路由的服务端最佳实践。
xu-xiang/everything-claude-code-zh
后端架构模式、API 设计、数据库优化以及 Node.js、Express 和 Next.js API 路由的服务端最佳实践。
xu-xiang/everything-claude-code-zh
后端架构模式、API 设计、数据库优化以及针对 Node.js、Express 和 Next.js API 路由的服务端最佳实践。
Categories
使用 pytest-django 进行 Django 测试的策略、TDD 方法论、factoryboy、Mock 模拟、测试覆盖率以及测试 Django REST Framework API。. Django TDD is an agent skill from xu-xiang/everything-claude-code-zh.
Django TDD fits situations like: tasks that involve Backend development; tasks that involve Test-driven development; tasks that involve Unit testing.
Run `npx skills add xu-xiang/everything-claude-code-zh --skill django-tdd -a claude-code`. Or copy the skill folder (skills/django-tdd in xu-xiang/everything-claude-code-zh) into .claude/skills/django-tdd in your project. Claude Code loads it when a task matches its description.
Run `npx skills add xu-xiang/everything-claude-code-zh --skill django-tdd -a codex`. Or copy the skill folder (skills/django-tdd in xu-xiang/everything-claude-code-zh) into .agents/skills/django-tdd in your project. Codex loads it when a task matches its description.
Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add xu-xiang/everything-claude-code-zh --skill django-tdd -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/django-tdd, .gemini/skills/django-tdd, .github/skills/django-tdd and .opencode/skills/django-tdd in your project.
Going by SKILL.md and its folder, Django TDD needs the command-line tools its instructions call (pytest). Our summary lists: Python 3.
SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.
Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.
Django TDD is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.
About 4.7k tokens (SKILL.md is roughly 19k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.
Skills that share tags, products or a category with Django TDD: Django TDD (affaan-m/ECC, 277k stars), Django TDD (affaan-m/ECC, 277k stars), Dj Pytest (dvf/opinionated-django, 109 stars) and Write Backend Unit Test (baserow/baserow, 6.1k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.
xu-xiang (a GitHub user) maintains it in xu-xiang/everything-claude-code-zh, which has 1,978 GitHub stars. The repository holds 78 skills in this directory. The repository was last updated on March 5, 2026.
Source: xu-xiang/everything-claude-code-zh on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.