mcpbeat Sign in

Test Contract Skill for Claude

Generate protocol/interface test suites that any implementation must pass. Define the contract once, test every implementation. Use when designing protocols or swapping implementations.

2k tokens
context cost
the whole folder, loaded on every use
1
files
instructions only
0
copies elsewhere
how many repositories repackaged it
585
stars on the repo
on the repository, not the skill itself

Install

one command, takes just this skill from the repository
npx skills add https://github.com/rshankras/claude-code-apple-skills --skill test-contract

The instruction itself

16 sections, as written by the author

Test Contract

Define behavioral contracts as test suites. Any class conforming to a protocol must pass the contract tests. Ensures consistent behavior across implementations — human-written, AI-generated, or mock.

When This Skill Activates

Use this skill when the user:

  • Designs a protocol and wants to ensure conformance quality
  • Has multiple implementations of the same interface (e.g., real + mock + in-memory)
  • Says "test the protocol" or "contract test"
  • Wants to swap implementations safely (e.g., CoreData → SwiftData)
  • Wants to ensure AI-generated implementations meet the spec

Why Contract Tests

Protocol: DataStore
  ├── SQLiteDataStore  → must pass contract tests
  ├── InMemoryDataStore → must pass contract tests
  ├── MockDataStore    → must pass contract tests
  └── CloudDataStore   → must pass contract tests

Write the contract once. Every implementation proves it works by passing the same tests.

Process

Phase 1: Identify the Protocol

Grep: "protocol.*\\{" to find protocols
Read: protocol definition

Understand:

  • [ ] All required methods and properties
  • [ ] Expected behavior for each method
  • [ ] Error conditions and edge cases
  • [ ] Thread safety requirements
  • [ ] State invariants (e.g., count matches items.count)

Phase 2: Define Contract Behaviors

For each protocol method, define required behaviors:

## DataStore Contract

### save(_ item:)
- Saving a new item increases count by 1
- Saved item is retrievable by ID

### fetch(id:)
- Returns item when it exists
- Returns nil when item doesn't exist
- Returns most recently saved version

### delete(id:)
- Deleting existing item decreases count by 1
- Deleted item is no longer fetchable

### fetchAll()
- Returns all saved items
- Returns empty array when store is empty
- Items are in consistent order (insertion or specified)

### Invariants
- count == fetchAll().count (always)
- save then fetch returns same item
- delete then fetch returns nil

Phase 3: Generate Contract Test Suite

Pattern: Generic Test Suite
import Testing

/// Contract tests for any DataStore implementation.
/// Subclass or call with your concrete implementation.
struct DataStoreContractTests<Store: DataStore> {

    let makeStore: () -> Store

    init(makeStore: @escaping () -> Store) {
        self.makeStore = makeStore
    }

    // MARK: - save(_ item:)

    @Test("save increases count")
    func saveIncreasesCount() async throws {
        let store = makeStore()
        let item = Item(id: "1", title: "Test")

        try await store.save(item)

        #expect(store.count == 1)
    }

    @Test("save then fetch returns same item")
    func saveAndFetch() async throws {
        let store = makeStore()
        let item = Item(id: "1", title: "Test")

        try await store.save(item)
        let fetched = try await store.fetch(id: "1")

        #expect(fetched?.title == "Test")
    }

    @Test("save existing item updates it")
    func saveUpdates() async throws {
        let store = makeStore()
        try await store.save(Item(id: "1", title: "Original"))
        try await store.save(Item(id: "1", title: "Updated"))

        let fetched = try await store.fetch(id: "1")

        #expect(fetched?.title == "Updated")
        #expect(store.count == 1)
    }

    @Test("save throws on invalid item")
    func saveInvalidThrows() async {
        let store = makeStore()
        let invalid = Item(id: "1", title: "")

        await #expect(throws: DataStoreError.invalidItem) {
            try await store.save(invalid)
        }
    }

    // MARK: - fetch(id:)

    @Test("fetch returns nil for non-existent ID")
    func fetchNonExistent() async throws {
        let store = makeStore()

        let result = try await store.fetch(id: "nonexistent")

        #expect(result == nil)
    }

    // MARK: - delete(id:)

    @Test("delete removes item")
    func deleteRemoves() async throws {
        let store = makeStore()
        try await store.save(Item(id: "1", title: "Test"))

        try await store.delete(id: "1")

        #expect(store.count == 0)
        let fetched = try await store.fetch(id: "1")
        #expect(fetched == nil)
    }

    @Test("delete non-existent does nothing")
    func deleteNonExistent() async throws {
        let store = makeStore()

        try await store.delete(id: "nonexistent")

        #expect(store.count == 0)
    }

    // MARK: - fetchAll()

    @Test("fetchAll returns all items")
    func fetchAll() async throws {
        let store = makeStore()
        try await store.save(Item(id: "1", title: "A"))
        try await store.save(Item(id: "2", title: "B"))

        let all = try await store.fetchAll()

        #expect(all.count == 2)
    }

    @Test("fetchAll returns empty when store is empty")
    func fetchAllEmpty() async throws {
        let store = makeStore()

        let all = try await store.fetchAll()

        #expect(all.isEmpty)
    }

    // MARK: - Invariants

    @Test("count matches fetchAll count")
    func countInvariant() async throws {
        let store = makeStore()
        try await store.save(Item(id: "1", title: "A"))
        try await store.save(Item(id: "2", title: "B"))
        try await store.delete(id: "1")

        let all = try await store.fetchAll()

        #expect(store.count == all.count)
    }
}
Running Contract Tests Per Implementation
@Suite("InMemoryDataStore Contract")
struct InMemoryDataStoreContractTests {
    let contract = DataStoreContractTests { InMemoryDataStore() }

    @Test("save increases count")
    func saveIncreasesCount() async throws {
        try await contract.saveIncreasesCount()
    }

    @Test("save then fetch returns same item")
    func saveAndFetch() async throws {
        try await contract.saveAndFetch()
    }

    // ... all contract tests
}

@Suite("SQLiteDataStore Contract")
struct SQLiteDataStoreContractTests {
    let contract = DataStoreContractTests { SQLiteDataStore(path: ":memory:") }

    @Test("save increases count")
    func saveIncreasesCount() async throws {
        try await contract.saveIncreasesCount()
    }

    // ... all contract tests
}

Common Contract Categories

Repository / Data Store

  • CRUD operations (create, read, update, delete)
  • Query/filter behavior
  • Ordering guarantees
  • Uniqueness constraints
  • Empty state handling

Network Client

  • Successful response parsing
  • Error response handling (4xx, 5xx)
  • Timeout behavior
  • Retry logic
  • Request construction (headers, body)

Cache

  • Store and retrieve
  • Expiration/TTL
  • Thread safety
  • Persistence across init

Authentication

  • Login with valid credentials
  • Reject invalid credentials
  • Token refresh
  • Session expiration
  • Logout clears state

Output Format

## Contract Tests: [Protocol Name]

### Protocol

protocol DataStore { ... }


### Behaviors Tested
| Behavior | Tests | Edge Cases |
|----------|-------|------------|
| save | 3 | empty title, duplicate ID |
| fetch | 2 | non-existent ID |
| delete | 2 | non-existent ID |
| fetchAll | 2 | empty store |
| invariants | 1 | count consistency |

### Implementations Tested
- [x] InMemoryDataStore — all passing
- [x] SQLiteDataStore — all passing
- [ ] CloudDataStore — pending implementation

### Files Created
- `Tests/Contracts/DataStoreContractTests.swift`
- `Tests/Contracts/InMemoryDataStoreContractTests.swift`

References

  • testing/tdd-feature/ — for TDD workflow using contract tests
  • generators/test-generator/ — for standard test generation
  • Design by Contract (Bertrand Meyer) — theoretical foundation

Other skills for the same job

different authors, same section of the catalogue
Webapp Testing
by anthropics
vendor ×12

Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.

6k tokens scripts
Finishing A Development Branch
by ZhanlinCui
×7

Use when implementation is complete, all tests pass, and you need to decide how to integrate the work - guides completion of development work by presenting structured options for merge, PR, or cleanup

1k tokens
Test Driven Development
by w95
×7

Use when implementing any feature or bugfix, before writing implementation code

2k tokens
Systematic Debugging
by ratacat
×7

Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes

10k tokens scripts
Verification Before Completion
by ZhanlinCui
×6

Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always

1k tokens
Backtest Expert
by BaggaT236
×3

Expert guidance for systematic backtesting of trading strategies. Use when developing, testing, stress-testing, or validating quantitative trading strategies. Covers "beating ideas to death" methodology, parameter robustness testing, slippage modeling, bias prevention, and interpreting backtest results. Applicable when user asks about backtesting, strategy validation, robustness testing, avoiding overfitting, or systematic trading development.

15k tokens scripts
Adaptyv
by christophacham
×3

Cloud laboratory platform for automated protein testing and validation. Use when designing proteins and needing experimental validation including binding assays, expression testing, thermostability measurements, enzyme activity assays, or protein sequence optimization. Also use for submitting experiments via API, tracking experiment status, downloading results, optimizing protein sequences for better expression using computational tools (NetSolP, SoluProt, SolubleMPNN, ESM), or managing protein design workflows with wet-lab validation.

16k tokens
Aeon
by christophacham
×3

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

19k tokens

How to use it

Copy the folder

Take rshankras/test-contract from the repository into ~/.claude/skills for personal use, or into .claude/skills inside a project.

Check the name does not clash

The agent identifies a skill by the name field in its header. Two skills with the same name cannot sit side by side — one of them will be ignored.