CodeSampleX

示例

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

已验证示例 — golang go.uber.org/mock v0.5.0: gomock.Call. contract 在 go 1.26 · linux alpine/x64 · docker 上运行并通过: Return sets expected method return values

sha256:53768bec41a2cab7c76deb808902157b0569a27adfc1ea1e61005679971f64a2

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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)
	}
}

原始种子者

匿名