[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7871D09BNP2X3Z9A6E2KBCR":3,"skill-same:01M7871D09BNP2X3Z9A6E2KBCR":46},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":26,"commitSha":27,"skillDirectory":28,"forksCount":14,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":31,"install":32,"resources":45},"01M7871D09BNP2X3Z9A6E2KBCR","python-testing",null,"Use ONLY when user explicitly requests Python test code, pytest configuration,\ntest failure diagnosis, or coverage improvement for Python projects.\n\nTriggers: \"write test\", \"pytest\", \"unit test python\", \"coverage python\",\n\"flaky test python\", \"mock python\", \"test fixture\", \"parametrize\", \"factory boy\",\n\"freezegun\", \"pytest-asyncio\", \"pytest-cov\".\n\nDo NOT activate for: general Python coding without test context, linting (flake8\u002Fruff),\ntype checking (mypy), or non-test package management (pip install general).","chenziyang110\u002Flaunchdeck","chenziyang110","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F43693913?v=4","01M7863EBWK1D0P6A29YGEMAS4","Robin11","01M7863ECM1VB6RXDMHTW90D2T",0,"MIT","https:\u002F\u002Fgithub.com\u002Fchenziyang110\u002Flaunchdeck\u002Fblob\u002Fmain\u002F.specify\u002Ftemplates\u002Fpassive-skills\u002Fpython-testing\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: python-testing\ndescription: |\n  Use ONLY when user explicitly requests Python test code, pytest configuration,\n  test failure diagnosis, or coverage improvement for Python projects.\n\n  Triggers: \"write test\", \"pytest\", \"unit test python\", \"coverage python\",\n  \"flaky test python\", \"mock python\", \"test fixture\", \"parametrize\", \"factory boy\",\n  \"freezegun\", \"pytest-asyncio\", \"pytest-cov\".\n\n  Do NOT activate for: general Python coding without test context, linting (flake8\u002Fruff),\n  type checking (mypy), or non-test package management (pip install general).\norigin: ECC\n---\n\n# Python Testing (Agent Skill)\n\nAgent-focused testing workflow for modern Python (3.10+) using pytest, the industry-standard test framework.\n\n## When to Use\n\n- Writing new Python tests or fixing existing tests\n- Designing unit\u002Fintegration test coverage for Python components\n- Adding test coverage, CI gating, or regression protection\n- Configuring pytest workflows for consistent execution\n- Investigating test failures or flaky behavior\n- Testing async code, CLI tools, or web frameworks\n\n### When NOT to Use\n\n- Implementing new product features without test changes\n- Large-scale refactors unrelated to test coverage or failures\n- Performance tuning without test regressions to validate\n- Non-Python projects or non-test tasks\n\n### Stop Conditions — When to ASK instead of generating\n\nBefore generating any test code, STOP and ask the user if:\n- The code under test has **zero testability** (no DI, global mutable state, hard-coded external calls, no interfaces)\n- **No test framework** is detected in the project (no `pytest.ini`, `pyproject.toml` test config, `conftest.py`)\n- The request is **ambiguous**: \"test my app\" or \"add tests\" without specifying files or components\n- A **required test dependency** (`pytest`, `pytest-asyncio`, `pytest-cov`) is not installed\n- The test would require **secrets, real credentials, or production database access**\n\n## Core Concepts\n\n- **TDD loop**: red → green → refactor (tests first, minimal fix, then cleanups).\n- **Isolation**: prefer dependency injection and fixtures over global state.\n- **Test layout**: `tests\u002Funit`, `tests\u002Fintegration`, `tests\u002Fconftest.py`, `tests\u002Ftestdata\u002F`.\n- **Fixtures**: pytest's dependency injection mechanism for setup\u002Fteardown.\n- **Parametrization**: `@pytest.mark.parametrize` for testing multiple inputs.\n- **CI signal**: run subset first, then full suite with `--tb=short -x`.\n\n## Agent Execution Protocol\n\nWhen this skill is activated, follow this exact execution sequence:\n\n### Phase 1: Context Analysis\nBefore writing any test code:\n1. Identify the Python version (3.10+) and test framework (pytest preferred).\n2. Check for existing test files (`tests\u002F`, `*_test.py`, `test_*.py`) to infer naming conventions.\n3. Analyze the code under test: identify public API surface, side effects, I\u002FO boundaries (DB, HTTP, filesystem), and async\u002Fawait usage.\n4. Determine request type: (a) new tests, (b) fixing broken tests, (c) coverage improvement, (d) flaky test diagnosis.\n\n### Phase 2: Strategy Selection\nBased on Phase 1, select the appropriate strategy:\n- **Pure functions \u002F value objects**: unit tests only, no mocks needed. Use `pytest.mark.parametrize` for multiple cases.\n- **External dependencies (DB, HTTP, filesystem)**: use `unittest.mock`, `pytest.monkeypatch`, or `responses`\u002F`pytest-httpx`; prefer `tmp_path` for filesystem.\n- **Async code**: use `pytest-asyncio` with `@pytest.mark.asyncio` and `asyncio_mode = auto`.\n- **Web frameworks (Django\u002FFastAPI\u002FFlask)**: use framework-specific test clients (`django.test.Client`, `TestClient`).\n\n### Decision Tree (Complex Scenarios)\n\n```text\nQ1: External I\u002FO (DB, HTTP, filesystem, network)?\n  → Yes → Q2\n  → No  → Pure unit test, no mocks needed\n\nQ2: Mockable at code boundary (DI, interface, parameter injection)?\n  → Yes → Mock at boundary (unittest.mock, monkeypatch, responses)\n  → No  → Q3\n\nQ3: Needs real behavior verification (SQL, transactions)?\n  → Yes → Integration test (Django TestCase, FastAPI TestClient, testcontainers)\n  → No  → Use fake\u002Fstub (in-memory repo, tmp_path files)\n\nQ4: Async code (asyncio)?\n  → Yes → @pytest.mark.asyncio + asyncio_mode = auto\n  → No  → Synchronous test sufficient\n\nQ5: Web\u002Fbrowser rendering?\n  → Yes → Django LiveServerTestCase, Playwright, Selenium\n  → No  → Standard unit test\n```\n\n### Phase 3: Test Case Design\nApply systematic test design before coding:\n1. **Happy path**: normal input → expected output.\n2. **Boundary values**: empty string, zero, `None`, max length, empty collection.\n3. **Error cases**: invalid types, exceptions (`pytest.raises`), permission errors, timeout scenarios.\n4. **State & concurrency**: shared mutable state, race conditions, cache invalidation.\n\n### Phase 4: Code Generation\nOutput tests in this exact structure:\n```\n#### Test Strategy Summary\n- [ ] Scope: Unit \u002F Integration \u002F E2E\n- [ ] Framework: pytest (with asyncio\u002Fmonkeypatch if needed)\n- [ ] Mocking: Yes\u002FNo — tools used\n- [ ] Edge cases covered: \u003Clist>\n\n#### Generated Test Code\n\u003Cfile_path>\n\u003Ccode>\n\n#### Running Commands\n```bash\npytest -x --tb=short -v \u003Cfile_path>\n```\n\n#### Coverage Impact (if applicable)\n- Estimated coverage change: \u003CX%>\n- Command to verify: `pytest --cov=src --cov-report=term-missing`\n```\n\n### Phase 5: Verification Checklist\nBefore completing, verify:\n- [ ] Tests parse without syntax errors (`pytest --collect-only`).\n- [ ] Each test has exactly one logical assertion focus.\n- [ ] Mocks are reset between tests (use `yield` fixtures or `clear` in `setup_method`).\n- [ ] No `time.sleep` used for synchronization (use `freezegun` or `asyncio.sleep`).\n- [ ] Flaky test guardrails applied (isolation, determinism, `tmp_path`).\n\n## TDD Workflow\n\nFollow the RED → GREEN → REFACTOR loop:\n\n1. **RED**: write a failing test that captures the new behavior\n2. **GREEN**: implement the smallest change to pass\n3. **REFACTOR**: clean up while tests stay green\n\n```python\n# tests\u002Ftest_add.py\ndef add(a: int, b: int) -> int:  # Provided by production code.\n    ...\n\ndef test_adds_two_numbers():  # RED\n    assert add(2, 3) == 5\n\n# src\u002Fadd.py\ndef add(a: int, b: int) -> int:  # GREEN\n    return a + b\n\n# REFACTOR: simplify\u002Frename once tests pass\n```\n\n## Code Examples\n\n### Basic Unit Test (pytest)\n\n```python\n# tests\u002Ftest_calculator.py\n\ndef add(a: int, b: int) -> int:  # Provided by production code.\n    ...\n\nclass TestCalculator:\n    def test_adds_two_numbers(self):\n        assert add(2, 3) == 5\n```\n\n### Fixtures (pytest)\n\n```python\n# tests\u002Fconftest.py\nimport pytest\nfrom typing import Optional\n\nclass User:\n    def __init__(self, name: str):\n        self.name = name\n\nclass UserStore:\n    def __init__(self):\n        self._users: list[User] = []\n\n    def seed(self, users: list[User]) -> None:\n        self._users.extend(users)\n\n    def find(self, name: str) -> Optional[User]:\n        return next((u for u in self._users if u.name == name), None)\n\n@pytest.fixture\ndef user_store():\n    store = UserStore()\n    store.seed([User(\"alice\"), User(\"bob\")])\n    return store\n\n# tests\u002Ftest_user_store.py\ndef test_finds_existing_user(user_store):\n    user = user_store.find(\"alice\")\n    assert user is not None\n    assert user.name == \"alice\"\n```\n\n### Mocking (pytest + monkeypatch \u002F unittest.mock)\n\n```python\n# tests\u002Ftest_notifier.py\nfrom unittest.mock import Mock\n\nclass Service:\n    def __init__(self, notifier):\n        self._notifier = notifier\n\n    def publish(self, message: str):\n        self._notifier.send(message)\n\ndef test_sends_notifications():\n    notifier = Mock()\n    service = Service(notifier)\n\n    service.publish(\"hello\")\n\n    notifier.send.assert_called_once_with(\"hello\")\n```\n\n### Async Test (pytest-asyncio)\n\n```python\n# tests\u002Ftest_api.py\nimport pytest\n\nasync def fetch_user(user_id: str) -> dict:\n    return {\"name\": \"alice\"}\n\n@pytest.mark.asyncio\nasync def test_fetches_user_data():\n    user = await fetch_user(\"1\")\n    assert user[\"name\"] == \"alice\"\n\n@pytest.mark.asyncio\nasync def test_handles_errors():\n    with pytest.raises(ValueError):\n        raise ValueError(\"invalid id\")\n```\n\n### Parametrized Test\n\n```python\n# tests\u002Ftest_math.py\nimport pytest\n\ndef add(a: int, b: int) -> int:\n    return a + b\n\n@pytest.mark.parametrize(\"a,b,expected\", [\n    (1, 2, 3),\n    (-1, 1, 0),\n    (0, 0, 0),\n    (100, 200, 300),\n])\ndef test_add(a, b, expected):\n    assert add(a, b) == expected\n```\n\n### Exception Testing\n\n```python\n# tests\u002Ftest_validation.py\nimport pytest\n\ndef validate_age(age: int) -> None:\n    if age \u003C 0:\n        raise ValueError(\"age must be non-negative\")\n\ndef test_raises_on_negative_age():\n    with pytest.raises(ValueError, match=\"must be non-negative\"):\n        validate_age(-1)\n```\n\n## Pytest Configuration\n\n```ini\n# pytest.ini\n[pytest]\ntestpaths = tests\npython_files = test_*.py\npython_functions = test_*\nmarkers =\n    slow: marks tests as slow (deselect with '-m \"not slow\"')\n    integration: marks tests as integration tests\n    asyncio: marks tests as async\n```\n\n```toml\n# pyproject.toml\n[tool.pytest.ini_options]\ntestpaths = [\"tests\"]\npython_files = [\"test_*.py\"]\npython_functions = [\"test_*\"]\nmarkers = [\n    \"slow: marks tests as slow (deselect with '-m \\\"not slow\\\"')\",\n    \"integration: marks tests as integration tests\",\n    \"asyncio: marks tests as async\",\n]\n```\n\n```bash\npytest                       # run all tests\npytest -v                    # verbose\npytest -x                    # stop on first failure\npytest --tb=short            # shorter traceback\npytest -k \"test_add\"         # run tests matching expression\npytest -m \"not slow\"         # run all except slow tests\npytest --coverage            # with coverage (pytest-cov>=6.0)\n```\n\n### Async Configuration (pytest 8.0+)\n\npytest-asyncio changed its default mode in pytest 8.0. Explicitly set the mode to avoid deprecation warnings:\n\n```ini\n# pytest.ini\n[pytest]\nasyncio_mode = auto\n```\n\n```toml\n# pyproject.toml\n[tool.pytest.ini_options]\nasyncio_mode = \"auto\"\n```\n\n### Parallel Execution (pytest-xdist)\n\n```bash\n# Install: pip install pytest-xdist>=3.6\npytest -n auto          # use all CPU cores\npytest -n 4             # use 4 workers\npytest -n auto --dist loadgroup  # group related tests\n```\n\n## Running Tests\n\n```bash\npytest\npytest tests\u002Ftest_calculator.py\npytest tests\u002Ftest_calculator.py::test_add\npytest -x --tb=short -v\npytest --junitxml=report.xml\npytest --coverage --coverage-report=html\n```\n\n## Debugging Failures\n\n1. Re-run with `-x --tb=long -v` for maximum detail on the first failure.\n2. Use `--pdb` to drop into debugger on failure.\n3. Add `assert 0, repr(variable)` for quick inspection.\n4. Use `-k` filter to run only the failing test.\n5. Expand to full suite once the root cause is fixed.\n\n## Coverage\n\n```bash\npytest --cov=src --cov-report=term-missing\npytest --cov=src --cov-report=xml --cov-report=html\n```\n\n```toml\n# pyproject.toml\n[tool.coverage.run]\nsource = [\"src\"]\nomit = [\"tests\u002F*\"]\n\n[tool.coverage.report]\nshow_missing = true\nfail_under = 80\n```\n\n## CI\u002FCD Integration (GitHub Actions)\n\n```yaml\n# .github\u002Fworkflows\u002Ftest.yml\nname: Test\non: [push, pull_request]\njobs:\n  test:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-python@v5\n        with: { python-version: '3.12' }\n      - run: pip install pytest>=8.3 pytest-cov>=6.0 pytest-xdist>=3.6\n      - run: pytest -n auto --cov=src --cov-report=xml --junitxml=report.xml\n      - uses: actions\u002Fupload-artifact@v4\n        if: always()\n        with: { name: test-results, path: report.xml }\n```\n\n## Flaky Tests Guardrails\n\n- Never use `time.sleep` for synchronization; use `await asyncio.sleep(0)` or `pytest-timeout`.\n- Make temp directories unique per test using `tmp_path` fixture.\n- Avoid real time, network, or filesystem dependencies in unit tests.\n- Use `freezegun` for time-dependent code.\n- Use `pytest-repeat` with `--count 10` to reproduce flakiness.\n\n### Test Data Generation (factory-boy)\n\n```python\n# tests\u002Ffactories.py\nimport factory\nfrom myapp.models import User\n\nclass UserFactory(factory.Factory):\n    class Meta:\n        model = User\n\n    name = factory.Faker(\"name\")\n    email = factory.Faker(\"email\")\n    age = factory.Faker(\"random_int\", min=18, max=90)\n\n# tests\u002Ftest_user_service.py\ndef test_creates_user():\n    user = UserFactory()  # generates fake but deterministic data\n    assert user.name is not None\n    assert user.age >= 18\n```\n\n## Test Case Design Patterns\n\nApply these systematic patterns before writing test code to ensure robust coverage beyond the happy path.\n\n### 1. Boundary Value Analysis\nTest at the edges of valid input domains: empty, zero, maximum, null, and just-outside valid ranges.\n\n```python\n# tests\u002Ftest_validator.py\nimport pytest\n\n@pytest.mark.parametrize(\"input,expected_error\", [\n    (\"\", ValueError),                     # empty string\n    (None, TypeError),                    # null boundary\n    (\"a\" * 10001, ValueError),            # length overflow\n    (\"\u003Cscript>alert(1)\u003C\u002Fscript>\", ValueError),  # security boundary\n])\ndef test_validate_input_boundary(input, expected_error):\n    with pytest.raises(expected_error):\n        validate_input(input)\n```\n\n### 2. Negative \u002F Error Case Testing\nVerify the system behaves correctly under invalid or unexpected conditions.\n\n```python\n# tests\u002Ftest_calculator.py\ndef test_divide_by_zero_raises():\n    with pytest.raises(ZeroDivisionError, match=\"division by zero\"):\n        divide(10, 0)\n\ndef test_parse_int_rejects_non_numeric():\n    with pytest.raises(ValueError):\n        parse_int(\"not-a-number\")\n```\n\n### 3. State-Based Testing\nFor objects with internal state, verify transitions between states are correct and irreversible where expected.\n\n```python\n# tests\u002Ftest_connection.py\ndef test_connection_state_transitions():\n    conn = Connection()\n    assert conn.state == \"closed\"\n    conn.open()\n    assert conn.state == \"open\"\n    conn.close()\n    assert conn.state == \"closed\"\n    # Idempotency check\n    conn.close()\n    assert conn.state == \"closed\"\n```\n\n## Common Test Smells to Avoid\n\n- **Assertion Roulette**: Many assertions without descriptive messages, making failure diagnosis ambiguous. *Fix: Use `pytest` assertion introspection with clear variable names.*\n- **Happy Path Bias**: Only testing successful scenarios, leaving error paths uncovered. *Fix: Ensure `pytest.raises` for exceptions, test `None`\u002Fempty\u002Fzero inputs.*\n- **Mock Overdose**: Too many mocks hiding integration issues or coupling tests to implementation. *Fix: Mock only at architectural boundaries (I\u002FO, external services), not internal collaborators.*\n- **The Free Ride**: Tests that execute code but assert nothing meaningful (e.g., `assert response` without checking content). *Fix: Every test must have at least one specific, falsifiable assertion.*\n- **Obscure Test**: Long, complex test methods with no clear arrange\u002Fact\u002Fassert structure. *Fix: Follow AAA (Arrange-Act-Assert), use descriptive test names.*\n- **Flaky Test**: Non-deterministic results from time, order, or network dependencies. *Fix: Use `freezegun`, `tmp_path`, fixed seeds, fixture isolation.*\n\n## Best Practices\n\n### DO\n\n- Keep tests deterministic and isolated\n- Use fixtures for setup\u002Fteardown instead of `setup_method`\u002F`teardown_method`\n- Use `tmp_path` fixture for temporary files\n- Separate unit vs integration tests in markers or directory structure\n- Use `parametrize` to cover edge cases\n- Use `pytest.approx()` for floating-point comparisons\n- Prefer `assert` over `self.assertEqual` (pytest style)\n\n### DON'T\n\n- Don't depend on real time, network, or external services in unit tests\n- Don't use `time.sleep` for synchronization\n- Don't use global state that leaks between tests\n- Don't test implementation details (private methods prefixed with `_`)\n- Don't write overly large test functions — test one behavior per test\n\n### Common Pitfalls\n\n- **Leaking fixture state** → Use `yield` fixtures with teardown after yield.\n- **Relying on real time** → Use `freezegun` or pass a clock dependency.\n- **Flaky async tests** → Use `pytest-asyncio` with `@pytest.mark.asyncio`.\n- **Global state pollution** → Reset singletons and module-level state in fixtures.\n- **Over-mocking** → Prefer integration tests for core logic; mock only external boundaries.\n- **Missing coverage config** → Add `--cov` with fail-under in CI.\n- **Slow test suite** → Mark slow tests with `@pytest.mark.slow` and separate in CI.\n\n## Optional Appendix: Property-Based Testing\n\nOnly use if the project already supports Hypothesis.\n\n- **Hypothesis**: property-based testing for Python.\n\n```python\nfrom hypothesis import given, strategies as st\n\ndef add(a: int, b: int) -> int:\n    return a + b\n\n@given(a=st.integers(), b=st.integers())\ndef test_add_is_commutative(a, b):\n    assert add(a, b) == add(b, a)\n```\n\n## Alternatives to pytest\n\n- **unittest**: built-in, xUnit-style, compatible with pytest runner.\n- **nose2**: plugin-based successor to nose.\n- **doctest**: embedded tests in docstrings, best for simple validation.\n","# Python Testing (Agent Skill)\n\nAgent-focused testing workflow for modern Python (3.10+) using pytest, the industry-standard test framework.\n\n## When to Use\n\n- Writing new Python tests or fixing existing tests\n- Designing unit\u002Fintegration test coverage for Python components\n- Adding test coverage, CI gating, or regression protection\n- Configuring pytest workflows for consistent execution\n- Investigating test failures or flaky behavior\n- Testing async code, CLI tools, or web frameworks\n\n### When NOT to Use\n\n- Implementing new product features without test changes\n- Large-scale refactors unrelated to test coverage or failures\n- Performance tuning without test regressions to validate\n- Non-Python projects or non-test tasks\n\n### Stop Conditions — When to ASK instead of generating\n\nBefore generating any test code, STOP and ask the user if:\n- The code under test has **zero testability** (no DI, global mutable state, hard-coded external calls, no interfaces)\n- **No test framework** is detected in the project (no `pytest.ini`, `pyproject.toml` test config, `conftest.py`)\n- The request is **ambiguous**: \"test my app\" or \"add tests\" without specifying files or components\n- A **required test dependency** (`pytest`, `pytest-asyncio`, `pytest-cov`) is not installed\n- The test would require **secrets, real credentials, or production database access**\n\n## Core Concepts\n\n- **TDD loop**: red → green → refactor (tests first, minimal fix, then cleanups).\n- **Isolation**: prefer dependency injection and fixtures over global state.\n- **Test layout**: `tests\u002Funit`, `tests\u002Fintegration`, `tests\u002Fconftest.py`, `tests\u002Ftestdata\u002F`.\n- **Fixtures**: pytest's dependency injection mechanism for setup\u002Fteardown.\n- **Parametrization**: `@pytest.mark.parametrize` for testing multiple inputs.\n- **CI signal**: run subset first, then full suite with `--tb=short -x`.\n\n## Agent Execution Protocol\n\nWhen this skill is activated, follow this exact execution sequence:\n\n### Phase 1: Context Analysis\nBefore writing any test code:\n1. Identify the Python version (3.10+) and test framework (pytest preferred).\n2. Check for existing test files (`tests\u002F`, `*_test.py`, `test_*.py`) to infer naming conventions.\n3. Analyze the code under test: identify public API surface, side effects, I\u002FO boundaries (DB, HTTP, filesystem), and async\u002Fawait usage.\n4. Determine request type: (a) new tests, (b) fixing broken tests, (c) coverage improvement, (d) flaky test diagnosis.\n\n### Phase 2: Strategy Selection\nBased on Phase 1, select the appropriate strategy:\n- **Pure functions \u002F value objects**: unit tests only, no mocks needed. Use `pytest.mark.parametrize` for multiple cases.\n- **External dependencies (DB, HTTP, filesystem)**: use `unittest.mock`, `pytest.monkeypatch`, or `responses`\u002F`pytest-httpx`; prefer `tmp_path` for filesystem.\n- **Async code**: use `pytest-asyncio` with `@pytest.mark.asyncio` and `asyncio_mode = auto`.\n- **Web frameworks (Django\u002FFastAPI\u002FFlask)**: use framework-specific test clients (`django.test.Client`, `TestClient`).\n\n### Decision Tree (Complex Scenarios)\n\n```text\nQ1: External I\u002FO (DB, HTTP, filesystem, network)?\n  → Yes → Q2\n  → No  → Pure unit test, no mocks needed\n\nQ2: Mockable at code boundary (DI, interface, parameter injection)?\n  → Yes → Mock at boundary (unittest.mock, monkeypatch, responses)\n  → No  → Q3\n\nQ3: Needs real behavior verification (SQL, transactions)?\n  → Yes → Integration test (Django TestCase, FastAPI TestClient, testcontainers)\n  → No  → Use fake\u002Fstub (in-memory repo, tmp_path files)\n\nQ4: Async code (asyncio)?\n  → Yes → @pytest.mark.asyncio + asyncio_mode = auto\n  → No  → Synchronous test sufficient\n\nQ5: Web\u002Fbrowser rendering?\n  → Yes → Django LiveServerTestCase, Playwright, Selenium\n  → No  → Standard unit test\n```\n\n### Phase 3: Test Case Design\nApply systematic test design before coding:\n1. **Happy path**: normal input → expected output.\n2. **Boundary values**: empty string, zero, `None`, max length, empty collection.\n3. **Error cases**: invalid types, exceptions (`pytest.raises`), permission errors, timeout scenarios.\n4. **State & concurrency**: shared mutable state, race conditions, cache invalidation.\n\n### Phase 4: Code Generation\nOutput tests in this exact structure:\n```\n#### Test Strategy Summary\n- [ ] Scope: Unit \u002F Integration \u002F E2E\n- [ ] Framework: pytest (with asyncio\u002Fmonkeypatch if needed)\n- [ ] Mocking: Yes\u002FNo — tools used\n- [ ] Edge cases covered: \u003Clist>\n\n#### Generated Test Code\n\u003Cfile_path>\n\u003Ccode>\n\n#### Running Commands\n```bash\npytest -x --tb=short -v \u003Cfile_path>\n```\n\n#### Coverage Impact (if applicable)\n- Estimated coverage change: \u003CX%>\n- Command to verify: `pytest --cov=src --cov-report=term-missing`\n```\n\n### Phase 5: Verification Checklist\nBefore completing, verify:\n- [ ] Tests parse without syntax errors (`pytest --collect-only`).\n- [ ] Each test has exactly one logical assertion focus.\n- [ ] Mocks are reset between tests (use `yield` fixtures or `clear` in `setup_method`).\n- [ ] No `time.sleep` used for synchronization (use `freezegun` or `asyncio.sleep`).\n- [ ] Flaky test guardrails applied (isolation, determinism, `tmp_path`).\n\n## TDD Workflow\n\nFollow the RED → GREEN → REFACTOR loop:\n\n1. **RED**: write a failing test that captures the new behavior\n2. **GREEN**: implement the smallest change to pass\n3. **REFACTOR**: clean up while tests stay green\n\n```python\n# tests\u002Ftest_add.py\ndef add(a: int, b: int) -> int:  # Provided by production code.\n    ...\n\ndef test_adds_two_numbers():  # RED\n    assert add(2, 3) == 5\n\n# src\u002Fadd.py\ndef add(a: int, b: int) -> int:  # GREEN\n    return a + b\n\n# REFACTOR: simplify\u002Frename once tests pass\n```\n\n## Code Examples\n\n### Basic Unit Test (pytest)\n\n```python\n# tests\u002Ftest_calculator.py\n\ndef add(a: int, b: int) -> int:  # Provided by production code.\n    ...\n\nclass TestCalculator:\n    def test_adds_two_numbers(self):\n        assert add(2, 3) == 5\n```\n\n### Fixtures (pytest)\n\n```python\n# tests\u002Fconftest.py\nimport pytest\nfrom typing import Optional\n\nclass User:\n    def __init__(self, name: str):\n        self.name = name\n\nclass UserStore:\n    def __init__(self):\n        self._users: list[User] = []\n\n    def seed(self, users: list[User]) -> None:\n        self._users.extend(users)\n\n    def find(self, name: str) -> Optional[User]:\n        return next((u for u in self._users if u.name == name), None)\n\n@pytest.fixture\ndef user_store():\n    store = UserStore()\n    store.seed([User(\"alice\"), User(\"bob\")])\n    return store\n\n# tests\u002Ftest_user_store.py\ndef test_finds_existing_user(user_store):\n    user = user_store.find(\"alice\")\n    assert user is not None\n    assert user.name == \"alice\"\n```\n\n### Mocking (pytest + monkeypatch \u002F unittest.mock)\n\n```python\n# tests\u002Ftest_notifier.py\nfrom unittest.mock import Mock\n\nclass Service:\n    def __init__(self, notifier):\n        self._notifier = notifier\n\n    def publish(self, message: str):\n        self._notifier.send(message)\n\ndef test_sends_notifications():\n    notifier = Mock()\n    service = Service(notifier)\n\n    service.publish(\"hello\")\n\n    notifier.send.assert_called_once_with(\"hello\")\n```\n\n### Async Test (pytest-asyncio)\n\n```python\n# tests\u002Ftest_api.py\nimport pytest\n\nasync def fetch_user(user_id: str) -> dict:\n    return {\"name\": \"alice\"}\n\n@pytest.mark.asyncio\nasync def test_fetches_user_data():\n    user = await fetch_user(\"1\")\n    assert user[\"name\"] == \"alice\"\n\n@pytest.mark.asyncio\nasync def test_handles_errors():\n    with pytest.raises(ValueError):\n        raise ValueError(\"invalid id\")\n```\n\n### Parametrized Test\n\n```python\n# tests\u002Ftest_math.py\nimport pytest\n\ndef add(a: int, b: int) -> int:\n    return a + b\n\n@pytest.mark.parametrize(\"a,b,expected\", [\n    (1, 2, 3),\n    (-1, 1, 0),\n    (0, 0, 0),\n    (100, 200, 300),\n])\ndef test_add(a, b, expected):\n    assert add(a, b) == expected\n```\n\n### Exception Testing\n\n```python\n# tests\u002Ftest_validation.py\nimport pytest\n\ndef validate_age(age: int) -> None:\n    if age \u003C 0:\n        raise ValueError(\"age must be non-negative\")\n\ndef test_raises_on_negative_age():\n    with pytest.raises(ValueError, match=\"must be non-negative\"):\n        validate_age(-1)\n```\n\n## Pytest Configuration\n\n```ini\n# pytest.ini\n[pytest]\ntestpaths = tests\npython_files = test_*.py\npython_functions = test_*\nmarkers =\n    slow: marks tests as slow (deselect with '-m \"not slow\"')\n    integration: marks tests as integration tests\n    asyncio: marks tests as async\n```\n\n```toml\n# pyproject.toml\n[tool.pytest.ini_options]\ntestpaths = [\"tests\"]\npython_files = [\"test_*.py\"]\npython_functions = [\"test_*\"]\nmarkers = [\n    \"slow: marks tests as slow (deselect with '-m \\\"not slow\\\"')\",\n    \"integration: marks tests as integration tests\",\n    \"asyncio: marks tests as async\",\n]\n```\n\n```bash\npytest                       # run all tests\npytest -v                    # verbose\npytest -x                    # stop on first failure\npytest --tb=short            # shorter traceback\npytest -k \"test_add\"         # run tests matching expression\npytest -m \"not slow\"         # run all except slow tests\npytest --coverage            # with coverage (pytest-cov>=6.0)\n```\n\n### Async Configuration (pytest 8.0+)\n\npytest-asyncio changed its default mode in pytest 8.0. Explicitly set the mode to avoid deprecation warnings:\n\n```ini\n# pytest.ini\n[pytest]\nasyncio_mode = auto\n```\n\n```toml\n# pyproject.toml\n[tool.pytest.ini_options]\nasyncio_mode = \"auto\"\n```\n\n### Parallel Execution (pytest-xdist)\n\n```bash\n# Install: pip install pytest-xdist>=3.6\npytest -n auto          # use all CPU cores\npytest -n 4             # use 4 workers\npytest -n auto --dist loadgroup  # group related tests\n```\n\n## Running Tests\n\n```bash\npytest\npytest tests\u002Ftest_calculator.py\npytest tests\u002Ftest_calculator.py::test_add\npytest -x --tb=short -v\npytest --junitxml=report.xml\npytest --coverage --coverage-report=html\n```\n\n## Debugging Failures\n\n1. Re-run with `-x --tb=long -v` for maximum detail on the first failure.\n2. Use `--pdb` to drop into debugger on failure.\n3. Add `assert 0, repr(variable)` for quick inspection.\n4. Use `-k` filter to run only the failing test.\n5. Expand to full suite once the root cause is fixed.\n\n## Coverage\n\n```bash\npytest --cov=src --cov-report=term-missing\npytest --cov=src --cov-report=xml --cov-report=html\n```\n\n```toml\n# pyproject.toml\n[tool.coverage.run]\nsource = [\"src\"]\nomit = [\"tests\u002F*\"]\n\n[tool.coverage.report]\nshow_missing = true\nfail_under = 80\n```\n\n## CI\u002FCD Integration (GitHub Actions)\n\n```yaml\n# .github\u002Fworkflows\u002Ftest.yml\nname: Test\non: [push, pull_request]\njobs:\n  test:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-python@v5\n        with: { python-version: '3.12' }\n      - run: pip install pytest>=8.3 pytest-cov>=6.0 pytest-xdist>=3.6\n      - run: pytest -n auto --cov=src --cov-report=xml --junitxml=report.xml\n      - uses: actions\u002Fupload-artifact@v4\n        if: always()\n        with: { name: test-results, path: report.xml }\n```\n\n## Flaky Tests Guardrails\n\n- Never use `time.sleep` for synchronization; use `await asyncio.sleep(0)` or `pytest-timeout`.\n- Make temp directories unique per test using `tmp_path` fixture.\n- Avoid real time, network, or filesystem dependencies in unit tests.\n- Use `freezegun` for time-dependent code.\n- Use `pytest-repeat` with `--count 10` to reproduce flakiness.\n\n### Test Data Generation (factory-boy)\n\n```python\n# tests\u002Ffactories.py\nimport factory\nfrom myapp.models import User\n\nclass UserFactory(factory.Factory):\n    class Meta:\n        model = User\n\n    name = factory.Faker(\"name\")\n    email = factory.Faker(\"email\")\n    age = factory.Faker(\"random_int\", min=18, max=90)\n\n# tests\u002Ftest_user_service.py\ndef test_creates_user():\n    user = UserFactory()  # generates fake but deterministic data\n    assert user.name is not None\n    assert user.age >= 18\n```\n\n## Test Case Design Patterns\n\nApply these systematic patterns before writing test code to ensure robust coverage beyond the happy path.\n\n### 1. Boundary Value Analysis\nTest at the edges of valid input domains: empty, zero, maximum, null, and just-outside valid ranges.\n\n```python\n# tests\u002Ftest_validator.py\nimport pytest\n\n@pytest.mark.parametrize(\"input,expected_error\", [\n    (\"\", ValueError),                     # empty string\n    (None, TypeError),                    # null boundary\n    (\"a\" * 10001, ValueError),            # length overflow\n    (\"\u003Cscript>alert(1)\u003C\u002Fscript>\", ValueError),  # security boundary\n])\ndef test_validate_input_boundary(input, expected_error):\n    with pytest.raises(expected_error):\n        validate_input(input)\n```\n\n### 2. Negative \u002F Error Case Testing\nVerify the system behaves correctly under invalid or unexpected conditions.\n\n```python\n# tests\u002Ftest_calculator.py\ndef test_divide_by_zero_raises():\n    with pytest.raises(ZeroDivisionError, match=\"division by zero\"):\n        divide(10, 0)\n\ndef test_parse_int_rejects_non_numeric():\n    with pytest.raises(ValueError):\n        parse_int(\"not-a-number\")\n```\n\n### 3. State-Based Testing\nFor objects with internal state, verify transitions between states are correct and irreversible where expected.\n\n```python\n# tests\u002Ftest_connection.py\ndef test_connection_state_transitions():\n    conn = Connection()\n    assert conn.state == \"closed\"\n    conn.open()\n    assert conn.state == \"open\"\n    conn.close()\n    assert conn.state == \"closed\"\n    # Idempotency check\n    conn.close()\n    assert conn.state == \"closed\"\n```\n\n## Common Test Smells to Avoid\n\n- **Assertion Roulette**: Many assertions without descriptive messages, making failure diagnosis ambiguous. *Fix: Use `pytest` assertion introspection with clear variable names.*\n- **Happy Path Bias**: Only testing successful scenarios, leaving error paths uncovered. *Fix: Ensure `pytest.raises` for exceptions, test `None`\u002Fempty\u002Fzero inputs.*\n- **Mock Overdose**: Too many mocks hiding integration issues or coupling tests to implementation. *Fix: Mock only at architectural boundaries (I\u002FO, external services), not internal collaborators.*\n- **The Free Ride**: Tests that execute code but assert nothing meaningful (e.g., `assert response` without checking content). *Fix: Every test must have at least one specific, falsifiable assertion.*\n- **Obscure Test**: Long, complex test methods with no clear arrange\u002Fact\u002Fassert structure. *Fix: Follow AAA (Arrange-Act-Assert), use descriptive test names.*\n- **Flaky Test**: Non-deterministic results from time, order, or network dependencies. *Fix: Use `freezegun`, `tmp_path`, fixed seeds, fixture isolation.*\n\n## Best Practices\n\n### DO\n\n- Keep tests deterministic and isolated\n- Use fixtures for setup\u002Fteardown instead of `setup_method`\u002F`teardown_method`\n- Use `tmp_path` fixture for temporary files\n- Separate unit vs integration tests in markers or directory structure\n- Use `parametrize` to cover edge cases\n- Use `pytest.approx()` for floating-point comparisons\n- Prefer `assert` over `self.assertEqual` (pytest style)\n\n### DON'T\n\n- Don't depend on real time, network, or external services in unit tests\n- Don't use `time.sleep` for synchronization\n- Don't use global state that leaks between tests\n- Don't test implementation details (private methods prefixed with `_`)\n- Don't write overly large test functions — test one behavior per test\n\n### Common Pitfalls\n\n- **Leaking fixture state** → Use `yield` fixtures with teardown after yield.\n- **Relying on real time** → Use `freezegun` or pass a clock dependency.\n- **Flaky async tests** → Use `pytest-asyncio` with `@pytest.mark.asyncio`.\n- **Global state pollution** → Reset singletons and module-level state in fixtures.\n- **Over-mocking** → Prefer integration tests for core logic; mock only external boundaries.\n- **Missing coverage config** → Add `--cov` with fail-under in CI.\n- **Slow test suite** → Mark slow tests with `@pytest.mark.slow` and separate in CI.\n\n## Optional Appendix: Property-Based Testing\n\nOnly use if the project already supports Hypothesis.\n\n- **Hypothesis**: property-based testing for Python.\n\n```python\nfrom hypothesis import given, strategies as st\n\ndef add(a: int, b: int) -> int:\n    return a + b\n\n@given(a=st.integers(), b=st.integers())\ndef test_add_is_commutative(a, b):\n    assert add(a, b) == add(b, a)\n```\n\n## Alternatives to pytest\n\n- **unittest**: built-in, xUnit-style, compatible with pytest runner.\n- **nose2**: plugin-based successor to nose.\n- **doctest**: embedded tests in docstrings, best for simple validation.\n",{"name":5,"origin":24,"description":25},"ECC","Use ONLY when user explicitly requests Python test code, pytest configuration,\ntest failure diagnosis, or coverage improvement for Python projects.\n\nTriggers: \"write test\", \"pytest\", \"unit test python\", \"coverage python\",\n\"flaky test python\", \"mock python\", \"test fixture\", \"parametrize\", \"factory boy\",\n\"freezegun\", \"pytest-asyncio\", \"pytest-cov\".\n\nDo NOT activate for: general Python coding without test context, linting (flake8\u002Fruff),\ntype checking (mypy), or non-test package management (pip install general).\n","main","021f5cbe02157229460a577e9a585f2da6d78cb0",".specify\u002Ftemplates\u002Fpassive-skills\u002Fpython-testing","https:\u002F\u002Fgithub.com\u002Fchenziyang110\u002Flaunchdeck","https:\u002F\u002Fgithub.com\u002Fchenziyang110","2026-08-07 18:10:54",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add chenziyang110\u002Flaunchdeck --skill python-testing",{"tool":38,"command":39},"bunx","bunx skills add chenziyang110\u002Flaunchdeck --skill python-testing",{"tool":41,"command":42},"pnpm","pnpm dlx skills add chenziyang110\u002Flaunchdeck --skill python-testing","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fchenziyang110\u002Flaunchdeck\u002Fblob\u002Fmain\u002F.specify\u002Ftemplates\u002Fpassive-skills\u002Fpython-testing\u002FSKILL.md",true,[],[47,54,60,66,73,82],{"skillNo":48,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":19},"01M7875F3HQ1GF5F6BR36KY3JE","launchdeck-agent","Codex host adapter contract fixture for Launchdeck.","https:\u002F\u002Fgithub.com\u002Fchenziyang110\u002Flaunchdeck\u002Fblob\u002Fmain\u002Ftest\u002Ffixtures\u002Fagent-hosts\u002Fcodex\u002Fskill\u002FSKILL.md",[],[],{"skillNo":55,"name":49,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":19},"01M7875DV2DQR33K1NFJHKAMZP","Claude host adapter contract fixture for Launchdeck.","https:\u002F\u002Fgithub.com\u002Fchenziyang110\u002Flaunchdeck\u002Fblob\u002Fmain\u002Ftest\u002Ffixtures\u002Fagent-hosts\u002Fclaude\u002Fskill\u002FSKILL.md",[],[],{"skillNo":61,"name":49,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M78759JQ7A6FQ8KDQTNYS3X9","Use this skill aggressively for local project lifecycle operations even when the user does not mention Launchdeck: start this project, run the dev server, dev, build, test, restart service, stop service, show logs, inspect ports, port is occupied, clean cache; and when the user explicitly asks to configure this local project for Launchdeck or create or generate a project-adapted `.launchdeck.yml`, including 为这个项目生成 Launchdeck 配置. Do not use for ordinary code edits, docs-only work, general explanations, API design discussion, or production deployment unless the user also asks to operate or configure a local project or service.","https:\u002F\u002Fgithub.com\u002Fchenziyang110\u002Flaunchdeck\u002Fblob\u002Fmain\u002Fagent\u002Finstaller-payload\u002Fskill\u002Flaunchdeck-agent\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M78753ZJQ7G2CZT1W1G8WRJV","zig-testing","Use ONLY when user explicitly requests Zig test code, built-in test runner configuration,\ntest failure diagnosis, or coverage for Zig projects.\n\nTriggers: \"write test zig\", \"zig test\", \"testing.allocator\", \"zig coverage\",\n\"comptime test\", \"zig expectError\", \"zig snapshot test\", \"zig fuzz\".\n\nDo NOT activate for: general Zig coding without test context, build.zig configuration\nfor non-test targets, Zig compiler errors, or Zig build system setup.","https:\u002F\u002Fgithub.com\u002Fchenziyang110\u002Flaunchdeck\u002Fblob\u002Fmain\u002F.specify\u002Ftemplates\u002Fpassive-skills\u002Fzig-testing\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":77,"licenseFileUrl":78,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M78750JXY4Z5D5W1EX3PQ31Z","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fchenziyang110\u002Flaunchdeck\u002Fblob\u002Fmain\u002F.specify\u002Ftemplates\u002Fpassive-skills\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fchenziyang110\u002Flaunchdeck\u002Fblob\u002Fmain\u002F.specify\u002Ftemplates\u002Fpassive-skills\u002Fwebapp-testing\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M7874X2T83EQQFRCEY5SJJVC","verification-before-completion","Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always","https:\u002F\u002Fgithub.com\u002Fchenziyang110\u002Flaunchdeck\u002Fblob\u002Fmain\u002F.specify\u002Ftemplates\u002Fpassive-skills\u002Fverification-before-completion\u002FSKILL.md",[],[]]