CodeSampleX

Beispiel

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

Verifiziertes Beispiel für golang go.uber.org/mock v0.5.0: gomock.Controller. Der Vertrag lief auf go 1.26 · linux alpine/x64 · docker und bestand.

sha256:446576c22a5a16709f614a4bc15672b79cc6063f650b801d43155a04840fe30f

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
2
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung linux 24 · ubuntu · glibc 2.39 x64 go

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
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

Fall

HOW
Ziel
verify go.uber.org/mock/gomock.Controller in pkg:golang/go.uber.org/mock@v0.5.0
Pakete
Symbole
  • go.uber.org/mock/gomock.Controller
Erstellt
2026-08-26T12:54:25Z

Contract

  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

Dateien

  • PROMPT.md
  • controller_test.go
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • store.go

Quellartefakt herunterladen (tar.gz)

Quelltext

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)
}

Ursprungs-Seeder

anonym