contract-tester について
contract-testerは、API契約とプロバイダー・コンシューマー間の互換性を検証するスキルです。契約文書のチェックや破壊的変更の検出に加え、モックサーバーと契約テストに対応します。
主な機能
- 01CTR YAMLスキーマ検証
- 02OpenAPI、AsyncAPI、JSON Schema、GraphQLの検査
- 03バージョン互換性と破壊的変更の検出
- 04モックAPIサーバーの生成
- 05コンシューマー駆動型契約テスト
- 06APIドキュメントの生成
活用シーン
- 01デプロイ前の契約文書検証
- 02API変更の互換性確認
- 03モックAPIを使ったコンシューマーのテスト
- 04契約に基づくプロバイダー実装の検証
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ vladm3105/ aidoc-flow-framework --skill contract-testerインストール後、Claude Code で/contract-testerを入力して読み込まれたか確認します。
詳細
contract-tester
説明:API コントラクトの検証、破壊的変更の検出、コンシューマー駆動型コントラクトテスト
カテゴリ:API 品質保証
複雑度:中〜高(スキーマ検証+コントラクト互換性)
目的
API 実装を CTR(コントラクト)ドキュメントに照らして検証し、破壊的変更を検出して、プロバイダーとコンシューマーの互換性を確保します。デプロイ前に API コントラクト違反を防ぎます。
機能
1. CTR YAML スキーマ検証
- YAML 構造をスキーマに照らして検証
- 必須フィールドがすべてそろっているか確認
- データ型が正しいか確認
- 列挙値を検証
- フォーマット仕様(メールアドレス、URL、UUID)を確認
2. OpenAPI/AsyncAPI 準拠性
- CTR を OpenAPI 3.0/3.1 仕様に変換
- OpenAPI スキーマに照らして検証
- イベント駆動型 API の AsyncAPI 検証
- JSON Schema 検証
- GraphQL スキーマ検証
3. コントラクトのバージョン管理
- セマンティックバージョニング(MAJOR.MINOR.PATCH)の検証
- バージョン互換性の確認
- 非推奨化の警告
- 移行パスの検証
4. 破壊的変更の検出
- エンドポイント/操作の削除
- リクエスト/レスポンススキーマの変更
- 必須フィールドの削除
- フィールド型の変更
- より厳格な検証ルール
- 認証要件の変更
5. モックサーバーの生成
- CTR からモック API サーバーを生成
- 現実的なレスポンスの生成
- レスポンス遅延の設定
- エラーシナリオのシミュレーション
- ステートフル API の状態管理
6. コンシューマー駆動型コントラクトテスト
- Pact コントラクトテスト
- プロバイダーの検証
- コンシューマーコントラクトの生成
- 双方向コントラクトテスト
- コントラクトの変遷の追跡
7. コントラクト互換性マトリックス
- プロバイダーバージョンの互換性
- コンシューマーバージョンのサポート状況
- 非推奨化スケジュールの追跡
- 移行要件
8. API ドキュメントの生成
- CTR から API ドキュメントを生成
- インタラクティブな API エクスプローラー
- 複数の言語によるコード例
- 認証ガイド
コントラクトテストのワークフロー
graph TD
A[CTR Document] --> B[Parse YAML]
B --> C{Valid YAML?}
C -->|No| D[Report Parse Error]
C -->|Yes| E[Schema Validation]
E --> F{Schema Valid?}
F -->|No| G[Report Schema Errors]
F -->|Yes| H[Version Check]
H --> I{Version Valid?}
I -->|No| J[Report Version Error]
I -->|Yes| K[Breaking Change Detection]
K --> L{Previous Version Exists?}
L -->|No| M[First Version]
L -->|Yes| N[Compare Versions]
N --> O{Breaking Changes?}
O -->|Yes| P[Report Breaking Changes]
O -->|No| Q[Compatible Change]
M --> R[Generate Mock Server]
Q --> R
P --> R
R --> S[Run Contract Tests]
S --> T{Tests Pass?}
T -->|No| U[Report Test Failures]
T -->|Yes| V[Generate Documentation]
V --> W[Validation Complete]
D --> W
G --> W
J --> W
U --> W
使用方法
CTR ドキュメントの検証
contract-tester validate --file ctrs/CTR-USER-V1.yaml
出力:
=== Contract Validation Report: CTR-USER-V1 ===
Status: PASS
Schema Validation: ✓
- Service name: user-service
- Version: 1.0.0
- Protocol: REST
- Endpoints: 5
- Models: 3
OpenAPI Compliance: ✓
- Valid OpenAPI 3.1 specification
- All schemas properly defined
- Authentication specified (Bearer JWT)
Version Check: ✓
- Semantic versioning: 1.0.0
- No previous version (initial release)
Breaking Changes: N/A (initial release)
Warnings (1):
- Endpoint DELETE /users/{id} lacks rate limiting specification
→ Recommendation: Add rate limiting to prevent abuse
Summary: Contract is valid and ready for implementation
破壊的変更の検出
contract-tester diff \
--previous ctrs/CTR-USER-V1.yaml \
--current ctrs/CTR-USER-V2.yaml
出力:
=== Breaking Change Analysis: V1 → V2 ===
BREAKING CHANGES (3):
1. [CRITICAL] Removed endpoint
- DELETE /users/{id}
- Impact: Consumers using this endpoint will fail
- Migration: Use DELETE /users/{id}/deactivate instead
2. [CRITICAL] Changed response type
- Endpoint: GET /users/{id}
- Field: created_at
- V1: string (format: date-time)
- V2: integer (unix timestamp)
- Impact: Date parsing will fail in consumers
- Migration: Update consumers to handle unix timestamp
3. [MAJOR] Added required field
- Endpoint: POST /users
- Field: email_verified (boolean, required)
- Impact: Existing POST requests missing this field will fail
- Migration: Update all POST requests to include email_verified
NON-BREAKING CHANGES (2):
1. [MINOR] Added optional field
- Endpoint: GET /users/{id}
- Field: last_login (string, optional)
- Impact: None (backward compatible)
2. [PATCH] Fixed typo in description
- Model: User
- Field: username
- Impact: Documentation only
RECOMMENDATION: Version should be 2.0.0 (MAJOR bump due to breaking changes)
Current version: 1.1.0 ❌
Suggested version: 2.0.0 ✓
モックサーバーの生成
contract-tester mock \
--file ctrs/CTR-USER-V1.yaml \
--port 8080 \
--response-delay 100ms
モックサーバーの機能:
- スキーマに基づいた現実的なデータの生成
- レスポンス遅延の設定
- エラーシナリオの注入
- リクエストの検証
- レスポンスのログ記録
# Test against mock server
curl http://localhost:8080/api/users/123
# Response
{
"user_id": "123e4567-e89b-12d3-a456-426614174000",
"username": "john_doe",
"email": "[email protected]",
"created_at": "2025-01-15T10:30:00Z",
"status": "active"
}
コンシューマーコントラクトテストの実行
contract-tester test-consumer \
--contract ctrs/CTR-USER-V1.yaml \
--consumer user-frontend \
--provider user-service \
--output reports/contract-tests/
生成される Pact テスト:
import pytest
from pact import Consumer, Provider, Like, EachLike, Term
@pytest.fixture
def pact():
return Consumer('user-frontend').has_pact_with(
Provider('user-service'),
pact_dir='./pacts'
)
def test_get_user_contract(pact):
"""Verify GET /users/{id} contract"""
expected_response = {
'user_id': Like('123e4567-e89b-12d3-a456-426614174000'),
'username': Like('john_doe'),
'email': Term(r'.+@.+\..+', '[email protected]'),
'created_at': Like('2025-01-15T10:30:00Z'),
'status': Term(r'active|inactive|suspended', 'active')
}
(pact
.given('user with id 123 exists')
.upon_receiving('a request for user 123')
.with_request('GET', '/api/users/123')
.will_respond_with(200, body=expected_response))
with pact:
result = user_api.get_user('123')
assert result.status_code == 200
assert 'user_id' in result.json()
プロバイダー実装の検証
contract-tester test-provider \
--contract ctrs/CTR-USER-V1.yaml \
--provider-url http://localhost:8000 \
--output reports/provider-verification/
CTR ドキュメントの構造
CTR の完全な例
# ctrs/CTR-USER-V1.yaml
contract_id: CTR-USER-V1
version: 1.0.0
service_name: user-service
protocol: REST
base_path: /api
metadata:
description: User management API contract
owner: backend-team
consumers:
- user-frontend
- admin-dashboard
traceability:
requirements:
- REQ-USER-001
- REQ-USER-002
specifications:
- SPEC-API-V1
authentication:
type: bearer
scheme: JWT
token_location: header
header_name: Authorization
endpoints:
- operation_id: get_user
method: GET
path: /users/{id}
summary: Retrieve user by ID
parameters:
- name: id
in: path
required: true
schema:
type: string
format: uuid
responses:
200:
description: User found
content:
application/json:
schema:
$ref: '#/components/schemas/User'
404:
description: User not found
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
401:
description: Unauthorized
rate_limit:
requests: 100
window: 60s
- operation_id: create_user
method: POST
path: /users
summary: Create new user
request_body:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateUserRequest'
responses:
201:
description: User created
content:
application/json:
schema:
$ref: '#/components/schemas/User'
400:
description: Invalid request
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
409:
description: User already exists
- operation_id: update_user
method: PUT
path: /users/{id}
summary: Update user
parameters:
- name: id
in: path
required: true
schema:
type: string
format: uuid
request_body:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/UpdateUserRequest'
responses:
200:
description: User updated
content:
application/json:
schema:
$ref: '#/components/schemas/User'
404:
description: User not found
- operation_id: delete_user
method: DELETE
path: /users/{id}
summary: Delete user
parameters:
- name: id
in: path
required: true
schema:
type: string
format: uuid
responses:
204:
description: User deleted
404:
description: User not found
- operation_id: list_users
method: GET
path: /users
summary: List all users
parameters:
- name: page
in: query
schema:
type: integer
minimum: 1
default: 1
- name: limit
in: query
schema:
type: integer
minimum: 1
maximum: 100
default: 20
responses:
200:
description: User list
content:
application/json:
schema:
type: object
properties:
users:
type: array
items:
$ref: '#/components/schemas/User'
pagination:
$ref: '#/components/schemas/Pagination'
components:
schemas:
User:
type: object
required:
- user_id
- username
- email
- created_at
- status
properties:
user_id:
type: string
format: uuid
description: Unique user identifier
username:
type: string
minLength: 3
maxLength: 20
pattern: '^[a-zA-Z0-9_]+$'
description: Unique username
email:
type: string
format: email
description: User email address
full_name:
type: string
maxLength: 100
description: User's full name
created_at:
type: string
format: date-time
description: Account creation timestamp
updated_at:
type: string
format: date-time
description: Last update timestamp
status:
type: string
enum: [active, inactive, suspended]
description: Account status
CreateUserRequest:
type: object
required:
- username
- email
- password
properties:
username:
type: string
minLength: 3
maxLength: 20
pattern: '^[a-zA-Z0-9_]+$'
email:
type: string
format: email
password:
type: string
minLength: 8
maxLength: 128
full_name:
type: string
maxLength: 100
UpdateUserRequest:
type: object
properties:
email:
type: string
format: email
full_name:
type: string
maxLength: 100
status:
type: string
enum: [active, inactive, suspended]
Error:
type: object
required:
- error_code
- message
properties:
error_code:
type: string
description: Machine-readable error code
message:
type: string
description: Human-readable error message
details:
type: object
description: Additional error details
Pagination:
type: object
required:
- page
- limit
- total
properties:
page:
type: integer
description: Current page number
limit:
type: integer
description: Items per page
total:
type: integer
description: Total number of items
has_next:
type: boolean
description: Whether there are more pages
破壊的変更のルール
MAJOR バージョンの変更(X.0.0)
-
エンドポイントの削除
# V1 DELETE /users/{id} # V2 (BREAKING) # Endpoint removed -
必須フィールドの削除
# V1 required: [username, email, password] # V2 (BREAKING) required: [username, email] # password removed -
フィールド型の変更
# V1 user_id: type: string # V2 (BREAKING) user_id: type: integer -
検証の厳格化
# V1 username: type: string # V2 (BREAKING) username: type: string pattern: '^[a-zA-Z0-9_]+$' # New constraint -
認証の変更
# V1 authentication: type: basic # V2 (BREAKING) authentication: type: bearer scheme: JWT
MINOR バージョンの変更(x.Y.0)
-
エンドポイントの追加
# V1.0.0 GET /users # V1.1.0 (Non-breaking) GET /users GET /users/search # New endpoint -
任意フィールドの追加
# V1.0.0 properties: username: ... # V1.1.0 (Non-breaking) properties: username: ... nickname: ... # New optional field -
検証の緩和
# V1.0.0 username: minLength: 5 # V1.1.0 (Non-breaking) username: minLength: 3 # Less strict
PATCH バージョンの変更(x.y.Z)
- ドキュメントの更新
- 説明のバグ修正
- 誤字の修正
- 例の更新
コントラクト互換性マトリックス
Provider Version Compatibility:
V1.0.0 consumers can use:
- V1.0.0, V1.0.1, V1.1.0, V1.2.0 providers ✓
- V2.0.0 providers ❌ (breaking changes)
V1.1.0 consumers can use:
- V1.1.0, V1.1.1, V1.2.0 providers ✓
- V1.0.0 providers ⚠️ (missing optional features)
- V2.0.0 providers ❌ (breaking changes)
V2.0.0 consumers can use:
- V2.0.0, V2.0.1, V2.1.0 providers ✓
- V1.x.x providers ❌ (incompatible)
ツールへのアクセス
必要なツール:
Read:CTR YAML ファイルの読み取りWrite:テストファイルとドキュメントの生成Bash:検証・テストツールの実行Grep:コントラクトのパターン検索
必要なライブラリ:
- pyyaml:YAML の解析
- jsonschema:スキーマ検証
- openapi-spec-validator:OpenAPI の検証
- pact-python:コンシューマー駆動型コントラクトテスト
- faker:モックデータの生成
統合ポイント
doc-flow との連携
- 生成時に CTR ドキュメントを検証
- 要件への追跡可能性を確保
- コントラクトの変更に合わせてドキュメントを更新
test-automation との連携
- コントラクトテストを自動生成
- テストスイートと統合
- コントラクトテストのカバレッジを追跡
code-review との連携
- API 実装をコントラクトに照らして検証
- コード内のコントラクト違反を検出
- コントラクトに準拠した修正を提案
devops-flow を使用する場合
- CI/CD パイプラインでのコントラクト検証
- 破壊的変更を含むデプロイをブロック
- API ゲートウェイ設定を生成
ベストプラクティス
- セマンティックバージョニング:MAJOR.MINOR.PATCH を厳密に遵守します
- 後方互換性:追加的な変更を優先します
- 非推奨の通知:機能を削除する前に警告します
- コンシューマーからのフィードバック:コントラクトの変更にコンシューマーを参加させます
- ドキュメント:破壊的変更に対する明確な移行ガイドを用意します
- テスト:リリース前にすべてのコントラクト変更をテストします
- バージョニング戦略:最低でも N-1 バージョンをサポートします
- 変更履歴:包括的なコントラクト変更履歴を維持します
成功基準
- コントラクト検証カバレッジ 100%
- 検出されない破壊的変更ゼロ
- コントラクト検証時間 5 分未満
- 同じ MAJOR バージョン内でのコンシューマーとプロバイダーの互換性 100%
- すべての破壊的変更に移行手順を記載
- すべてのコントラクトでモックサーバーを利用可能にする
- すべての CTR ドキュメントに、以下を含む完全な文書管理セクションを記載:
- プロジェクトのメタデータ(名前、バージョン、日付、所有者、作成者、ステータス)
- すべてのコントラクト変更を追跡する文書改訂履歴の表
注記
- コントラクトテストはデプロイ前に CI/CD で実行します
- 破壊的変更には MAJOR バージョンの引き上げが必要です
- プロバイダーは MAJOR バージョン内で後方互換性を維持する必要があります
- コンシューマーはマイナーバージョンの違いを適切に処理する必要があります
- コントラクトの変更時に、コンシューマーへ自動通知を送信します
コメント
Markdown 対応