test-strategy — правило для Claude Code: тесты и установка
Правило test-strategy для Claude Code задаёт структуру тест-плана и требования к автотестам — от граничных случаев до проверки ошибок. Описывает тесты, добавляемые или изменяемые вместе с кодом.
MIT ★ 359 обновлён 2025-12-01
.claude/rules/test-strategy.mdЧто делает test-strategy
Перед разработкой тестов нужно составить таблицу сценариев с входными условиями, ожидаемым результатом и типом проверки. Она должна охватывать штатные ситуации, ошибки и границы вроде нуля, минимума, максимума, пустого значения и NULL. Если кандидат не подходит спецификации, причину записывают в примечаниях.
Каждый сценарий из таблицы становится автотестом. Правило требует не меньше тестов на ошибки, чем на обычные случаи, комментарии Given/When/Then и проверку типа и сообщения исключения. Цель — 100% покрытия ветвей; если это недостижимо, нужно описать непокрытые ветви и их влияние. Для сбоев внешних зависимостей предусмотрены заглушки или моки.
В конце документации или PR нужно указать команду запуска и способ получить покрытие. Даже если внешних зависимостей нет, правило требует моделировать сбои с помощью моков. Для Claude Code файл устанавливают по пути .claude/rules/test-strategy.md; для Windsurf указан .devin/rules/test-strategy.md.
Какие задачи решает
- составить таблицу тестовых сценариев до написания тестов
- проверить граничные значения и некорректные входные данные
- добавить автотесты для ошибок и сбоев зависимостей
- зафиксировать непокрытые ветви и причины
- описать запуск тестов и получение отчёта покрытия
Примеры запросов агенту
- Составь таблицу сценариев для тестов этой функции, включая ошибки и граничные значения.
- Добавь автотесты по таблице и проверь типы и сообщения исключений.
- Укажи команду запуска тестов и способ получить покрытие в описании PR.
Как установить test-strategy
Вручную: положить файлы
.claude/rules/test-strategy.mdПоле paths во frontmatter ограничивает файлы
AGENTS.md
Codex читает AGENTS.md: вставьте текст правила туда
Вручную: положить файлы
.cursor/rules/test-strategy.mdcВо frontmatter: description, globs, alwaysApply
Вручную: положить файлы
.github/instructions/test-strategy.instructions.mdПоле applyTo задаёт, к каким файлам применять
Вручную: положить файлы
.devin/rules/test-strategy.mdВручную: положить файлы
.clinerules/test-strategy.mdПо шагам, с командами для каждой платформы: AGENTS.md и CLAUDE.md: что это, кто читает и какой выбрать
Вопросы о test-strategy
Как установить test-strategy в Claude Code?
Добавьте правило в проект по пути .claude/rules/test-strategy.md.
Что делает test-strategy?
Правило задаёт процесс подготовки таблицы сценариев, реализации автотестов и проверки покрытия. Оно также требует явно проверять ошибки и исключения.
Какие тестовые случаи требует test-strategy?
Нужны штатные, ошибочные и граничные случаи, а также проверки неверного типа или формата. Сбои API, базы данных и других внешних зависимостей проверяют, когда это применимо.
Исходный текст
test-strategy.md · MIT
--- trigger: model_decision description: Applied when implementing or modifying test code. Rules for creating test perspective tables (equivalence partitioning/boundary values), Given/When/Then format, and coverage targets globs: --- ## Test Strategy Rules These rules define the testing process that must be followed when implementing or modifying test code. A test task is not considered complete unless all of the following steps are satisfied. --- ## 1. Test Perspective Table (Equivalence Partitioning / Boundary Values) 1. Before starting any test work, you must first present a "test perspectives table" in Markdown format. 2. The table must include at least the following columns: `Case ID`, `Input / Precondition`, `Perspective (Equivalence / Boundary)`, `Expected Result`, `Notes`. 3. Rows must cover normal cases, error cases, and boundary value cases. For boundary values, include at minimum `0 / minimum / maximum / ±1 / empty / NULL`. Boundary value candidates (0 / minimum / maximum / ±1 / empty / NULL) that have no meaning in the specification may be omitted with the reason stated in `Notes`. 4. If you notice missing perspectives later, update the table after self-review and add necessary cases. 5. Note that for minor modifications to existing tests (message adjustments, minor expected value corrections, etc.) where no new branches or constraints are added, creating/updating the test perspective table is optional. ### Template Example | Case ID | Input / Precondition | Perspective (Equivalence / Boundary) | Expected Result | Notes | |--------|----------------------|---------------------------------------|----------------------------------------------|-------| | TC-N-01 | Valid input A | Equivalence – normal | Processing succeeds and returns expected value | - | | TC-A-01 | NULL | Boundary – NULL | Validation error (required field) | - | | ... | ... | ... | ... | ... | --- ## 2. Test Code Implementation Policy 1. Implement **all** cases listed in the above table as automated tests. 2. **Always include failure cases equal to or more than normal cases** (validation errors, exceptions, external dependency failures, etc.). 3. Cover the following perspectives in tests: - Normal cases (main scenarios) - Error cases (validation errors, exception paths) - Boundary values (0, minimum, maximum, ±1, empty, NULL) - Invalid type/format inputs - External dependency failures (API / DB / messaging, etc. when applicable) - Exception types and error messages 4. Furthermore, aim for 100% branch coverage and design additional cases yourself as needed. 100% branch coverage is a target; if not reasonably achievable, at minimum cover branches with high business impact and main error paths. If there are uncovered branches, state the reason and impact in `Notes` or the PR body. --- ## 3. Given / When / Then Comments Each test case must have the following comment format. ```text // Given: Preconditions // When: Operation to execute // Then: Expected result/verification ``` Write comments directly above the test code or within steps to keep the scenario traceable for readers. --- ## 4. Exception/Error Verification 1. For cases where exceptions occur, explicitly verify the exception **type** and **message**. 2. For validation error cases, also verify error codes and field information if available. 3. When simulating external dependency failures, use stubs/mocks to verify that expected exceptions/retries/fallbacks are called. --- ## 5. Execution Commands and Coverage 1. At the end of test implementation, always document the **execution command** and **coverage acquisition method** at the end of documentation or PR body. - Examples: `npm run test`, `pnpm vitest run --coverage`, `pytest --cov=...` 2. Check branch coverage and statement coverage, aiming for 100% branch coverage (if not reasonably achievable, prioritize branches with high business impact and main error paths). 3. Attach coverage report verification results (screenshots or summaries) where possible. --- ## 6. Operational Notes 1. Test diffs that do not conform to this rule will be rejected in review. 2. Even when there are no external dependencies, **use mocks to simulate failures** for failure cases. 3. When new branches or constraints are added to the test target specification, update the test perspective table and test code simultaneously. 4. If there are cases that are difficult to automate, clearly state the reason and alternative means, and reach agreement with reviewers. Alternative means should include at minimum: target functionality and risks, manual verification procedures, expected results, and how to save logs or screenshots. 5. As a rule, PRs containing meaningful changes to production code (feature additions, bug fixes, refactoring that may affect behavior) must always include corresponding automated test additions or updates. 6. If adding/updating tests is reasonably difficult, clearly state the reason and alternative verification procedures (manual test procedures, etc.) in the PR body and reach agreement with reviewers. 7. Even for refactoring not intended to change behavior, verify that the changed areas are sufficiently covered by existing tests, and add tests if insufficient. --- Follow this rule and always self-check for missing perspectives before designing and implementing tests.
© kinopeee · MIT · kinopeee/windsurf-antigravity-rules