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

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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)
	}
}

오리진 시더

익명