Django 代码测试
- 作者仓库星标 0
- 作者仓库 skills-registry
Django Testing with TDD
Contents
When to Use
- Writing new Django applications
- Implementing Django REST Framework APIs
- Testing Django models, views, and serializers
- Setting up testing infrastructure for Django projects
TDD Workflow
Red-Green-Refactor Cycle
RED → Write failing test first
GREEN → Write minimal code to pass
REFACTOR → Improve while keeping tests green
REPEAT → Continue with next requirement
Example
# Step 1: RED - Write failing test
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')
# Step 2: GREEN - Make test pass (implement User model)
# Step 3: REFACTOR - Improve while keeping tests green
Testing Best Practices
DO
- Use factories — Instead of manual object creation
- One assertion per test — Keep tests focused
- Descriptive test names —
test_user_cannot_delete_others_post - Test edge cases — Empty inputs, None values, boundary conditions
- Mock external services — Don't depend on external APIs
- Use fixtures — Eliminate duplication
- Test permissions — Ensure authorization works
- Keep tests fast — Use
--reuse-dband--nomigrations
DON'T
- Don't test Django internals — Trust Django to work
- Don't test third-party code — Trust libraries to work
- Don't ignore failing tests — All tests must pass
- Don't make tests dependent — Tests should run in any order
- Don't over-mock — Mock only external dependencies
- Don't test private methods — Test public interface
- Don't use production database — Always use test database
Coverage
Running Coverage
# Run tests with coverage
pytest --cov=apps --cov-report=html --cov-report=term-missing
# Generate HTML report
open htmlcov/index.html
Coverage Targets
| Component | Target |
|---|---|
| Models | 90%+ |
| Serializers | 85%+ |
| Views | 80%+ |
| Services | 90%+ |
| Utilities | 80%+ |
| Overall | 80%+ |
Quick Reference
| Pattern | Usage |
|---|---|
@pytest.mark.django_db |
Enable database access |
client |
Django test client |
api_client |
DRF API client |
factory.create_batch(n) |
Create multiple objects |
patch('module.function') |
Mock external dependencies |
override_settings |
Temporarily change settings |
force_authenticate() |
Bypass authentication |
mail.outbox |
Check sent emails |
Common Test Patterns
# Test with factory
def test_product_creation():
product = ProductFactory(price=100.00)
assert product.price == 100.00
def test_product_validation():
product = ProductFactory.build(price=-1)
with pytest.raises(ValidationError):
product.full_clean()
def test_payment(mock_stripe, client, user):
mock_stripe.Charge.create.return_value = {'status': 'succeeded'}
# ... test payment flow
References
- Setup — pytest config, test settings, conftest
- Factory Examples — Factory Boy patterns
- Test Examples — Model, view, serializer, API tests
- Mocking & Integration — Mocking patterns and integration tests
<!-- tomevault:4.0:skill_md:2026-05-22 -->Source: basidiocarp/lamella — distributed by TomeVault.
- 流狐分类
- AI 智能
- 作者声明 Agent
- 未找到明确声明;不据此推断已兼容或已测试
- 静态检查
- 88 / 100 · 启发式扫描,不代表运行安全
- 作者 / 版本 / 许可
- @tomevault-io · 未声明 license
- 流狐 Token 估算
- 低消耗
- 流狐接入估算
- 即装即用
- 是否需要外部 API Key
- 未发现要求
- 检测到的系统要求
- 未声明
- 底层运行要求
- Python
- 检测到的文件与系统行为
-
- 只读
- 允许写入 / 修改
- 检测到的网络行为
- 仅限本地
- 安装命令数
- 无(仅作为资料)
档案由构建时根据 SKILL.md 与安装命令自动衍生,可能与作者实际意图存在差异。
需要注意: 未限定 allowed-tools,默认拥有全部工具权限。
作者没有在当前 SKILL.md 中定义固定输出样例。 Contents
When to Use TDD Workflow Testing Best Practices
When to Use
Writing new Django applications Implementing Django REST Framework APIs Testing Django models, views, and serializers
TDD Workflow
TDD Workflow
Red-Green-Refactor Cycle
Red-Green-Refactor Cycle
Example
Example
Testing Best Practices
Testing Best Practices
# Django Testing with TDD
## Contents
- [When to Use](#when-to-use)
- [TDD Workflow](#tdd-workflow)
- [Testing Best Practices](#testing-best-practices)
- [Coverage](#coverage)
- [Quick Reference](#quick-reference)
- [References](#references)
## When to Use
- Writing new Django applications
- Implementing Django REST Framework APIs
- Testing Django models, views, and serializers
- Setting up testing infrastructure for Django projects
## TDD Workflow
### Red-Green-Refactor Cycle
```
RED → Write failing test first
GREEN → Write minimal code to pass
REFACTOR → Improve while keeping tests green
REPEAT → Continue with next requirement
```
### Example
```python
# Step 1: RED - Write failing test
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')
# Step 2: GREEN - Make test pass (implement User model)
# Step 3: REFACTOR - Improve while keeping tests green
```
## Testing Best Practices
### DO
- **Use factories** — Instead of manual object creation
- **One assertion per test** — Keep tests focused
- **Descriptive test names** — `test_user_cannot_delete_others_post`
- **Test edge cases** — Empty inputs, None values, boundary conditions
- **Mock external services** — Don't depend on external APIs
- **Use fixtures** — Eliminate duplication
- **Test permissions** — Ensure authorization works
- **Keep tests fast** — Use `--reuse-db` and `--nomigrations`
### DON'T
- **Don't test Django internals** — Trust Django to work
- **Don't test third-party code** — Trust libraries to work
- **Don't ignore failing tests** — All tests must pass
- **Don't make tests dependent** — Tests should run in any order
… 证据边界与执行链路
作者原文负责流程事实;流狐只索引当前章节、要点、文件与命令。
章节 -> Contents → When to Use → TDD Workflow → Red-Green-Refactor Cycle → Example → Testing Best Practices
要点 -> Use factories · One assertion per test · Descriptive test names · Test edge cases · Mock external services · Use fixtures · Test permissions · Keep tests fast
文件/命令 -> testusercannotdeleteotherspost · --reuse-db · --nomigrations · @pytest.mark.djangodb · client · apiclient · factory.createbatch(n) · patch('module.function')
内容 SHA-256 -> a5ce84485899
方法与流程
适用与边界
原文中的明确线索
testusercannotdeleteotherspost、--reuse-db、--nomigrations、@pytest.mark.djangodb、client、apiclient、factory.createbatch(n)、patch('module.function')