[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-4c7179d2-77bc-4b39-acb3-ae896a9b80a8":3,"$fwkwN86OovCmacQ6FXHwZnMxGLUrp7CMoYAjpGQ6wcbk":43},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":18,"createdAt":19,"updatedAt":19,"module":20,"category":27,"packages":34},"4c7179d2-77bc-4b39-acb3-ae896a9b80a8","tdd-guide","测试驱动开发技能，包括编写单元测试、生成测试用例和模拟、分析覆盖率差距以及指导Jest、Pytest、JUnit、Vitest和Mocha中的红绿重构工作流程。当用户请求编写测试、提高测试覆盖率、练习TDD、生成模拟或存根或提及Jest、pytest或JUnit等测试框架时使用。","cat_coding_review","mod_coding","alirezarezvani,coding","---\nname: \"tdd-guide\"\ndescription: \"Test-driven development skill for writing unit tests, generating test fixtures and mocks, analyzing coverage gaps, and guiding red-green-refactor workflows across Jest, Pytest, JUnit, Vitest, and Mocha. Use when the user asks to write tests, improve test coverage, practice TDD, generate mocks or stubs, or mentions testing frameworks like Jest, pytest, or JUnit.\"\n---\n\n# TDD Guide\n\nTest-driven development skill for generating tests, analyzing coverage, and guiding red-green-refactor workflows across Jest, Pytest, JUnit, and Vitest.\n\n---\n\n## Workflows\n\n### Generate Tests from Code\n\n1. Provide source code (TypeScript, JavaScript, Python, Java)\n2. Specify target framework (Jest, Pytest, JUnit, Vitest)\n3. Run `test_generator.py` with requirements\n4. Review generated test stubs\n5. **Validation:** Tests compile and cover happy path, error cases, edge cases\n\n### Analyze Coverage Gaps\n\n1. Generate coverage report from test runner (`npm test -- --coverage`)\n2. Run `coverage_analyzer.py` on LCOV\u002FJSON\u002FXML report\n3. Review prioritized gaps (P0\u002FP1\u002FP2)\n4. Generate missing tests for uncovered paths\n5. **Validation:** Coverage meets target threshold (typically 80%+)\n\n### TDD New Feature\n\n1. Write failing test first (RED)\n2. Run `tdd_workflow.py --phase red` to validate\n3. Implement minimal code to pass (GREEN)\n4. Run `tdd_workflow.py --phase green` to validate\n5. Refactor while keeping tests green (REFACTOR)\n6. **Validation:** All tests pass after each cycle\n\n---\n\n## Examples\n\n### Test Generation — Input → Output (Pytest)\n\n**Input source function (`math_utils.py`):**\n```python\ndef divide(a: float, b: float) -> float:\n    if b == 0:\n        raise ValueError(\"Cannot divide by zero\")\n    return a \u002F b\n```\n\n**Command:**\n```bash\npython scripts\u002Ftest_generator.py --input math_utils.py --framework pytest\n```\n\n**Generated test output (`test_math_utils.py`):**\n```python\nimport pytest\nfrom math_utils import divide\n\nclass TestDivide:\n    def test_divide_positive_numbers(self):\n        assert divide(10, 2) == 5.0\n\n    def test_divide_negative_numerator(self):\n        assert divide(-10, 2) == -5.0\n\n    def test_divide_float_result(self):\n        assert divide(1, 3) == pytest.approx(0.333, rel=1e-3)\n\n    def test_divide_by_zero_raises_value_error(self):\n        with pytest.raises(ValueError, match=\"Cannot divide by zero\"):\n            divide(10, 0)\n\n    def test_divide_zero_numerator(self):\n        assert divide(0, 5) == 0.0\n```\n\n---\n\n### Coverage Analysis — Sample P0\u002FP1\u002FP2 Output\n\n**Command:**\n```bash\npython scripts\u002Fcoverage_analyzer.py --report lcov.info --threshold 80\n```\n\n**Sample output:**\n```\nCoverage Report — Overall: 63% (threshold: 80%)\n\nP0 — Critical gaps (uncovered error paths):\n  auth\u002Flogin.py:42-58   handle_expired_token()       0% covered\n  payments\u002Fprocess.py:91-110  handle_payment_failure()   0% covered\n\nP1 — High-value gaps (core logic branches):\n  users\u002Fservice.py:77   update_profile() — else branch  0% covered\n  orders\u002Fcart.py:134    apply_discount() — zero-qty guard  0% covered\n\nP2 — Low-risk gaps (utility \u002F helper functions):\n  utils\u002Fformatting.py:12  format_currency()            0% covered\n\nRecommended: Generate tests for P0 items first to reach 80% threshold.\n```\n\n---\n\n## Key Tools\n\n| Tool | Purpose | Usage |\n|------|---------|-------|\n| `test_generator.py` | Generate test cases from code\u002Frequirements | `python scripts\u002Ftest_generator.py --input source.py --framework pytest` |\n| `coverage_analyzer.py` | Parse and analyze coverage reports | `python scripts\u002Fcoverage_analyzer.py --report lcov.info --threshold 80` |\n| `tdd_workflow.py` | Guide red-green-refactor cycles | `python scripts\u002Ftdd_workflow.py --phase red --test test_auth.py` |\n| `fixture_generator.py` | Generate test data and mocks | `python scripts\u002Ffixture_generator.py --entity User --count 5` |\n\nAdditional scripts: `framework_adapter.py` (convert between frameworks), `metrics_calculator.py` (quality metrics), `format_detector.py` (detect language\u002Fframework), `output_formatter.py` (CLI\u002Fdesktop\u002FCI output).\n\n---\n\n## Input Requirements\n\n**For Test Generation:**\n- Source code (file path or pasted content)\n- Target framework (Jest, Pytest, JUnit, Vitest)\n- Coverage scope (unit, integration, edge cases)\n\n**For Coverage Analysis:**\n- Coverage report file (LCOV, JSON, or XML format)\n- Optional: Source code for context\n- Optional: Target threshold percentage\n\n**For TDD Workflow:**\n- Feature requirements or user story\n- Current phase (RED, GREEN, REFACTOR)\n- Test code and implementation status\n\n---\n\n## Spec-First Workflow\n\nTDD is most effective when driven by a written spec. The flow:\n\n1. **Write or receive a spec** — stored in `specs\u002F\u003Cfeature>.md`\n2. **Extract acceptance criteria** — each criterion becomes one or more test cases\n3. **Write failing tests (RED)** — one test per acceptance criterion\n4. **Implement minimal code (GREEN)** — satisfy each test in order\n5. **Refactor** — clean up while all tests stay green\n\n### Spec Directory Convention\n\n```\nproject\u002F\n├── specs\u002F\n│   ├── user-auth.md          # Feature spec with acceptance criteria\n│   ├── payment-processing.md\n│   └── notification-system.md\n├── tests\u002F\n│   ├── test_user_auth.py     # Tests derived from specs\u002Fuser-auth.md\n│   ├── test_payments.py\n│   └── test_notifications.py\n└── src\u002F\n```\n\n### Extracting Tests from Specs\n\nEach acceptance criterion in a spec maps to at least one test:\n\n| Spec Criterion | Test Case |\n|---------------|-----------|\n| \"User can log in with valid credentials\" | `test_login_valid_credentials_returns_token` |\n| \"Invalid password returns 401\" | `test_login_invalid_password_returns_401` |\n| \"Account locks after 5 failed attempts\" | `test_login_locks_after_five_failures` |\n\n**Tip:** Number your acceptance criteria in the spec. Reference the number in the test docstring for traceability (`# AC-3: Account locks after 5 failed attempts`).\n\n> **Cross-reference:** See `engineering\u002Fspec-driven-workflow` for the full spec methodology, including spec templates and review checklists.\n\n---\n\n## Red-Green-Refactor Examples Per Language\n\n### TypeScript \u002F Jest\n\n```typescript\n\u002F\u002F test\u002Fcart.test.ts\ndescribe(\"Cart\", () => {\n  describe(\"addItem\", () => {\n    it(\"should add a new item to an empty cart\", () => {\n      const cart = new Cart();\n      cart.addItem({ id: \"sku-1\", name: \"Widget\", price: 9.99, qty: 1 });\n\n      expect(cart.items).toHaveLength(1);\n      expect(cart.items[0].id).toBe(\"sku-1\");\n    });\n\n    it(\"should increment quantity when adding an existing item\", () => {\n      const cart = new Cart();\n      cart.addItem({ id: \"sku-1\", name: \"Widget\", price: 9.99, qty: 1 });\n      cart.addItem({ id: \"sku-1\", name: \"Widget\", price: 9.99, qty: 2 });\n\n      expect(cart.items).toHaveLength(1);\n      expect(cart.items[0].qty).toBe(3);\n    });\n\n    it(\"should throw when quantity is zero or negative\", () => {\n      const cart = new Cart();\n      expect(() =>\n        cart.addItem({ id: \"sku-1\", name: \"Widget\", price: 9.99, qty: 0 })\n      ).toThrow(\"Quantity must be positive\");\n    });\n  });\n});\n```\n\n### Python \u002F Pytest (Advanced Patterns)\n\n```python\n# tests\u002Fconftest.py — shared fixtures\nimport pytest\nfrom app.db import create_engine, Session\n\n@pytest.fixture(scope=\"session\")\ndef db_engine():\n    engine = create_engine(\"sqlite:\u002F\u002F\u002F:memory:\")\n    yield engine\n    engine.dispose()\n\n@pytest.fixture\ndef db_session(db_engine):\n    session = Session(bind=db_engine)\n    yield session\n    session.rollback()\n    session.close()\n\n# tests\u002Ftest_pricing.py — parametrize for multiple cases\nimport pytest\nfrom app.pricing import calculate_discount\n\n@pytest.mark.parametrize(\"subtotal, expected_discount\", [\n    (50.0, 0.0),       # Below threshold — no discount\n    (100.0, 5.0),      # 5% tier\n    (250.0, 25.0),     # 10% tier\n    (500.0, 75.0),     # 15% tier\n])\ndef test_calculate_discount(subtotal, expected_discount):\n    assert calculate_discount(subtotal) == pytest.approx(expected_discount)\n```\n\n### Go — Table-Driven Tests\n\n```go\n\u002F\u002F cart_test.go\npackage cart\n\nimport \"testing\"\n\nfunc TestApplyDiscount(t *testing.T) {\n    tests := []struct {\n        name     string\n        subtotal float64\n        want     float64\n    }{\n        {\"no discount below threshold\", 50.0, 0.0},\n        {\"5 percent tier\", 100.0, 5.0},\n        {\"10 percent tier\", 250.0, 25.0},\n        {\"15 percent tier\", 500.0, 75.0},\n        {\"zero subtotal\", 0.0, 0.0},\n    }\n\n    for _, tt := range tests {\n        t.Run(tt.name, func(t *testing.T) {\n            got := ApplyDiscount(tt.subtotal)\n            if got != tt.want {\n                t.Errorf(\"ApplyDiscount(%v) = %v, want %v\", tt.subtotal, got, tt.want)\n            }\n        })\n    }\n}\n```\n\n---\n\n## Bounded Autonomy Rules\n\nWhen generating tests autonomously, follow these rules to decide when to stop and ask the user:\n\n### Stop and Ask When\n\n- **Ambiguous requirements** — the spec or user story has conflicting or unclear acceptance criteria\n- **Missing edge cases** — you cannot determine boundary values without domain knowledge (e.g., max allowed transaction amount)\n- **Test count exceeds 50** — large test suites need human review before committing; present a summary and ask which areas to prioritize\n- **External dependencies unclear** — the feature relies on third-party APIs or services with undocumented behavior\n- **Security-sensitive logic** — authentication, authorization, encryption, or payment flows require human sign-off on test scenarios\n\n### Continue Autonomously When\n\n- **Clear spec with numbered acceptance criteria** — each criterion maps directly to tests\n- **Straightforward CRUD operations** — create, read, update, delete with well-defined models\n- **Well-defined API contracts** — OpenAPI spec or typed interfaces available\n- **Pure functions** — deterministic input\u002Foutput with no side effects\n- **Existing test patterns** — the codebase already has similar tests to follow\n\n---\n\n## Property-Based Testing\n\nProperty-based testing generates random inputs to verify invariants instead of relying on hand-picked examples. Use it when the input space is large and the expected behavior can be described as a property.\n\n### Python — Hypothesis\n\n```python\nfrom hypothesis import given, strategies as st\nfrom app.serializers import serialize, deserialize\n\n@given(st.text())\ndef test_roundtrip_serialization(data):\n    \"\"\"Serialization followed by deserialization returns the original.\"\"\"\n    assert deserialize(serialize(data)) == data\n\n@given(st.integers(), st.integers())\ndef test_addition_is_commutative(a, b):\n    assert a + b == b + a\n```\n\n### TypeScript — fast-check\n\n```typescript\nimport fc from \"fast-check\";\nimport { encode, decode } from \".\u002Fcodec\";\n\ntest(\"encode\u002Fdecode roundtrip\", () => {\n  fc.assert(\n    fc.property(fc.string(), (input) => {\n      expect(decode(encode(input))).toBe(input);\n    })\n  );\n});\n```\n\n### When to Use Property-Based Over Example-Based\n\n| Use Property-Based | Example |\n|-------------------|---------|\n| Data transformations | Serialize\u002Fdeserialize roundtrips |\n| Mathematical properties | Commutativity, associativity, idempotency |\n| Encoding\u002Fdecoding | Base64, URL encoding, compression |\n| Sorting and filtering | Output is sorted, length preserved |\n| Parser correctness | Valid input always parses without error |\n\n---\n\n## Mutation Testing\n\nMutation testing modifies your production code (creates \"mutants\") and checks whether your tests catch the changes. If a mutant survives (tests still pass), your tests have a gap that coverage alone cannot reveal.\n\n### Tools\n\n| Language | Tool | Command |\n|----------|------|---------|\n| TypeScript\u002FJavaScript | **Stryker** | `npx stryker run` |\n| Python | **mutmut** | `mutmut run --paths-to-mutate=src\u002F` |\n| Java | **PIT** | `mvn org.pitest:pitest-maven:mutationCoverage` |\n\n### Why Mutation Testing Matters\n\n- **100% line coverage != good tests** — coverage tells you code was executed, not that it was verified\n- **Catches weak assertions** — tests that run code but assert nothing meaningful\n- **Finds missing boundary tests** — mutants that change `\u003C` to `\u003C=` expose off-by-one gaps\n- **Quantifiable quality metric** — mutation score (% mutants killed) is a stronger signal than coverage %\n\n**Recommendation:** Run mutation testing on critical paths (auth, payments, data processing) even if overall coverage is high. Target 85%+ mutation score on P0 modules.\n\n---\n\n## Cross-References\n\n| Skill | Relationship |\n|-------|-------------|\n| `engineering\u002Fspec-driven-workflow` | Spec → acceptance criteria → test extraction pipeline |\n| `engineering-team\u002Ffocused-fix` | Phase 5 (Verify) uses TDD to confirm the fix with a regression test |\n| `engineering-team\u002Fsenior-qa` | Broader QA strategy; TDD is one layer in the test pyramid |\n| `engineering-team\u002Fcode-reviewer` | Review generated tests for assertion quality and coverage completeness |\n| `engineering-team\u002Fsenior-fullstack` | Project scaffolders include testing infrastructure compatible with TDD workflows |\n\n---\n\n## Limitations\n\n| Scope | Details |\n|-------|---------|\n| Unit test focus | Integration and E2E tests require different patterns |\n| Static analysis | Cannot execute tests or measure runtime behavior |\n| Language support | Best for TypeScript, JavaScript, Python, Java |\n| Report formats | LCOV, JSON, XML only; other formats need conversion |\n| Generated tests | Provide scaffolding; require human review for complex logic |\n\n**When to use other tools:**\n- E2E testing: Playwright, Cypress, Selenium\n- Performance testing: k6, JMeter, Locust\n- Security testing: OWASP ZAP, Burp Suite\n","","imported","https:\u002F\u002Fgithub.com\u002Falirezarezvani\u002Fclaude-skills","user_system_seed","SkillOPIC",true,136,1656,"2026-05-16 13:58:22",{"id":8,"name":21,"slug":22,"icon":23,"description":24,"sort":25,"createdAt":26},"编程开发","coding","mdi-code-braces","代码生成、调试、审查，提升开发效率",2,"2026-05-16 12:53:40",{"id":7,"name":28,"slug":29,"icon":30,"description":31,"moduleId":8,"sort":32,"skillCount":33,"createdAt":26},"代码审查","review","mdi-magnify-scan","代码质量分析、安全审查",4,145,[35],{"id":36,"skillId":4,"version":37,"fileName":38,"fileSize":39,"filePath":40,"fileHash":41,"manifest":42,"createdAt":19},"911381c2-4fe6-4d63-8a9d-bb0746c52347","1.0.0","tdd-guide.zip",51419,"uploads\u002Fskills\u002F4c7179d2-77bc-4b39-acb3-ae896a9b80a8\u002Ftdd-guide.zip","70903ef5523d7527b4f16ea4e5538a5e672897a7df13ddbf961fd70311b41db6","[{\"path\":\"HOW_TO_USE.md\",\"isDirectory\":false,\"size\":7176},{\"path\":\"README.md\",\"isDirectory\":false,\"size\":18528},{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":13707},{\"path\":\"assets\u002Fexpected_output.json\",\"isDirectory\":false,\"size\":2404},{\"path\":\"assets\u002Fsample_coverage_report.lcov\",\"isDirectory\":false,\"size\":615},{\"path\":\"assets\u002Fsample_input_python.json\",\"isDirectory\":false,\"size\":1443},{\"path\":\"assets\u002Fsample_input_typescript.json\",\"isDirectory\":false,\"size\":1469},{\"path\":\"references\u002Fci-integration.md\",\"isDirectory\":false,\"size\":4017},{\"path\":\"references\u002Fframework-guide.md\",\"isDirectory\":false,\"size\":4316},{\"path\":\"references\u002Ftdd-best-practices.md\",\"isDirectory\":false,\"size\":3516},{\"path\":\"scripts\u002Fcoverage_analyzer.py\",\"isDirectory\":false,\"size\":15502},{\"path\":\"scripts\u002Ffixture_generator.py\",\"isDirectory\":false,\"size\":14311},{\"path\":\"scripts\u002Fformat_detector.py\",\"isDirectory\":false,\"size\":12207},{\"path\":\"scripts\u002Fframework_adapter.py\",\"isDirectory\":false,\"size\":14834},{\"path\":\"scripts\u002Fmetrics_calculator.py\",\"isDirectory\":false,\"size\":15476},{\"path\":\"scripts\u002Foutput_formatter.py\",\"isDirectory\":false,\"size\":12734},{\"path\":\"scripts\u002Ftdd_workflow.py\",\"isDirectory\":false,\"size\":16968},{\"path\":\"scripts\u002Ftest_generator.py\",\"isDirectory\":false,\"size\":14617}]",{"code":44,"message":45,"data":46},200,"success",{"items":47,"stats":48,"page":51},[],{"averageRating":49,"totalRatings":49,"ratingCounts":50},0,[49,49,49,49,49],{"limit":52,"offset":49,"hasMore":53,"nextOffset":52,"ratedOnly":16},15,false]