tdd
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTest-Driven Development Skill
测试驱动开发技能
Overview
概述
Guides Test-Driven Development workflow: Red-Green-Refactor cycle for new features, bug fixes, legacy code, and test refactoring.
指导测试驱动开发工作流:针对新功能、Bug修复、遗留代码和测试重构的红-绿-重构循环。
Development Scenarios
开发场景
1. New Feature Development
1. 新功能开发
Follow the Red-Green-Refactor cycle:
遵循红-绿-重构循环:
🔴 RED - Write a Failing Test
🔴 红阶段 - 编写失败的测试
- Write the smallest test defining desired behavior
- Run test to confirm failure
bash
uv run pytest tests/feature/test_new_function.py -v- 编写定义期望行为的最小测试用例
- 运行测试确认失败
bash
uv run pytest tests/feature/test_new_function.py -v🟢 GREEN - Make the Test Pass
🟢 绿阶段 - 让测试通过
- Write minimal production code to pass
- Run test to confirm passes
- Iterate until all tests pass
bash
uv run pytest tests/feature/test_new_function.py::test_new_function -v
uv run pytest- 编写最少的生产代码使测试通过
- 运行测试确认通过
- 迭代直到所有测试通过
bash
uv run pytest tests/feature/test_new_function.py::test_new_function -v
uv run pytest🔵 REFACTOR - Improve the Code
🔵 重构阶段 - 优化代码
- Clean up test and production code
- Ensure tests still pass
- List refactoring opportunities (see Test Refactoring Opportunities)
bash
uv run pytest --cov=src --cov-report=term-missing- 清理测试代码和生产代码
- 确保测试仍能通过
- 列出重构优化点(参见测试重构优化点)
bash
uv run pytest --cov=src --cov-report=term-missing2. Bug Fixes
2. Bug修复
Never fix a bug without writing a test first.
- Write test reproducing bug, verify fails
- Fix bug in implementation
- Run tests until green
- Check refactoring opportunities
python
def test_calculate_total_with_negative_price_raises_error():
items = [Item("Coke", -1.50)]
with pytest.raises(ValueError, match="Price cannot be negative"):
calculate_total(items)修复Bug前务必先编写测试。
- 编写复现Bug的测试用例,验证测试失败
- 在实现代码中修复Bug
- 运行测试直到全部通过
- 检查重构优化点
python
def test_calculate_total_with_negative_price_raises_error():
items = [Item("Coke", -1.50)]
with pytest.raises(ValueError, match="Price cannot be negative"):
calculate_total(items)3. Legacy Code
3. 遗留代码
- Write characterization tests capturing current behavior
- Run tests to establish baseline
- Make small changes with test coverage
- Refactor incrementally
bash
uv run pytest tests/legacy/test_old_module.py -v
uv run pytest --cov=src/legacy_module --cov-report=term-missing- 编写特征化测试捕获当前代码行为
- 运行测试建立基准
- 在测试覆盖下进行小幅度修改
- 逐步重构
bash
uv run pytest tests/legacy/test_old_module.py -v
uv run pytest --cov=src/legacy_module --cov-report=term-missingTest Refactoring Opportunities
测试重构优化点
After each TDD cycle (or when reviewing existing tests), search for these improvement opportunities:
在每个TDD循环结束后(或评审现有测试时),寻找以下改进机会:
Identify Opportunities
识别优化点
Check for:
- Redundant tests: Similar test logic that can be consolidated with parametrization
- Duplicate fixtures: Common test data defined in multiple files
- Missing parametrization: Multiple tests for similar scenarios
- File organization: Tests that could be better consolidated
- Best practice violations: Testing private methods, vague assertions, etc.
- Slow tests: Tests that could be optimized or marked with
@pytest.mark.slow - Hardcoded values: Test data that should use fixtures or factories
检查以下内容:
- 冗余测试:可通过参数化合并的相似测试逻辑
- 重复夹具:在多个文件中定义的通用测试数据
- 缺少参数化:针对相似场景的多个重复测试
- 文件组织:可优化合并的测试文件
- 违反最佳实践:测试私有方法、模糊断言等
- 慢测试:可优化或标记为的测试
@pytest.mark.slow - 硬编码值:应使用夹具或工厂的测试数据
Refactoring Process
重构流程
When refactoring existing tests:
-
Capture baseline metrics:bash
bin/ci-local 2>&1 | tee baseline.txt grep "passed" baseline.txt # Note test count grep "Cover" baseline.txt # Note coverage % -
Prioritize changes by impact and isolation:
- High impact, isolated changes first (parametrization, shared fixtures)
- Medium impact changes (consolidating test files)
- Complex changes last (large file reorganization)
-
Apply refactoring patterns (see patterns.md)
-
Verify coverage maintained or improved:bash
uv run pytest --cov=src --cov-report=term-missing
重构现有测试时:
-
捕获基准指标:bash
bin/ci-local 2>&1 | tee baseline.txt grep "passed" baseline.txt # 记录测试数量 grep "Cover" baseline.txt # 记录覆盖率百分比 -
按影响和独立性优先处理变更:
- 先处理高影响、独立的变更(参数化、共享夹具)
- 再处理中等影响的变更(合并测试文件)
- 最后处理复杂变更(大规模文件重组)
-
应用重构模式(参见patterns.md)
-
验证覆盖率维持或提升:bash
uv run pytest --cov=src --cov-report=term-missing
Verification Checklist
验证清单
After completing TDD cycles or test refactoring, verify:
- All tests pass:
uv run pytest - Coverage maintained or improved:
uv run pytest --cov=src --cov-report=term-missing - No mypy errors:
uv run mypy src/ - No ruff errors:
uv run ruff check src/ - Tests execute faster:
uv run pytest --durations=10
For complete verification, run the full CI pipeline:
bash
bin/ci-local完成TDD循环或测试重构后,验证以下内容:
- 所有测试通过:
uv run pytest - 覆盖率维持或提升:
uv run pytest --cov=src --cov-report=term-missing - 无mypy错误:
uv run mypy src/ - 无ruff错误:
uv run ruff check src/ - 测试执行更快:
uv run pytest --durations=10
如需完整验证,运行完整CI流水线:
bash
bin/ci-localBest Practices
最佳实践
See best-practices.md for test writing, organization, and code quality guidelines.
参见best-practices.md获取测试编写、组织和代码质量指南。
Verification Commands
验证命令
bash
undefinedbash
undefinedRun all tests
运行所有测试
uv run pytest
uv run pytest
Run specific test file
运行指定测试文件
uv run pytest tests/models/test_registry.py -v
uv run pytest tests/models/test_registry.py -v
Run specific test
运行指定测试用例
uv run pytest tests/test_file.py::TestClass::test_function -vv
uv run pytest tests/test_file.py::TestClass::test_function -vv
Run with coverage
带覆盖率运行测试
uv run pytest --cov=src --cov-report=term-missing --cov-report=html
uv run pytest --cov=src --cov-report=term-missing --cov-report=html
Run full CI pipeline
运行完整CI流水线
bin/ci-local
bin/ci-local
Check test execution time
检查测试执行时间
uv run pytest --durations=10
uv run pytest --durations=10
Run fast tests only
仅运行快速测试
uv run pytest -m "not slow"
undefineduv run pytest -m "not slow"
undefinedImportant Notes
重要注意事项
- Test First: Always write tests before implementation
- Verify Red Phase: Confirm tests fail before writing implementation
- One at a Time: Focus on one failing test before moving to the next
- Maintain Coverage: Coverage must never decrease during refactoring
- Small Changes: Make incremental changes and run tests frequently
- List Refactoring Opportunities: After green, identify but wait for user request before implementing
- 先写测试:始终在实现代码前编写测试
- 验证红阶段:在编写实现代码前确认测试失败
- 一次处理一个:专注于一个失败的测试,再进行下一个
- 维持覆盖率:重构期间覆盖率绝不能下降
- 小步变更:进行增量变更并频繁运行测试
- 列出重构优化点:绿阶段结束后识别优化点,但需等待用户请求再实施