Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

pact-contract-testing

БесплатноБез исполняемых скриптовНе проверен

Use whenever two services (a frontend and an API, or two microservices) keep breaking each other's API: set up Pact consumer-driven contract tests, publish…

testlandот testland★ 18 звёзд на GitHub

Об этом скилле

pact-contract-testing

Overview

Pact is a code-first tool for consumer-driven contract tests over HTTP and message integrations (pact-overview). The contract is a side-effect of the consumer's tests - each test documents one request/response pair, and only the parts the consumer actually uses get tested.

The lifecycle has five steps (pact-how-it-works):

  1. Consumer test runs against a Pact mock server using the Pact DSL.
  2. The framework writes a pact file (JSON) capturing every given() → uponReceiving() → withRequest() → willRespondWith() interaction.
  3. The pact file is published to the Pact Broker.
  4. The provider verifies the pact: each recorded request is replayed against the running provider and responses are checked against the contract.
  5. can-i-deploy queries the Broker matrix to confirm the candidate version has a green verification against every consumer/provider already deployed in the target environment (can-i-deploy).

When to use

  • Two or more services communicate over HTTP/JSON or a message bus.
  • The team owns both consumer and provider - Pact requires provider buy-in for verification.
  • You want a safety net richer than schema comparison: contract-by-example asserts what consumers actually use, not the full provider surface.
  • The repo already imports @pact-foundation/pact, pact-jvm-consumer, pact-python, etc., or a .pact/ directory is present.

If the API has no consumers under your control (public or third-party APIs), prefer openapi-contract-diff - schema diffs need no consumer coordination.

Authoring (consumer side)

Install (Node example)

npm install --save-dev @pact-foundation/pact

(Per pact-js.)

Consumer test with PactV3

const { PactV3, MatchersV3 } = require('@pact-foundation/pact');
const { like, eachLike } = MatchersV3;

const provider = new PactV3({
  consumer: 'web-app',
  provider: 'pet-service',
  dir: path.resolve(process.cwd(), 'pacts'),
});

describe('Pet Service consumer', () => {
  it('returns a list of dogs', async () => {
    provider
      .given('I have a list of dogs')
      .uponReceiving('a request for all dogs with the builder pattern')
      .withRequest({
        method: 'GET',
        path: '/dogs',
        headers: { Accept: 'application/json' },
      })
      .willRespondWith({
        status: 200,
        headers: { 'Content-Type': 'application/json' },
        body: eachLike({
          id: like(1),
          name: like('Rex'),
        }),
      });

    await provider.executeTest(async (mockServer) => {
      const response = await fetch(`${mockServer.url}/dogs`);
      expect(response.status).toBe(200);
    });
  });
});

(Adapted from pact-js.)

given() describes a provider state the verifier sets up later. Matchers like like() and eachLike() assert type/shape rather than exact values, so the provider isn't bound to fixture-specific data.

Where pact files are written

By default, PactV3 writes pact files to ./pacts/ relative to the process CWD (pact-js). Each consumer/provider pair produces one JSON file: <consumer>-<provider>.json.

Publishing to the Pact Broker

The Broker is the central registry for pact files and verification results. Publishing happens after the consumer tests pass:

npx pact-broker publish ./pacts \
  --consumer-app-version=$(git rev-parse HEAD) \
  --branch=$(git rev-parse --abbrev-ref HEAD) \
  --broker-base-url=$PACT_BROKER_BASE_URL \
  --broker-token=$PACT_BROKER_TOKEN

The Broker stores (overview):

  • The pact files themselves.
  • Provider verification results per consumer version.
  • Tags and branches that map app versions to lifecycle environments (e.g. production, staging, main).

Tagging by branch + the Git SHA as consumer-app-version is the canonical pattern - can-i-deploy queries the matrix using these identifiers.

Provider verification

const { Verifier } = require('@pact-foundation/pact');

new Verifier({
  providerBaseUrl: 'http://localhost:8081',
  pactBrokerUrl: process.env.PACT_BROKER_BASE_URL,
  pactBrokerToken: process.env.PACT_BROKER_TOKEN,
  provider: 'pet-service',
  providerVersion: process.env.GIT_SHA,
  providerVersionBranch: process.env.GIT_BRANCH,
  publishVerificationResult: true,
  consumerVersionSelectors: [
    { mainBranch: true },
    { deployedOrReleased: true },
  ],
}).verifyProvider();

(Adapted from pact-js.)

consumerVersionSelectors controls which consumer pacts get verified - mainBranch plus deployedOrReleased keeps the provider compatible with both the latest consumer work and what's in production (pact-how-it-works). `publi

Полный SKILL.md на GitHub

Установить pact-contract-testing в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

.tessl-plugin/plugin.jsonevals/broker-has-the-pact-but-every-row-says-unknown/criteria.jsonevals/broker-has-the-pact-but-every-row-says-unknown/task.mdevals/deploy-gate-blocks-a-hotfix-on-an-unchanged-service/criteria.jsonevals/deploy-gate-blocks-a-hotfix-on-an-unchanged-service/task.mdevals/provider-seed-change-turned-the-contract-red/criteria.jsonevals/provider-seed-change-turned-the-contract-red/task.mdevals/provider-team-offers-to-write-everyones-pacts/criteria.jsonevals/provider-team-offers-to-write-everyones-pacts/task.mdevals/two-integrations-one-ticket-one-vendor-wont-verify/criteria.jsonevals/two-integrations-one-ticket-one-vendor-wont-verify/task.mdreferences/ci-pipelines.md

FAQ

Что делает скилл pact-contract-testing?

Use whenever two services (a frontend and an API, or two microservices) keep breaking each other's API: set up Pact consumer-driven contract tests, publish pacts to a broker, verify the provider and gate deploys with can-i-deploy.

Как установить скилл pact-contract-testing?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл pact-contract-testing запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

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

Сравнить pact-contract-testing с