TDD Guide
Test-driven development skill for generating tests, analyzing coverage, and guiding red-green-refactor workflows across Jest, Pytest, JUnit, and Vitest.
Workflows
Generate Tests from Code
- 1. Provide source code (TypeScript, JavaScript, Python, Java)
- Specify target framework (Jest, Pytest, JUnit, Vitest)
- Run
test_generator.py with requirements - Review generated test stubs
- Validation: Tests compile and cover happy path, error cases, edge cases
Analyze Coverage Gaps
- 1. Generate coverage report from test runner (
npm test -- --coverage) - Run
coverage_analyzer.py on LCOV/JSON/XML report - Review prioritized gaps (P0/P1/P2)
- Generate missing tests for uncovered paths
- Validation: Coverage meets target threshold (typically 80%+)
TDD New Feature
- 1. Write failing test first (RED)
- Run
tdd_workflow.py --phase red to validate - Implement minimal code to pass (GREEN)
- Run
tdd_workflow.py --phase green to validate - Refactor while keeping tests green (REFACTOR)
- Validation: All tests pass after each cycle
Examples
Test Generation — Input → Output (Pytest)
Input source function (math_utils.py):
CODEBLOCK0
Command:
CODEBLOCK1
Generated test output (test_math_utils.py):
import pytest
from math_utils import divide
class TestDivide:
def test_divide_positive_numbers(self):
assert divide(10, 2) == 5.0
def test_divide_negative_numerator(self):
assert divide(-10, 2) == -5.0
def test_divide_float_result(self):
assert divide(1, 3) == pytest.approx(0.333, rel=1e-3)
def test_divide_by_zero_raises_value_error(self):
with pytest.raises(ValueError, match="Cannot divide by zero"):
divide(10, 0)
def test_divide_zero_numerator(self):
assert divide(0, 5) == 0.0
Coverage Analysis — Sample P0/P1/P2 Output
Command:
CODEBLOCK3
Sample output:
Coverage Report — Overall: 63% (threshold: 80%)
P0 — Critical gaps (uncovered error paths):
auth/login.py:42-58 handle_expired_token() 0% covered
payments/process.py:91-110 handle_payment_failure() 0% covered
P1 — High-value gaps (core logic branches):
users/service.py:77 update_profile() — else branch 0% covered
orders/cart.py:134 apply_discount() — zero-qty guard 0% covered
P2 — Low-risk gaps (utility / helper functions):
utils/formatting.py:12 format_currency() 0% covered
Recommended: Generate tests for P0 items first to reach 80% threshold.
Key Tools
| Tool | Purpose | Usage |
|---|
| INLINECODE7 | Generate test cases from code/requirements | INLINECODE8 |
| INLINECODE9 |
Parse and analyze coverage reports |
python scripts/coverage_analyzer.py --report lcov.info --threshold 80 |
|
tdd_workflow.py | Guide red-green-refactor cycles |
python scripts/tdd_workflow.py --phase red --test test_auth.py |
|
fixture_generator.py | Generate test data and mocks |
python scripts/fixture_generator.py --entity User --count 5 |
Additional scripts: framework_adapter.py (convert between frameworks), metrics_calculator.py (quality metrics), format_detector.py (detect language/framework), output_formatter.py (CLI/desktop/CI output).
Input Requirements
For Test Generation:
- - Source code (file path or pasted content)
- Target framework (Jest, Pytest, JUnit, Vitest)
- Coverage scope (unit, integration, edge cases)
For Coverage Analysis:
- - Coverage report file (LCOV, JSON, or XML format)
- Optional: Source code for context
- Optional: Target threshold percentage
For TDD Workflow:
- - Feature requirements or user story
- Current phase (RED, GREEN, REFACTOR)
- Test code and implementation status
Limitations
| Scope | Details |
|---|
| Unit test focus | Integration and E2E tests require different patterns |
| Static analysis |
Cannot execute tests or measure runtime behavior |
| Language support | Best for TypeScript, JavaScript, Python, Java |
| Report formats | LCOV, JSON, XML only; other formats need conversion |
| Generated tests | Provide scaffolding; require human review for complex logic |
When to use other tools:
- - E2E testing: Playwright, Cypress, Selenium
- Performance testing: k6, JMeter, Locust
- Security testing: OWASP ZAP, Burp Suite
TDD 指南
用于生成测试、分析覆盖率并指导 Jest、Pytest、JUnit 和 Vitest 中红-绿-重构工作流的测试驱动开发技能。
工作流
从代码生成测试
- 1. 提供源代码(TypeScript、JavaScript、Python、Java)
- 指定目标框架(Jest、Pytest、JUnit、Vitest)
- 根据需求运行 test_generator.py
- 审查生成的测试桩
- 验证: 测试编译通过,覆盖正常路径、错误情况和边界情况
分析覆盖率缺口
- 1. 从测试运行器生成覆盖率报告(npm test -- --coverage)
- 对 LCOV/JSON/XML 报告运行 coverage_analyzer.py
- 审查按优先级排序的缺口(P0/P1/P2)
- 为未覆盖路径生成缺失的测试
- 验证: 覆盖率达到目标阈值(通常为 80% 以上)
TDD 新功能
- 1. 先编写失败的测试(RED)
- 运行 tddworkflow.py --phase red 进行验证
- 实现最简代码以通过测试(GREEN)
- 运行 tddworkflow.py --phase green 进行验证
- 在保持测试通过的前提下重构(REFACTOR)
- 验证: 每个周期后所有测试均通过
示例
测试生成 — 输入 → 输出(Pytest)
输入源函数(math_utils.py):
python
def divide(a: float, b: float) -> float:
if b == 0:
raise ValueError(Cannot divide by zero)
return a / b
命令:
bash
python scripts/testgenerator.py --input mathutils.py --framework pytest
生成的测试输出(testmathutils.py):
python
import pytest
from math_utils import divide
class TestDivide:
def testdividepositive_numbers(self):
assert divide(10, 2) == 5.0
def testdividenegative_numerator(self):
assert divide(-10, 2) == -5.0
def testdividefloat_result(self):
assert divide(1, 3) == pytest.approx(0.333, rel=1e-3)
def testdividebyzeroraisesvalueerror(self):
with pytest.raises(ValueError, match=Cannot divide by zero):
divide(10, 0)
def testdividezero_numerator(self):
assert divide(0, 5) == 0.0
覆盖率分析 — 示例 P0/P1/P2 输出
命令:
bash
python scripts/coverage_analyzer.py --report lcov.info --threshold 80
示例输出:
覆盖率报告 — 总体:63%(阈值:80%)
P0 — 关键缺口(未覆盖的错误路径):
auth/login.py:42-58 handleexpiredtoken() 覆盖率 0%
payments/process.py:91-110 handlepaymentfailure() 覆盖率 0%
P1 — 高价值缺口(核心逻辑分支):
users/service.py:77 update_profile() — else 分支 覆盖率 0%
orders/cart.py:134 apply_discount() — 零数量守卫 覆盖率 0%
P2 — 低风险缺口(工具/辅助函数):
utils/formatting.py:12 format_currency() 覆盖率 0%
建议:优先为 P0 项生成测试,以达到 80% 的阈值。
关键工具
| 工具 | 用途 | 用法 |
|---|
| testgenerator.py | 从代码/需求生成测试用例 | python scripts/testgenerator.py --input source.py --framework pytest |
| coverageanalyzer.py |
解析和分析覆盖率报告 | python scripts/coverageanalyzer.py --report lcov.info --threshold 80 |
| tdd
workflow.py | 指导红-绿-重构周期 | python scripts/tddworkflow.py --phase red --test test_auth.py |
| fixture
generator.py | 生成测试数据和模拟对象 | python scripts/fixturegenerator.py --entity User --count 5 |
其他脚本:frameworkadapter.py(在框架间转换)、metricscalculator.py(质量指标)、formatdetector.py(检测语言/框架)、outputformatter.py(CLI/桌面/CI 输出)。
输入要求
对于测试生成:
- - 源代码(文件路径或粘贴的内容)
- 目标框架(Jest、Pytest、JUnit、Vitest)
- 覆盖率范围(单元测试、集成测试、边界情况)
对于覆盖率分析:
- - 覆盖率报告文件(LCOV、JSON 或 XML 格式)
- 可选:用于上下文的源代码
- 可选:目标阈值百分比
对于 TDD 工作流:
- - 功能需求或用户故事
- 当前阶段(RED、GREEN、REFACTOR)
- 测试代码和实现状态
限制
| 范围 | 详情 |
|---|
| 单元测试重点 | 集成测试和端到端测试需要不同的模式 |
| 静态分析 |
无法执行测试或测量运行时行为 |
| 语言支持 | 最适合 TypeScript、JavaScript、Python、Java |
| 报告格式 | 仅支持 LCOV、JSON、XML;其他格式需要转换 |
| 生成的测试 | 提供脚手架;复杂逻辑需要人工审查 |
何时使用其他工具:
- - 端到端测试:Playwright、Cypress、Selenium
- 性能测试:k6、JMeter、Locust
- 安全测试:OWASP ZAP、Burp Suite