TDD Guide
The agent guides red-green-refactor TDD workflows, generates framework-specific test stubs from requirements, parses coverage reports to identify prioritized gaps, and calculates test quality metrics including smell detection and assertion density. Supports Jest, Pytest, JUnit, Vitest, and Mocha.
Quick Start
# Generate test cases from requirements (Python API)
from test_generator import TestGenerator, TestFramework
gen = TestGenerator(framework=TestFramework.PYTEST, language="python")
cases = gen.generate_from_requirements(requirements)
# Analyze coverage gaps from LCOV report
from coverage_analyzer import CoverageAnalyzer
analyzer = CoverageAnalyzer()
analyzer.parse_coverage_report(content, "lcov")
gaps = analyzer.identify_gaps(threshold=80.0)
# Guide TDD cycle
from tdd_workflow import TDDWorkflow
wf = TDDWorkflow()
wf.start_cycle("User can reset password via email")
Core Workflows
Workflow 1: TDD a New Feature
- Write a failing test for the feature requirement (RED phase)
- Call
validate_red_phase()-- confirms test exists and fails - Write minimal code to make the test pass (GREEN phase)
- Call
validate_green_phase()-- confirms all tests pass - Refactor while keeping tests green (REFACTOR phase)
- Call
validate_refactor_phase()-- confirms tests still pass after cleanup - Validation checkpoint: Each cycle completes in under 10 minutes; zero test smells introduced
Workflow 2: Analyze Coverage Gaps
- Generate coverage report:
npm test -- --coverageorpytest --cov - Detect format with
detect_format()and parse withparse_coverage_report() - Run
identify_gaps(threshold=80.0)to get prioritized file list (P0/P1/P2) - Generate test stubs for P0 files (business-critical, lowest coverage)
- Validation checkpoint: Line coverage >= 80%; branch coverage >= 70%; zero P0 gaps in critical paths
Workflow 3: Generate Tests from Requirements
- Structure requirements as user stories with acceptance criteria
- Call
generate_from_requirements()with target framework - Review generated test cases for completeness (happy path, error, edge cases)
- Generate test file with
generate_test_file() - Validation checkpoint: Each acceptance criterion has at least one test; all tests compile
Tools
| Tool | Purpose | |------|---------| | test_generator.py | Generate test cases from requirements/specs | | coverage_analyzer.py | Parse LCOV/JSON/XML reports, find gaps | | tdd_workflow.py | Guide red-green-refactor cycles | | framework_adapter.py | Convert tests between frameworks | | fixture_generator.py | Generate test data and mocks with seeds | | metrics_calculator.py | Calculate complexity and test quality | | format_detector.py | Auto-detect language and framework | | output_formatter.py | Format output for CLI/desktop/CI |
Anti-Patterns
- Tests that pass immediately -- a test with no real assertion or
assert Trueskips the RED phase; every test must fail before implementation - Testing implementation details -- coupling tests to internal method names makes refactoring break tests; test behavior and outputs, not internals
- Non-deterministic fixtures -- random data without a seed produces different failures across CI runs; always pass
seed=<int>toFixtureGenerator - Skipping the refactor phase -- GREEN code that works but is messy accumulates; refactoring is not optional in TDD
- Coverage theater -- writing tests that hit lines without meaningful assertions; use
metrics_calculator.pyto detect low assertion density - Conditional test logic --
if/elseinside tests masks failures; each test should have a single clear path
Troubleshooting
| Problem | Cause | Solution | |---------|-------|----------| | Generated tests pass immediately (no RED phase) | Test has no real assertion or asserts a trivially true value | Ensure every test contains an assertion against the actual unit under test; remove placeholder assert True stubs before running | | Coverage report fails to parse | Report format does not match the expected LCOV, JSON, or XML structure | Run format_detector.py first to verify the detected format; convert non-standard reports (e.g., Clover) to Cobertura XML | | Framework adapter produces wrong import style | Source and target framework were swapped, or language/framework mismatch | Verify the framework and language arguments match your project; use detect_framework() on existing test code to auto-detect | | Fixture generator produces non-deterministic data | No random seed was supplied, so each run yields different values | Pass seed=<int> to FixtureGenerator() for reproducible fixtures across CI runs | | Metrics calculator reports 0 test functions | Test code uses an unsupported naming convention (e.g., spec_ prefix) | Rename tests to follow test_* / it() / @Test conventions, or extend the regex patterns in _count_test_functions() | | TDD workflow validates GREEN phase but tests still fail locally | Test result dict passed to validate_green_phase() has status not set to "passed" | Ensure your test runner output is normalized to {"status": "passed"} or {"status": "failed"} before passing it in | | Coverage gaps list is empty despite low overall coverage | All individual files meet the threshold even though the aggregate does not | Lower the threshold argument in identify_gaps() or inspect per-file coverage with get_file_coverage() |
Success Criteria
- Test-first ratio above 80% -- at least 4 out of every 5 features begin with a failing test before any implementation code is written.
- Red-green-refactor cycle under 10 minutes -- each TDD micro-cycle (write failing test, make it pass, refactor) completes within a single focused interval.
- Line coverage at or above 80% -- measured by
coverage_analyzer.pyagainst LCOV/JSON/XML reports, with branch coverage at or above 70%. - Test quality score at or above 75/100 -- as reported by
metrics_calculator.py, combining assertion density, isolation, naming quality, and absence of test smells. - Zero P0 coverage gaps in critical paths -- business-critical modules (auth, payments, data persistence) have no files flagged P0 by
identify_gaps(). - Test smell count of zero for high-severity items -- no
missing_assertions,sleepy_test, orconditional_test_logicsmells detected at high severity. - Fixture reproducibility across CI -- all generated fixtures use a fixed seed and produce identical output on every pipeline run.
Scope & Limitations
This skill covers:
- Unit test generation, scaffolding, and stub creation for Jest, Pytest, JUnit, Vitest, and Mocha
- Static coverage report parsing (LCOV, JSON/Istanbul, XML/Cobertura) with gap identification and prioritized recommendations
- Red-green-refactor workflow guidance with phase validation and cycle tracking
- Test quality assessment including complexity analysis, isolation scoring, naming quality, and test smell detection
This skill does NOT cover:
- Integration, end-to-end, or performance test generation -- see
senior-qafor E2E patterns andsenior-devopsfor load testing - Runtime test execution or live coverage measurement -- scripts perform static analysis only; you must run your test suite externally
- Visual/snapshot testing or browser-based test workflows -- use Playwright, Cypress, or Storybook for UI-level testing
- Security-focused test generation (fuzz testing, penetration testing) -- see
senior-securityandsenior-secopsskills
Integration Points
| Skill | Integration | Data Flow | |-------|-------------|-----------| | senior-qa | Generated test stubs feed into QA review workflows; QA coverage standards inform threshold settings | test_generator.py output → QA review → approved test suite | | code-reviewer | Metrics calculator output provides quantitative d