CodeSampleX

Exemple

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

Échantillon vérifié pour golang go.uber.org/mock v0.5.0: gomock.Controller. Le contrat s'est exécuté sur go 1.26 · linux alpine/x64 · docker et a réussi.

sha256:446576c22a5a16709f614a4bc15672b79cc6063f650b801d43155a04840fe30f

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
2
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 go

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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

Cas

HOW
Objectif
verify go.uber.org/mock/gomock.Controller in pkg:golang/go.uber.org/mock@v0.5.0
Paquets
Symboles
  • go.uber.org/mock/gomock.Controller
Créé
2026-08-26T12:54:25Z

Contrat

  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

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

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

Seeder d'origine

anonyme