Token导航 LogoToken导航

Agent Skill · 研究检索

contract-testing(合同测试)

用于辅助测试设计、自动化测试、用例整理和回归验证。它适合让 Agent 编写单元测试、端到端测试、测试计划或根据失败日志定位问题。使用时需要确认项目测试框架、运行命令和夹具数据,避免为了通过测试而改坏真实逻辑;涉及浏览器或外部服务时,应区分本地模拟、测试环境和生产环境。

contract-testing 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为执行命令;许可证信息还不明确,第三方扫描有提醒项,按安装量在研究检索类的 73,675 个 Skill 里排第 62,001。

总安装 343周安装 14GitHub Stars 4下载 111核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:contract-testing(合同测试)
来源仓库:https://github.com/petrkindlmann/qa-skills
仓库路径:skills/contract-testing
安装命令:
npx skills add https://github.com/petrkindlmann/qa-skills --skill contract-testing
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/petrkindlmann/qa-skills --skill contract-testing

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

用于辅助测试设计与自动化用例整理,适合接口契约验证场景。可帮助编写单元测试、端到端测试或根据失败日志定位问题。通过 GitHub 安装,支持 Codex、Claude、Cursor、Gemini CLI 等宿主环境。需确认项目测试框架与运行命令,避免为通过测试而破坏真实逻辑;涉及浏览器时应区分模拟与生产环境。

contract-testing 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/contract-testing

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/petrkindlmann/qa-skills --skill contract-testi…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要执行命令,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

contract-testing 怎么安装?

在终端执行 npx skills add https://github.com/petrkindlmann/qa-skills --skill contract-testing。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

contract-testing 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

contract-testing 需要什么权限?

权限级别是执行命令。安装流程涉及命令执行,可能通过 npx skills add https://github.com/petrkindlmann/qa-skills --skill contract-testing 联网下载 Skill 或依赖。用户安装前应确认命令来源、仓库内容和执行环境。

contract-testing 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

contract-testing 用的人多吗?

公开数据是累计安装 343 次,近一周安装 14 次,下载 111 次,GitHub 4 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

contract-testing 安全吗?

第三方扫描有提醒项,说明存在需要人工确认的行为。安装前请打开源码看清它读了什么、联网到哪里。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。

先想清楚的地方

  • 需要执行命令,装到常用环境前要先评估影响面。
  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方扫描存在提醒项或未通过项,需要人工逐条确认。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。

不太适合

  • 不能接受 Skill 在你机器上执行命令的人。
  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
contract-testing

合同测试 · 本页

3434执行命令未明确有提醒

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文


Discovery Questions

  1. Architecture: Microservices, monolith with separate consumers (mobile/SPA), or BFF pattern? Contract testing matters most when teams deploy independently.
  2. Who owns the contract? Consumer-driven (consumers define what they need) or provider-driven (provider publishes a spec)? Most teams benefit from consumer-driven.
  3. API versioning strategy: URL-based (/v1/, /v2/), header-based, or none? Contracts must account for version negotiations.
  4. How many consumer-provider pairs? Start with the highest-traffic or most-fragile integration. Do not try to contract-test everything at once.
  5. Existing API specs: Is there an OpenAPI/Swagger spec? If yes, consider schema-first contracts as a starting point.
  6. Check .agents/qa-project-context.md first. Respect existing API conventions and testing infrastructure.

Core Principles

1. Consumers define what they need, providers verify they can deliver. The consumer writes a test declaring "I will call GET /users/123 and expect {id, name, email}." The provider runs this test against its real implementation. If the provider cannot satisfy the contract, the build breaks before deployment.

2. Contracts are the shared source of truth. Not documentation, not Slack threads, not "just deploy and see." Contracts are executable tests that live in CI and block deployments on violation.

3. Contract tests replace integration environments, not integration tests. You still need integration tests for complex multi-step workflows. Contract tests eliminate the need to deploy consumer and provider together just to verify the interface.

4. Break the build on contract violation. A contract test that logs a warning but allows deployment provides zero value. Contracts must be deployment gates.

5. Test the contract, not the business logic. Consumer tests verify response shape and status codes. Provider verification ensures the contract is satisfiable. Business rules belong in unit and integration tests.


Pact.js Setup

Install

# Consumer side
npm i -D @pact-foundation/pact

# Provider side
npm i -D @pact-foundation/pact

Consumer Test

The consumer defines what it needs from the provider. This generates a pact file (JSON contract).

// consumer/tests/contract/userApi.pact.spec.ts
import { PactV4, MatchersV3 } from "@pact-foundation/pact";
import path from "path";
import { UserApiClient } from "../../src/userApiClient";

const { like, eachLike, integer, string, regex } = MatchersV3;

const provider = new PactV4({
  consumer: "frontend-app",
  provider: "user-service",
  dir: path.resolve(__dirname, "../../../pacts"),
  logLevel: "warn",
});

describe("User API Contract", () => {
  it("should return a user by ID", async () => {
    await provider
      .addInteraction()
      .given("user 123 exists")
      .uponReceiving("a request for user 123")
      .withRequest("GET", "/api/users/123", (builder) => {
        builder.headers({ Accept: "application/json" });
      })
      .willRespondWith(200, (builder) => {
        builder
          .headers({ "Content-Type": "application/json" })
          .jsonBody({
            id: integer(123),
            name: string("Alice Johnson"),
            email: regex("alice@example.com", "^[\\w.+-]+@[\\w-]+\\.[\\w.]+$"),
            role: string("member"),
            createdAt: regex("2024-01-15T00:00:00Z", "^\\d{4}-\\d{2}-\\d{2}T.*Z$"),
          });
      })
      .executeTest(async (mockServer) => {
        const client = new UserApiClient(mockServer.url);
        const user = await client.getUser(123);

        expect(user.id).toBe(123);
        expect(user.name).toBeDefined();
        expect(user.email).toContain("@");
      });
  });

  it("should return 404 for non-existent user", async () => {
    await provider
      .addInteraction()
      .given("user 999 does not exist")
      .uponReceiving("a request for non-existent user")
      .withRequest("GET", "/api/users/999")
      .willRespondWith(404, (builder) => {
        builder.jsonBody({
          error: string("Not Found"),
          message: string("User 999 not found"),
        });
      })
      .executeTest(async (mockServer) => {
        const client = new UserApiClient(mockServer.url);
        await expect(client.getUser(999)).rejects.toThrow("User 999 not found");
      });
  });

  it("should return a paginated list of users", async () => {
    await provider
      .addInteraction()
      .given("users exist")
      .uponReceiving("a request for the user list")
      .withRequest("GET", "/api/users", (builder) => {
        builder.query({ page: "1", limit: "10" });
      })
      .willRespondWith(200, (builder) => {
        builder.jsonBody({
          data: eachLike({
            id: integer(1),
            name: string("Alice"),
            email: string("alice@example.com"),
          }),
          pagination: {
            page: integer(1),
            limit: integer(10),
            total: integer(42),
          },
        });
      })
      .executeTest(async (mockServer) => {
        const client = new UserApiClient(mockServer.url);
        const result = await client.listUsers({ page: 1, limit: 10 });

        expect(result.data.length).toBeGreaterThan(0);
        expect(result.pagination.page).toBe(1);
      });
  });
});

Running this test generates pacts/frontend-app-user-service.json -- the contract file.

Provider Verification

The provider verifies it can satisfy all consumer contracts. This runs against the real provider implementation (not mocks).

// provider/tests/contract/providerVerification.spec.ts
import { Verifier } from "@pact-foundation/pact";
import path from "path";
import { startApp, stopApp } from "../../src/server";

describe("Provider Verification", () => {
  let serverUrl: string;

  beforeAll(async () => {
    // Start the real provider with a test database
    const server = await startApp({ port: 0, dbUrl: process.env.TEST_DATABASE_URL });
    serverUrl = `http://localhost:${server.port}`;
  });

  afterAll(async () => {
    await stopApp();
  });

  it("should satisfy all consumer contracts", async () => {
    await new Verifier({
      providerBaseUrl: serverUrl,
      provider: "user-service",

      // Option A: local files; Option B: set pactBrokerUrl/pactBrokerToken/consumerVersionSelectors
      pactUrls: [
        path.resolve(__dirname, "../../../pacts/frontend-app-user-service.json"),
      ],

      // Provider states: set up data that matches consumer expectations
      stateHandlers: {
        "user 123 exists": async () => {
          await seedUser({ id: 123, name: "Alice Johnson", email: "alice@example.com" });
        },
        "user 999 does not exist": async () => {
          await clearUsers();
        },
        "users exist": async () => {
          await seedUsers(15); // Seed enough for pagination
        },
      },

      // Publish verification results back to broker
      publishVerificationResult: true,
      providerVersion: process.env.GIT_COMMIT ?? "local",
      providerVersionBranch: process.env.GIT_BRANCH ?? "local",
    }).verifyProvider();
  });
});

Pact Broker

The Pact Broker is the central registry where pact files are published and provider verification results are recorded. It enables the can-i-deploy workflow.

Setup with Docker

# docker-compose.pact-broker.yml
services:
  pact-broker:
    image: pactfoundation/pact-broker:latest
    ports:
      - "9292:9292"
    environment:
      PACT_BROKER_DATABASE_URL: postgres://pact:pact@postgres/pact
      PACT_BROKER_BASIC_AUTH_USERNAME: admin
      PACT_BROKER_BASIC_AUTH_PASSWORD: ${PACT_BROKER_PASSWORD}
      PACT_BROKER_ALLOW_PUBLIC_READ: "true"
    depends_on:
      postgres:
        condition: service_healthy

  postgres:
    image: postgres:16-alpine
    environment:
      POSTGRES_DB: pact
      POSTGRES_USER: pact
      POSTGRES_PASSWORD: pact
    volumes:
      - pact-db:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U pact"]
      interval: 3s
      timeout: 2s
      retries: 10

volumes:
  pact-db:

Publishing Pacts (Consumer CI)

# After consumer tests generate pact files
npx pact-broker publish ./pacts \
  --consumer-app-version="$GIT_COMMIT" \
  --branch="$GIT_BRANCH" \
  --broker-base-url="https://pact.example.com" \
  --broker-token="$PACT_BROKER_TOKEN"

Consumer-Driven Workflow

The Full Cycle

1. Consumer writes contract test
   └── Generates pact JSON file

2. Consumer CI publishes pact to broker
   └── Broker stores pact tagged with consumer version + branch

3. Broker webhook triggers provider verification
   └── Provider CI pulls latest pact, runs verification

4. Provider publishes verification result to broker
   └── Broker records: "provider v2.3.1 satisfies consumer v1.5.0"

5. Before deploy: can-i-deploy check
   └── "Can consumer v1.5.0 be deployed? Yes, provider v2.3.1 is in production and verified."

Consumer CI Pipeline

# .github/workflows/consumer-contract.yml
name: Consumer Contract Tests
on: [push]

jobs:
  contract-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 20, cache: npm }
      - run: npm ci

      - name: Run consumer contract tests
        run: npm run test:contract

      - name: Publish pacts to broker
        if: github.ref == 'refs/heads/main' || github.event_name == 'pull_request'
        env:
          PACT_BROKER_BASE_URL: ${{ secrets.PACT_BROKER_URL }}
          PACT_BROKER_TOKEN: ${{ secrets.PACT_BROKER_TOKEN }}
        run: |
          npx pact-broker publish ./pacts \
            --consumer-app-version="${{ github.sha }}" \
            --branch="${{ github.head_ref || github.ref_name }}"

      - name: Can I deploy?
        if: github.ref == 'refs/heads/main'
        env:
          PACT_BROKER_BASE_URL: ${{ secrets.PACT_BROKER_URL }}
          PACT_BROKER_TOKEN: ${{ secrets.PACT_BROKER_TOKEN }}
        run: |
          npx pact-broker can-i-deploy \
            --pacticipant="frontend-app" \
            --version="${{ github.sha }}" \
            --to-environment=production

Provider CI Pipeline

# .github/workflows/provider-contract.yml
name: Provider Contract Verification
on:
  push:
  repository_dispatch:
    types: [pact-changed]  # Triggered by Pact Broker webhook

jobs:
  verify-contracts:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:16-alpine
        env: { POSTGRES_DB: testdb, POSTGRES_USER: test, POSTGRES_PASSWORD: test }
        ports: ['5432:5432']
        options: >-
          --health-cmd="pg_isready -U test"
          --health-interval=5s
          --health-timeout=3s
          --health-retries=5
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 20, cache: npm }
      - run: npm ci
      - run: npm run db:migrate

      - name: Verify provider contracts
        env:
          TEST_DATABASE_URL: postgres://test:test@localhost:5432/testdb
          GIT_COMMIT: ${{ github.sha }}
          GIT_BRANCH: ${{ github.head_ref || github.ref_name }}
          PACT_BROKER_BASE_URL: ${{ secrets.PACT_BROKER_URL }}
          PACT_BROKER_TOKEN: ${{ secrets.PACT_BROKER_TOKEN }}
        run: npm run test:contract:provider

      - name: Can I deploy?
        if: github.ref == 'refs/heads/main'
        env:
          PACT_BROKER_BASE_URL: ${{ secrets.PACT_BROKER_URL }}
          PACT_BROKER_TOKEN: ${{ secrets.PACT_BROKER_TOKEN }}
        run: |
          npx pact-broker can-i-deploy \
            --pacticipant="user-service" \
            --version="${{ github.sha }}" \
            --to-environment=production

Pact Broker Webhooks

Configure webhooks in the Pact Broker to trigger provider verification via repository_dispatch when a new pact is published. The webhook sends a POST to https://api.github.com/repos/myorg/user-service/dispatches with event type pact-changed, which the provider pipeline listens for (see repository_dispatch trigger above).


Schema-First vs Consumer-First

Consumer-First (Pact)

Consumers define what they need. Contracts emerge from real usage patterns.

Best for: Teams where consumers have specific needs that differ across clients (mobile needs fewer fields than web), APIs that evolve organically, microservice ecosystems.

Schema-First (OpenAPI + Validation)

Provider publishes an OpenAPI spec. Consumers validate their usage against the spec.

Best for: Public APIs with many consumers, APIs designed upfront before implementation, teams with strong API design governance.

// Schema-first: validate response against OpenAPI spec
import SwaggerParser from "@apidevtools/swagger-parser";
import Ajv from "ajv";

const ajv = new Ajv();

async function validateAgainstSpec(response: unknown, operationId: string) {
  const spec = await SwaggerParser.dereference("./openapi.yaml");
  const operation = findOperation(spec, operationId);
  const schema = operation.responses["200"].content["application/json"].schema;

  const validate = ajv.compile(schema);
  const valid = validate(response);

  if (!valid) {
    throw new Error(`Response violates API spec: ${JSON.stringify(validate.errors)}`);
  }
}

Hybrid Approach

Use OpenAPI as the design artifact and Pact as the enforcement mechanism.

  1. Design API with OpenAPI spec (provider team leads design).
  2. Generate Pact consumer tests from OpenAPI spec as a baseline.
  3. Consumers add specific interactions beyond the baseline.
  4. Provider verifies against Pact contracts (which are a subset of the OpenAPI spec).

can-i-deploy

The can-i-deploy command is the deployment gate. It checks the Pact Broker matrix to determine if a version is safe to deploy.

# Check if consumer can be deployed to production
npx pact-broker can-i-deploy \
  --pacticipant="frontend-app" \
  --version="abc123" \
  --to-environment=production

# Output:
# CONSUMER        | C.VERSION | PROVIDER     | P.VERSION | SUCCESS?
# frontend-app    | abc123    | user-service | def456    | true
# frontend-app    | abc123    | order-service| ghi789    | true
#
# All required verification results are published and successful.
# Computer says yes \o/

# Record deployment after successful deploy
npx pact-broker record-deployment \
  --pacticipant="frontend-app" \
  --version="abc123" \
  --environment=production

Never deploy without a passing can-i-deploy check. This is the entire point of contract testing.


Anti-Patterns

Testing business logic in contracts. Keep contracts thin: status codes, field presence, field types, field format. Business logic belongs in unit and integration tests.

Provider-driven contracts without consumer input. If the provider team defines contracts alone, they test what they think consumers need, not what consumers actually use. Consumer-driven contracts catch real integration failures.

Skipping provider states. If the consumer expects given("user 123 exists") but provider verification runs against an empty database, the verification is meaningless. Provider state handlers must set up the exact scenario.

Publishing pacts from local machines. Pacts must be published from CI with a known commit SHA and branch. Local publishes produce untraceable versions that pollute the broker.

Ignoring can-i-deploy failures. If can-i-deploy says no, fix the contract violation or negotiate the change with the consumer team. Deploying anyway breaks production.

One massive pact covering every endpoint. Start with critical integration points. Add contracts incrementally as failures justify them. A 500-interaction pact is unmaintainable.

Not cleaning up old pacts. Configure Pact Broker to delete pact versions older than 90 days that are not deployed to any environment. Stale pacts slow down verification and confuse the matrix.


Done When

  • Consumer pact tests are written and publishing to Pact Broker on every CI run with a commit SHA and branch tag.
  • Provider verification job runs in CI on every provider change and on every new pact published (via Pact Broker webhook).
  • can-i-deploy gate is configured in both consumer and provider pipelines and blocks deployment when a contract is broken.
  • Consumer and provider teams have documented and agreed on the contract ownership model (who writes interactions, who reviews changes).
  • At least one breaking-change scenario has been tested end-to-end and confirmed caught by the can-i-deploy check before reaching production.

Related Skills

  • api-testing -- REST/GraphQL testing patterns, schema validation, auth flow testing.
  • ci-cd-integration -- Pipeline templates for running contract tests as CI gates.
  • test-environments -- Environment strategy, including where contract tests fit in the pipeline.
  • service-virtualization -- When to use stubs vs contracts vs real services.

平台分布

Codex

39.41%
按下载量换算44

Claude

27.72%
按下载量换算31

Cursor

18.28%
按下载量换算20

Gemini CLI

10.45%
按下载量换算12

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

可疑

权限和风险

执行命令

安装流程涉及命令执行,可能通过 npx skills add https://github.com/petrkindlmann/qa-skills --skill contract-testing 联网下载 Skill 或依赖。用户安装前应确认命令来源、仓库内容和执行环境。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在提醒或未通过项,安装前请自行复核。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills