api-contract-testing
Что он делает
Этот инструмент помогает проверить, не вызывают ли изменения в контракте API (правилах взаимодействия систем) проблем. Он гарантирует, что поставщик API и его потребители продолжают работать вместе после изменений.
Когда использовать
- ✓Когда меняется поле или правило в ответе API.
- ✓Когда код собирается без ошибок, но взаимодействие систем ломается во время работы.
- ✓Когда нужно понять, нарушает ли изменение совместимость или это просто новая функция.
Ссылка на скилл
https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/api-contract-testing/SKILL.mdСкопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.
Как использовать
Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.
Готовое сообщение для вставки
Для Claude Code, Codex или Cursor: запустите в папке проекта, и скилл установится.
Скачайте SKILL.md и положите его в папку скиллов вашего агента.
Пример запроса к вашему ИИ
“Проанализируй это изменение API. Перечисли затронутых потребителей и поддерживаемые комбинации версий. Добавь локальные контрактные тесты для корректных, некорректных и ошибочных ответов, используя существующий тестовый раннер. Сообщи, какие проверки реально запущены и что еще требует подтверждения.”
5 новых скиллов в неделю. 1 минута чтения.
Как это работает
Инструмент сравнивает официальное описание API с его фактическим поведением и создает небольшие тесты на тестовых данных. Так можно убедиться, что изменения не нарушают взаимодействие между системами, которые используют API.
Технический текст (оригинальный SKILL.md)
Оригинальный текст автора на английском, прямо с GitHub.
API Contract Testing
Overview
Turn an API change into explicit provider and consumer checks. Start from the actual contract and affected clients, then verify wire-level behavior rather than relying on generated types or a successful build. Default to local fixtures and existing test tools; this skill does not provision a testing service.
When to Use
- A response field, endpoint, event schema or error envelope changes.
- A client and server build successfully but disagree at runtime.
- A team needs to distinguish a breaking change from a compatible extension.
- A reported regression needs a minimal provider/consumer reproduction.
Do not use this as authorization to call production endpoints, bypass access controls or publish a new API version.
How It Works
1. Bind the contract and scope
Identify the provider, transport, contract source and version, known consumers and the requested behavior. Read the real OpenAPI/JSON Schema/protobuf definition or documented examples and the corresponding server/client code. Record missing consumers and stale specifications as coverage gaps; do not invent interfaces or claim complete coverage from one client.
Keep these distinct: documented schema, actual provider output, generated client types and runtime parsing. A type assertion alone is not validation. Preserve the existing protocol and test runner instead of introducing a new platform by default.
2. Classify the change
Review fields, requiredness, nullability, enum values, status codes, headers, content type, pagination and error behavior. Inspect whether clients tolerate extra fields and unknown enum values. Even an added optional field can break a strict consumer. Explicitly identify affected versions and assumptions before calling a change compatible.
For events, include duplicate delivery, ordering and version envelopes. For request changes, check serialization and server validation as well as responses.
3. Build a small test matrix
Use deterministic synthetic fixtures for:
- Valid success, including optional and empty values.
- Missing required fields, wrong types and explicit nulls.
- Extra fields and unknown enums according to the actual compatibility policy.
- Declared error envelopes, non-success statuses and malformed bodies.
- Old consumer against new provider and new consumer against retained old provider, where those combinations are supported.
Assert the behavior promised by the contract. Do not silently coerce malformed values or make the fixture match a defect just to get a passing test.
4. Verify each boundary
Run the existing schema validator against fixtures. Exercise the provider handler locally and pass its serialized result through the real consumer parser. Check failure cases reject or map errors as specified. Use an authorized isolated integration environment only when fixtures cannot establish the required property; report that boundary explicitly.
A mock verifies assumptions encoded in the mock. It does not establish that the real provider implements them. Record exact commands, fixture versions and observed outcomes separately from unrun checks.
5. Report and hand off
Deliver the change classification, affected consumers, test matrix, observed failures, minimal reproduction and remaining coverage gaps. For a breaking change, propose versioning, a compatibility adapter or a staged migration with owners and rollback criteria. Deployment and consumer migration require their own task authorization.
Example
Synthetic documented response:
{"id":"invoice-demo","amount_minor":1250,"currency":"EUR"}
Contract: id and currency are strings; amount_minor is a non-negative integer in minor units. This fixture does not represent an actual customer or payment.
| Fixture change | Expected check |
|---|---|
amount_minor becomes "1250" |
Runtime parser rejects the string; compile-time generated types alone cannot detect wire drift. |
amount_minor is missing or null |
Reject when the field is required and non-nullable. |
Extra display_label field |
Verify the consumer's documented extra-field policy before declaring compatibility. |
| HTTP error with an HTML body | Produce the declared transport/protocol error, rather than treating it as a valid invoice. |
Reusable prompt:
Review this API change against the actual contract and supplied client/server code.
…
Частые вопросы
Что такое «контракт API»?
Это документ, который описывает, как одна система (поставщик) взаимодействует с другой (потребитель). В нем указаны форматы данных, конечные точки и ожидаемые правила.
Почему не использовать реальные данные из рабочей среды?
Реальные данные могут раскрыть конфиденциальную информацию, и при их использовании нет гарантии, что проверены все сценарии ошибок. Минимальные синтетические данные безопаснее и эффективнее для тестирования.
Инструмент занимается развертыванием или управлением API?
Нет, он помогает планировать и проверять контракты API. Он не развертывает API и не управляет тестовыми сервисами.
Подробности
Оригинальное описание автора
Design and review API contract tests across providers and consumers. Use for schema changes, compatibility regressions and client integration failures.
Популярность
- Звёзды на GitHub
- 48k
- Место в рейтинге
- #3765
- Лицензия
- MIT
- Обновлён
- 15.10.2026
Комментарии
- …
Другие скиллы из этого репозитория
00-andruia-consultant
48kПомогает агенту начинать или улучшать ИИ-проекты: анализирует код, подбирает инструменты и составляет план на испанском.
007
48kАгент проводит аудит безопасности и моделирование угроз для защиты проектов.
10-andruia-skill-smith
48kПомогает агенту создавать и улучшать ИИ-инструменты: описание работы, документация и проверка структуры.
20-andruia-niche-intelligence
48kАгент составляет обзор отрасли: контекст, правила, паттерны использования и риски по надёжным источникам.
Похожие скиллы
test-driven-development
311kУчит агента сначала писать падающий тест, увидеть, что он падает, и только затем писать минимальный код, который его проходит, прежде чем создавать любую функцию или исправление.
verification-before-completion
311kУчит агента запускать настоящие проверки и читать их вывод, прежде чем утверждать, что задача, исправление или сборка готовы или проходят.
migrate-to-shoehorn
310kЗаменяет рискованные приведения типов в тестовых файлах на библиотеку shoehorn, чтобы тесты могли использовать неполные данные и проходить проверку типов.