CodeSampleX

サンプル

go.uber.org/mock v0.5.0: gomock.Call

検証済みサンプル — golang go.uber.org/mock v0.5.0: gomock.Call. go 1.26 · linux alpine/x64 · docker で contract を実行し、成功しました: Return sets expected method return values

sha256:53768bec41a2cab7c76deb808902157b0569a27adfc1ea1e61005679971f64a2

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
2
ビルドした署名鍵
1
宣言された環境 go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go

検証実行環境

環境 コントラクト ステージ 実行日
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-26
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-07

ケース

HOW
ゴール
verify go.uber.org/mock/gomock.Call in pkg:golang/go.uber.org/mock@v0.5.0
パッケージ
シンボル
  • go.uber.org/mock/gomock.Call
環境
go 1.26
作成日
2026-08-26T12:50:21Z

コントラクト

  1. Return sets expected method return values
  2. Do executes a custom callback function with invocation arguments
  3. DoAndReturn calculates dynamic return values based on input arguments
  4. Times MinTimes MaxTimes and AnyTimes constrain mock call invocation frequencies
  5. SetArg mutates caller-provided pointer arguments upon invocation
  6. After enforces prerequisite call ordering between specific mock expectations

ファイル

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • mock.go
  • spec.json
  • test/contract_test.go

ソースアーティファクトをダウンロード (tar.gz)

ソース

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify go.uber.org/mock/gomock.Call in pkg:golang/go.uber.org/mock@v0.5.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.uber.org/mock@v0.5.0
Demonstrate these symbols/APIs:
  - go.uber.org/mock/gomock.Call

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:84f92a0c2575bbaf899570f8a732e13a230109c18ea4e6c95e6e6df9c8f7bbc8","contract":["Return sets expected method return values","Do executes a custom callback function with invocation arguments","DoAndReturn calculates dynamic return values based on input arguments","Times MinTimes MaxTimes and AnyTimes constrain mock call invocation frequencies","SetArg mutates caller-provided pointer arguments upon invocation","After enforces prerequisite call ordering between specific mock expectations"],"goal":"verify go.uber.org/mock/gomock.Call in pkg:golang/go.uber.org/mock@v0.5.0","kind":"HOW","packages":["pkg:golang/go.uber.org/mock@v0.5.0"],"schemaVersion":1,"symbols":["go.uber.org/mock/gomock.Call"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","moduleSystem":"go.mod","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"go","runtimeVersion":"1.26","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/go.uber.org/mock@v0.5.0"],"schemaVersion":1,"subject":"pkg:golang/go.uber.org/mock@v0.5.0","symbols":["go.uber.org/mock/gomock.Call"],"verifierAdapter":"golang@1"}
go.mod
module example.com/gomock-call

go 1.24.0

require go.uber.org/mock v0.5.0
go.sum
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
mock.go
package sample

import (
	"context"
	"reflect"

	"go.uber.org/mock/gomock"
)

// KeyValueStore defines storage operations for key-value pairs.
type KeyValueStore interface {
	Get(ctx context.Context, key string) (string, error)
	Set(ctx context.Context, key, value string) error
	ReadInto(ctx context.Context, key string, buf *[]byte) error
}

// MockKeyValueStore is a mock implementation of KeyValueStore.
type MockKeyValueStore struct {
	ctrl     *gomock.Controller
	recorder *MockKeyValueStoreMockRecorder
}

// MockKeyValueStoreMockRecorder is the mock recorder for MockKeyValueStore.
type MockKeyValueStoreMockRecorder struct {
	mock *MockKeyValueStore
}

// NewMockKeyValueStore creates a new mock instance.
func NewMockKeyValueStore(ctrl *gomock.Controller) *MockKeyValueStore {
	mock := &MockKeyValueStore{ctrl: ctrl}
	mock.recorder = &MockKeyValueStoreMockRecorder{mock: mock}
	return mock
}

// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockKeyValueStore) EXPECT() *MockKeyValueStoreMockRecorder {
	return m.recorder
}

// Get mocks base method.
func (m *MockKeyValueStore) Get(ctx context.Context, key string) (string, error) {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "Get", ctx, key)
	ret0, _ := ret[0].(string)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}

// Get indicates an expected call of Get.
func (mr *MockKeyValueStoreMockRecorder) Get(ctx, key any) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockKeyValueStore)(nil).Get), ctx, key)
}

// Set mocks base method.
func (m *MockKeyValueStore) Set(ctx context.Context, key, value string) error {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "Set", ctx, key, value)
	ret0, _ := ret[0].(error)
	return ret0
}

// Set indicates an expected call of Set.
func (mr *MockKeyValueStoreMockRecorder) Set(ctx, key, value any) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Set", reflect.TypeOf((*MockKeyValueStore)(nil).Set), ctx, key, value)
}

// ReadInto mocks base method.
func (m *MockKeyValueStore) ReadInto(ctx context.Context, key string, buf *[]byte) error {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "ReadInto", ctx, key, buf)
	ret0, _ := ret[0].(error)
	return ret0
}

// ReadInto indicates an expected call of ReadInto.
func (mr *MockKeyValueStoreMockRecorder) ReadInto(ctx, key, buf any) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReadInto", reflect.TypeOf((*MockKeyValueStore)(nil).ReadInto), ctx, key, buf)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify go.uber.org/mock/gomock.Call in pkg:golang/go.uber.org/mock@v0.5.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.uber.org/mock@v0.5.0"
  ],
  "symbols": [
    "go.uber.org/mock/gomock.Call"
  ]
}
test/contract_test.go
package test

import (
	"context"
	"errors"
	"testing"

	sample "example.com/gomock-call"
	"go.uber.org/mock/gomock"
)

func TestGomockCallReturnAndDoContract(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	mockStore := sample.NewMockKeyValueStore(ctrl)
	ctx := context.Background()

	// 1. Return configures static return values
	mockStore.EXPECT().
		Get(ctx, "item-1").
		Return("value-1", nil).
		Times(1)

	val, err := mockStore.Get(ctx, "item-1")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if val != "value-1" {
		t.Fatalf("expected 'value-1', got %q", val)
	}

	// 2. Do captures invocation arguments as a side effect
	var capturedKey, capturedVal string
	mockStore.EXPECT().
		Set(ctx, gomock.Any(), gomock.Any()).
		Do(func(_ context.Context, k, v string) {
			capturedKey = k
			capturedVal = v
		}).
		Return(nil).
		Times(1)

	if err := mockStore.Set(ctx, "logged-key", "logged-value"); err != nil {
		t.Fatalf("unexpected set error: %v", err)
	}
	if capturedKey != "logged-key" || capturedVal != "logged-value" {
		t.Fatalf("Do hook did not capture arguments correctly: %q, %q", capturedKey, capturedVal)
	}

	// 3. DoAndReturn dynamically computes return values based on arguments
	mockStore.EXPECT().
		Get(ctx, gomock.Any()).
		DoAndReturn(func(_ context.Context, key string) (string, error) {
			if key == "missing" {
				return "", errors.New("not found")
			}
			return "computed:" + key, nil
		}).
		Times(2)

	dynVal, err := mockStore.Get(ctx, "dynamic-key")
	if err != nil || dynVal != "computed:dynamic-key" {
		t.Fatalf("unexpected DoAndReturn result: val=%q err=%v", dynVal, err)
	}

	_, err = mockStore.Get(ctx, "missing")
	if err == nil || err.Error() != "not found" {
		t.Fatalf("expected 'not found' error, got %v", err)
	}
}

func TestGomockCallConstraintsAndOrderingContract(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	mockStore := sample.NewMockKeyValueStore(ctrl)
	ctx := context.Background()

	// 4. Times, MinTimes, MaxTimes, and AnyTimes constrain call frequencies
	mockStore.EXPECT().
		Get(ctx, "exact-twice").
		Return("two", nil).
		Times(2)

	mockStore.EXPECT().
		Get(ctx, "bounded").
		Return("bound", nil).
		MinTimes(1).
		MaxTimes(3)

	mockStore.EXPECT().
		Get(ctx, "anytime").
		Return("ok", nil).
		AnyTimes()

	// Satisfy exact count
	mockStore.Get(ctx, "exact-twice")
	mockStore.Get(ctx, "exact-twice")

	// Satisfy bounded count (2 calls is within [1, 3])
	mockStore.Get(ctx, "bounded")
	mockStore.Get(ctx, "bounded")

	// Satisfy AnyTimes (1 call)
	mockStore.Get(ctx, "anytime")

	// 5. SetArg modifies pointer or slice arguments passed by caller
	mockStore.EXPECT().
		ReadInto(ctx, "binary-key", gomock.Any()).
		SetArg(2, []byte("injected-payload")).
		Return(nil).
		Times(1)

	var targetBuf []byte
	if err := mockStore.ReadInto(ctx, "binary-key", &targetBuf); err != nil {
		t.Fatalf("unexpected ReadInto error: %v", err)
	}
	if string(targetBuf) != "injected-payload" {
		t.Fatalf("expected SetArg to populate 'injected-payload', got %q", string(targetBuf))
	}

	// 6. After enforces prerequisite call order between specific calls
	step1 := mockStore.EXPECT().
		Set(ctx, "step1", "done").
		Return(nil)

	mockStore.EXPECT().
		Set(ctx, "step2", "done").
		Return(nil).
		After(step1)

	if err := mockStore.Set(ctx, "step1", "done"); err != nil {
		t.Fatalf("step1 failed: %v", err)
	}
	if err := mockStore.Set(ctx, "step2", "done"); err != nil {
		t.Fatalf("step2 failed: %v", err)
	}
}

オリジンシーダー

匿名