К основному содержанию
скилл CX Codex

testing-integration — скилл для Claude Code: тесты API и установка

Скилл testing-integration помогает проверять границы API и сервисов: интеграционные тесты, контракты Pact и валидацию схем Zod. Включается при работе с тестами API или взаимодействием сервисов.

MIT 131 установок ★ 305 обновлён 2026-11-07

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add yonatangross/orchestkit --skill testing-integration -a claude-code
Открыть на GitHub

Что делает testing-integration

Скилл содержит правила и справочные материалы для тестирования API, баз данных и React-компонентов. В него также входят проверки контрактов Pact, property-based и stateful-тесты, а также валидация схем Zod. Для сложных сценариев с эмуляцией API он отсылает к субагенту emulate-engineer.

Для тестов с реальными зависимостями описан Testcontainers: он поднимает временные Docker-контейнеры для Postgres, Redis, Kafka или S3-совместимого хранилища и удаляет их после теста. В примере для Node.js используются @testcontainers/postgresql и Vitest. Для этого сценария нужен Docker: контейнеры запускаются именно в нём.

Какие задачи решает

  • проверить API-эндпоинт интеграционным тестом
  • сверить контракты между сервисами через Pact
  • проверить работу слоя базы данных
  • проверить схемы Zod и свойства данных
  • запустить тест с реальным Postgres в контейнере

Примеры запросов агенту

  • Напиши интеграционный тест для API-эндпоинта.
  • Добавь проверку контракта Pact между сервисами.
  • Составь тест для UserRepository с Postgres в Testcontainers.

Как установить testing-integration

1Через Skills CLI (Vercel)

npx skills add yonatangross/orchestkit --skill testing-integration -a claude-code

2Вручную: положить файлы

~/.claude/skills/testing-integration/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/testing-integration/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о testing-integration

Как установить testing-integration в Claude Code?

Выполните npx skills add yonatangross/orchestkit --skill testing-integration -a claude-code. Файл скилла находится по пути ~/.claude/skills/testing-integration/SKILL.md.

Что делает testing-integration?

Скилл помогает писать интеграционные и контрактные тесты для API, сервисов и баз данных. Включает материалы по Pact, property-based тестам и схемам Zod.

Нужен ли Docker для тестов с Testcontainers?

Да. Testcontainers запускает временные Docker-контейнеры с зависимостями, например Postgres или Redis, и останавливает их после теста.

Исходный текст

SKILL.md · MIT
---
name: testing-integration
license: MIT
compatibility: "Claude Code 2.1.277+."
description: "Integration and contract tests: API endpoints, databases, Pact contracts, property-based tests, Zod validation. Use when testing API or service boundaries."
user-invocable: false
disable-model-invocation: false
targets:
  - library: "@pact-foundation/pact"
    version: ">=17.1.4"
  - library: "testcontainers"
    version: ">=12.2.0"
metadata:
  owner-agent: "test-generator"
  category: document-asset-creation
  version: "2.1.0"
  author: "OrchestKit"
  complexity: "medium"
  tags: "testing, integration, contract, pact, property, zod, api"
allowed-tools: "Read Glob Grep WebFetch WebSearch"
path_patterns: ["**/integration/**", "**/testcontainers/**", "docker-compose.test.*"]
---

# Integration & Contract Testing

Focused patterns for testing API boundaries, cross-service contracts, component integration, database layers, property-based verification, and schema validation.

## Quick Reference

> For complex emulate setups (full config generation, webhook HMAC, CI per-worker port isolation), delegate to the [`emulate-engineer`](../../agents/emulate-engineer.md) subagent. Pairs with the `emulate-seed` skill.

| Area | Rule / Reference | Impact |
|------|-----------------|--------|
| **Stateful API testing (emulate)** | `rules/emulate-stateful-testing.md` | **HIGH** |
| API endpoint tests | `rules/integration-api.md` | HIGH |
| React component integration | `rules/integration-component.md` | HIGH |
| Database layer testing | `rules/integration-database.md` | HIGH |
| Zod schema validation | `rules/validation-zod-schema.md` | HIGH |
| Pact contract testing | `rules/verification-contract.md` | MEDIUM |
| Stateful testing (Hypothesis) | `rules/verification-stateful.md` | MEDIUM |
| Evidence & property-based | `rules/verification-techniques.md` | MEDIUM |

### References

| Topic | File |
|-------|------|
| **House rules not documented upstream** | `references/ork-delta.md` |
| Consumer-side Pact tests | `references/consumer-tests.md` |
| Hypothesis strategies guide | `references/strategies-guide.md` |

### Checklists

| Checklist | File |
|-----------|------|
| Contract testing readiness | `checklists/contract-testing-checklist.md` |
| Property-based testing | `checklists/property-testing-checklist.md` |

### Scripts & Templates

| Script | File |
|--------|------|
| Create integration test | `scripts/create-integration-test.md` |

### Examples

| Example | File |
|---------|------|
| Full testing strategy | `examples/orchestkit-test-strategy.md` |

---

## Upstream coverage (do not restate)

This skill wraps Pact, the Pact Broker, and FastAPI testing. It carries only the OrchestKit
delta. Fetch the vendor docs for the topics below instead of restating them here.

| Topic | First-party source |
|-------|--------------------|
| Pact Broker publish CLI, pact versioning and tagging flags | https://docs.pact.io/pact_broker/publishing_and_retrieving_pacts |
| `can-i-deploy`, `record-deployment`, `record-release` | https://docs.pact.io/pact_broker/can_i_deploy |
| Deployment and release recording semantics | https://docs.pact.io/pact_broker/recording_deployments_and_releases |
| Broker webhooks that trigger a provider build on contract change | https://docs.pact.io/pact_broker/webhooks |
| Consumer version selector syntax (`mainBranch`, `deployedOrReleased`, `matchingBranch`) | https://docs.pact.io/pact_broker/advanced_topics/consumer_version_selectors |
| Pending pact semantics | https://docs.pact.io/pact_broker/advanced_topics/pending_pacts |
| Provider state setup hooks and state endpoint wiring | https://docs.pact.io/getting_started/provider_states |
| FastAPI `TestClient` and `dependency_overrides` for a test database | https://fastapi.tiangolo.com/advanced/testing-dependencies/ |
| GitHub Actions job ordering (`needs:`) and branch filters | https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions |
| QA test-plan paperwork (schedule, roles, defect lifecycle, sign-off tables) | Tracker-owned; no single vendor page covers all four. Defect lifecycle: https://docs.github.com/en/issues/tracking-your-work-with-issues/about-issues . Schedule, roles and sign-off are org process, not a documented product feature. House quality budgets from the retired template survive in `references/ork-delta.md` |

The house subset of those topics stays in this skill and is not routed away:
`rules/verification-contract.md` keeps the two broker commands ork gates on plus the selector
defaults; `checklists/contract-testing-checklist.md` keeps the CI/CD, isolation and security
checkboxes; `references/consumer-tests.md` keeps the business-language provider-state naming
convention and the matcher table. The rules that have no upstream home at all live in
`references/ork-delta.md`.

---

## Stateful API Testing (emulate — FIRST CHOICE)

For GitHub, Vercel, and Google API integration tests, **emulate is the first choice**. It provides full state machines that model real API behavior — not static mocks.

| Tool | Best For |
|------|----------|
| **emulate** | Stateful API tests (GitHub/Vercel/Google) — FIRST CHOICE |
| Pact | Cross-team contract verification |
| MSW | Frontend HTTP mocking (simple request/response) |
| Nock | Node.js unit-level HTTP interception |

See `rules/emulate-stateful-testing.md` for the full decision matrix, seed-start-test-assert pattern, and incorrect/correct examples.

---

## Testcontainers (real dependencies in CI)

When contract tests and emulate aren't enough — e.g. testing against real Postgres, Redis, Kafka, or an S3-compatible store — **Testcontainers** spins up ephemeral Docker containers per test and tears them down afterward. `path_patterns` above already matches `**/testcontainers/**`; use these patterns there.

**Target**: `testcontainers >= 11.0.0` (Node) — v11 (Q1 2026) added named-network auto-cleanup, reusable containers via `.withReuse()`, and first-class Podman support.

### Node.js (testcontainers-node)

```typescript
import { PostgreSqlContainer } from '@testcontainers/postgresql'
import { describe, beforeAll, afterAll, test, expect } from 'vitest'

describe('UserRepository integration', () => {
  let container: Awaited<ReturnType<PostgreSqlContainer['start']>>
  let repo: UserRepository

  beforeAll(async () => {
    container = await new PostgreSqlContainer('postgres:16-alpine')
      .withDatabase('test')
      .withUsername('test')
      .withPassword('test')
      .withReuse()  // v11+ — reuse across runs to speed CI
      .start()

    repo = new UserRepository(container.getConnectionUri())
    await repo.migrate()
  }, 30_000)

  afterAll(async () => {
    await container.stop()
  })

  test('persists and retrieves a user', async () => {
    const created = await repo.create({ email: '[email protected]' })
    const found = await repo.findById(created.id)
    expect(found?.email).toBe('[email protected]')
  })
})
```

### Python (testcontainers-python)

```python
from testcontainers.postgres import PostgresContainer
import pytest

@pytest.fixture(scope="session")
def postgres():
    with PostgresContainer("postgres:16-alpine") as pg:
        yield pg.get_connection_url()

def test_user_repo(postgres):
    repo = UserRepository(postgres)
    repo.migrate()
    user = repo.create(email="[email protected]")
    assert repo.find_by_id(user.id).email == "[email protected]"
```

**Decision matrix**:

| Scenario | Pick |
|----------|------|
| Third-party API (GitHub, Vercel, Google) | emulate |
| Cross-team API contract | Pact |
| Real Postgres / Redis / Kafka integration | **Testcontainers** |
| Just mocking HTTP in a frontend test | MSW |

---

## Quick Start: API Integration Test

### TypeScript (Supertest)

```typescript
import request from 'supertest';
import { app } from '../app';

describe('POST /api/users', () => {
  test('creates user and returns 201', async () => {
    const response = await request(app)
      .post('/api/users')
      .send({ email: '[email protected]', name: 'Test' });

    expect(response.status).toBe(201);
    expect(response.body.id).toBeDefined();
    expect(response.body.email).toBe('[email protected]');
  });

  test('returns 400 for invalid email', async () => {
    const response = await request(app)
      .post('/api/users')
      .send({ email: 'invalid', name: 'Test' });

    expect(response.status).toBe(400);
    expect(response.body.error).toContain('email');
  });
});
```

### Python (FastAPI + httpx)

```python
import pytest
from httpx import ASGITransport, AsyncClient
from app.main import app

@pytest.fixture
async def client():
    async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as ac:
        yield ac

@pytest.mark.asyncio
async def test_create_user(client: AsyncClient):
    response = await client.post(
        "/api/users",
        json={"email": "[email protected]", "name": "Test"}
    )
    assert response.status_code == 201
    assert response.json()["email"] == "[email protected]"
```

---

## Coverage Targets

| Area | Target |
|------|--------|
| API endpoints | 70%+ |
| Service layer | 80%+ |
| Component interactions | 70%+ |
| Contract tests | All consumer-used endpoints |
| Property tests | All encode/decode, idempotent functions |

---

## Key Principles

1. **Test at boundaries** -- API inputs, database queries, service calls, external integrations
2. **Fresh state per test** -- In-memory databases, transaction rollback, no shared mutable state
3. **Use matchers in contracts** -- `Like()`, `EachLike()`, `Term()` instead of exact values
4. **Property-based for invariants** -- Roundtrip, idempotence, commutativity properties
5. **Validate schemas at edges** -- Zod `.safeParse()` at every API boundary
6. **Evidence-backed completion** -- Exit code 0, coverage reports, timestamps

---

## When to Use This Skill

- Writing API endpoint tests (Supertest, httpx)
- Setting up React component integration tests with providers
- Creating database integration tests with isolation
- Implementing Pact consumer/provider contract tests
- Adding property-based tests with Hypothesis
- Validating Zod schemas at API boundaries
- Planning a testing strategy for a new feature or service

## Related Skills

- `ork:testing-unit` — Unit testing patterns, fixtures, mocking
- `ork:testing-e2e` — End-to-end Playwright tests
- `ork:emulate-seed` — Seed configuration authoring for emulate providers
- `ork:database-patterns` — Database schema and migration patterns
- `ork:api-design` — API design patterns for endpoint testing

© OrchestKit · MIT · yonatangross/orchestkit

Похожие скиллы

Все скиллы по теме «Тесты и QA» →
contract-testing kindlmann Скилл contract-testing для Claude Code помогает настроить контрактные тесты Pact между потребителем и провайдером API. Он включается по запросам о Pact, проверке провайдера или can-i-deploy. CX Codex +1 1 400установок api-testing-patterns proffesor-for-testing Скилл api-testing-patterns для Claude Code с готовыми паттернами тестирования REST и GraphQL API: контракты, авторизация, идемпотентность, гонки. Покрывает написание тестов и выбор стратегии. CX Codex +1 618установок api-contract-testing secondsky Скилл api-contract-testing помогает проверять контракты API между микросервисами через Pact и схемы OpenAPI без развёртывания полного сквозного окружения. CX Codex +1 498установок contract-testing-builder patricio0312rev Скилл contract-testing-builder внедряет контрактное тестирование API через Pact, OpenAPI и JSON Schema, чтобы изменения на бэкенде не ломали клиентские сервисы. CX Codex +1 266установок qe-contract-testing proffesor-for-testing Скилл qe-contract-testing для проверки контрактов REST, GraphQL и event-driven API с валидацией схем. Ловит несовместимые изменения и гарантирует, что API не сломает клиентов. CX Codex +1 115установок swagger-contract-testing pactflow Плагин swagger-contract-testing для Claude Code собирает скиллы и агентов для контрактного тестирования в PactFlow: от Pact-тестов до проверок can-i-deploy. ★ 7звёзд репо

Из того же набора86

Весь набор →
figma-design-handoff Скилл figma-design-handoff для Claude Code помогает переносить макеты Figma в код и описывать компоненты. Включается при подготовке дизайн-токенов, разборе Dev Mode или сравнении интерфейса с макетом. CX Codex +1 136установок user-research Скилл user-research для структурированного исследования пользователей: персоны, карты пути, интервью, тестирование юзабилити и card sorting. Помогает понять, что нужно пользователям, и обоснованно проектировать продукт. CX Codex +1 134установок brainstorm Скилл brainstorm собирает варианты решения через параллельных агентов, фильтрует их по реализуемости и помогает сравнить компромиссы. Код он не строит и не чинит. CX Codex +1 133установок setup Скилл setup сканирует проект, определяет стек, советует скиллы и MCP-серверы, а затем считает готовность проекта. Есть режимы повторного сканирования и настройки. CX Codex +1 133установок testing-llm Скилл testing-llm помогает тестировать функции с языковыми моделями: подменять ответы, оценивать качество RAG и проверять структурированный вывод. Включается при разработке тестов для ИИ-функций. CX Codex +1 126установок prioritization Скилл prioritization для ранжирования задач бэклога методами RICE, WSJF, ICE, MoSCoW и анализом альтернативных издержек. Агент подсчитывает баллы, строит сравнительные таблицы и обосновывает выбор между конкурирующими фичами. CX Codex +1 125установок competitive-analysis Скилл competitive-analysis формирует анализ рынка по пяти силам Портера, SWOT-матрицы, профили конкурентов и карты позиционирования. Включается при оценке ниши или подготовке сейлз-батлкард. CX Codex +1 125установок visualize-plan Скилл visualize-plan показывает план изменений в виде схемы «до и после», карты рисков и порядка выполнения. Запускается при разборе плана или изменений в текущей ветке. CX Codex +1 124установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой