CodeSampleX

샘플

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

검증된 샘플 — golang go.uber.org/mock v0.5.0: gomock.Controller. go 1.26 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: ctrl := gomock.NewController(t)…

sha256:446576c22a5a16709f614a4bc15672b79cc6063f650b801d43155a04840fe30f

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

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 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.Controller in pkg:golang/go.uber.org/mock@v0.5.0
패키지
심벌
  • go.uber.org/mock/gomock.Controller
생성일
2026-08-26T12:54:25Z

컨트랙트

  1. ctrl := gomock.NewController(t) creates a Controller managing mock lifecycle and expectations
  2. mock.EXPECT().Method(...).Return(...).Times(1) records expected call and returns configured values
  3. ctrl.Satisfied() reports false before required mock calls and true after all expectations are met
  4. gomock.InOrder enforces sequential call ordering across mock expectations
  5. ctrl.Finish() completes cleanly on satisfied expectations or reports failure on unfulfilled calls

파일

  • PROMPT.md
  • controller_test.go
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • store.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.Controller 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.Controller

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.
controller_test.go
package gomockdemo_test

import (
	"context"
	"errors"
	"fmt"
	"testing"

	"example.com/gomockdemo"
	"go.uber.org/mock/gomock"
)

type dummyReporter struct {
	failed   bool
	messages []string
}

func (r *dummyReporter) Errorf(format string, args ...any) {
	r.failed = true
	r.messages = append(r.messages, fmt.Sprintf(format, args...))
}

func (r *dummyReporter) Fatalf(format string, args ...any) {
	r.failed = true
	r.messages = append(r.messages, fmt.Sprintf(format, args...))
}

func (r *dummyReporter) Helper() {}

func TestControllerBasicLifecycle(t *testing.T) {
	ctrl := gomock.NewController(t)
	mock := gomockdemo.NewMockKeyValueStore(ctrl)

	ctx := context.Background()
	mock.EXPECT().Get(ctx, "session:1").Return("token_abc", nil).Times(1)

	// Controller should not be satisfied before the expected call is made
	if ctrl.Satisfied() {
		t.Fatal("expected ctrl.Satisfied() to be false before call invocation")
	}

	val, err := mock.Get(ctx, "session:1")
	if err != nil {
		t.Fatalf("unexpected error from mock.Get: %v", err)
	}
	if val != "token_abc" {
		t.Fatalf("expected 'token_abc', got %q", val)
	}

	// Controller must be satisfied after expected call is made
	if !ctrl.Satisfied() {
		t.Fatal("expected ctrl.Satisfied() to be true after call invocation")
	}

	ctrl.Finish()
}

func TestControllerInOrder(t *testing.T) {
	ctrl := gomock.NewController(t)
	mock := gomockdemo.NewMockKeyValueStore(ctrl)

	ctx := context.Background()
	call1 := mock.EXPECT().Set(ctx, "key1", "val1").Return(nil)
	call2 := mock.EXPECT().Get(ctx, "key1").Return("val1", nil)

	gomock.InOrder(call1, call2)

	if err := mock.Set(ctx, "key1", "val1"); err != nil {
		t.Fatalf("Set failed: %v", err)
	}

	val, err := mock.Get(ctx, "key1")
	if err != nil || val != "val1" {
		t.Fatalf("Get returned (%q, %v), expected ('val1', nil)", val, err)
	}

	if !ctrl.Satisfied() {
		t.Fatal("expected controller to be satisfied after sequenced calls")
	}

	ctrl.Finish()
}

func TestControllerDoAndReturn(t *testing.T) {
	ctrl := gomock.NewController(t)
	mock := gomockdemo.NewMockKeyValueStore(ctrl)

	deletedKeys := make(map[string]bool)
	mock.EXPECT().Delete(gomock.Any(), gomock.Any()).DoAndReturn(
		func(ctx context.Context, key string) error {
			if key == "" {
				return errors.New("empty key")
			}
			deletedKeys[key] = true
			return nil
		},
	).Times(2)

	ctx := context.Background()
	if err := mock.Delete(ctx, "item1"); err != nil {
		t.Fatalf("unexpected error deleting item1: %v", err)
	}
	if err := mock.Delete(ctx, ""); err == nil {
		t.Fatal("expected error deleting empty key")
	}

	if !deletedKeys["item1"] {
		t.Fatal("expected item1 to be recorded as deleted")
	}

	if !ctrl.Satisfied() {
		t.Fatal("expected controller to be satisfied")
	}

	ctrl.Finish()
}

func TestControllerUnsatisfiedExpectation(t *testing.T) {
	reporter := &dummyReporter{}
	ctrl := gomock.NewController(reporter)
	mock := gomockdemo.NewMockKeyValueStore(ctrl)

	mock.EXPECT().Get(gomock.Any(), "missing_key").Return("none", nil).Times(1)

	if ctrl.Satisfied() {
		t.Fatal("expected ctrl.Satisfied() to be false when expectation is uncalled")
	}

	// Calling Finish without fulfilling expectations should report failure to reporter
	ctrl.Finish()

	if !reporter.failed {
		t.Fatal("expected reporter.failed to be true for unsatisfied expectation")
	}
}
csx.json
{"case":{"caseId":"case:sha256:04eacaf7dda66ba0d833e6ef7f5a8f90abdd803141df694f99dbc922dace70ba","contract":["ctrl := gomock.NewController(t) creates a Controller managing mock lifecycle and expectations","mock.EXPECT().Method(...).Return(...).Times(1) records expected call and returns configured values","ctrl.Satisfied() reports false before required mock calls and true after all expectations are met","gomock.InOrder enforces sequential call ordering across mock expectations","ctrl.Finish() completes cleanly on satisfied expectations or reports failure on unfulfilled calls"],"goal":"verify go.uber.org/mock/gomock.Controller 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.Controller"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","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.Controller"],"verifierAdapter":"golang@1"}
go.mod
module example.com/gomockdemo

go 1.22

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=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify go.uber.org/mock/gomock.Controller 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.Controller"
  ]
}
store.go
package gomockdemo

import (
	"context"
	"reflect"

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

// KeyValueStore defines the interface for key-value storage operations.
type KeyValueStore interface {
	Get(ctx context.Context, key string) (string, error)
	Set(ctx context.Context, key string, val string) error
	Delete(ctx context.Context, key string) error
}

// MockKeyValueStore is a gomock 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 string, val string) error {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "Set", ctx, key, val)
	ret0, _ := ret[0].(error)
	return ret0
}

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

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

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

오리진 시더

익명