代码测试
- 作者仓库星标 0
- 作者仓库 skills-registry
- 领域
- 人工智能
- 作者声明的智能体
- 未找到明确声明;不据此推断已兼容或已测试
- 静态检查
- 88 / 100 · 启发式扫描,不代表运行安全
- 运行环境证据
- 未执行;当前没有隔离运行测试证据
- 作者 / 版本 / 许可证
- @tomevault-io · 未声明许可证
- 上下文用量评级
- 低消耗
- 接入复杂程度
- 即装即用
- 是否需要外部接口密钥
- 不需要
- 兼容的系统
- 未声明(默认跨平台)
- 运行环境要求
- 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
# 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
- **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
```bash
# 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
```python
# 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](references/setup.md) — pytest config, test settings, conftest
- [Factory Examples](references/factory-examples.md) — Factory Boy patterns
- [Test Examples](references/test-examples.md) — Model, view, serializer, API tests
- [Mocking & Integration](references/mocking-integration.md) — Mocking patterns and integration tests
---
> Source: [basidiocarp/lamella](https://github.com/basidiocarp/lamella) — distributed by [TomeVault](https://tomevault.io).
<!-- tomevault:4.0:skill_md:2026-05-22 -->
章节与文件索引
按说明文件中的顺序排列。
内容
何时使用
溶解氧
不要
覆盖目标
文件/命令 -> test_user_cannot_delete_others_post · --reuse-db · --nomigrations · @pytest.mark.django_db · client · api_client · factory.create_batch(n) · patch('module.function')
内容校验值 -> a5ce84485899
当前原文的自动摘译,尚未人工审校。
内容
何时使用 TDD 工作流程测试最佳实践覆盖范围快速参考
何时使用
编写新的 Django 应用程序 实现 Django REST Framework API 测试 Django 模型、视图和序列化器 为 Django 项目设置测试基础设施
溶解氧
使用工厂 — 而不是手动创建对象 每个测试一个断言 — 保持测试重点 描述性测试名称 —
test_user_cannot_delete_others_post测试边缘情况 — 空输入、无值、边界条件 模拟外部服务 — 不依赖外部 API不要
不要测试 Django 内部 - 信任 Django 可以工作 不要测试第三方代码 - 信任库可以工作 不要忽略失败的测试 - 所有测试都必须通过 不要使测试依赖 - 测试应该以任何顺序运行 不要过度模拟 - 仅模拟外部依赖
覆盖目标
组件 · 目标模型 · 90%+ 序列化程序 · 85%+ 视图 · 80%+ 服务 · 90%+