CodeSampleX

Exemple

go.uber.org/mock v0.5.2: gomock.Matcher

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

sha256:8e672312a5b8427518f9a709e1d46f7ca47a9cf2cfdffe89118de8cc4dfc2e1d

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
1
Clés de signature qui l’ont compilé
1
Environnement déclaré go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go

Environnements des exécutions de vérification

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

Cas

HOW
Objectif
verify go.uber.org/mock/gomock.Matcher in pkg:golang/go.uber.org/mock@v0.5.2
Paquets
Symboles
  • go.uber.org/mock/gomock.Matcher
Environnement
go 1.26
Créé
2026-09-05T12:47:38Z

Contrat

  1. Eq and Any built-in matchers validate exact values and arbitrary arguments
  2. Nil and Not matchers verify nil references and negate inner matchers
  3. All combines multiple matchers requiring all conditions to be satisfied
  4. Len and Cond matchers evaluate slice length and custom typed predicates
  5. Custom types implementing gomock.Matcher interface provide domain-specific argument verification

Fichiers

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • mock.go
  • spec.json
  • test/contract_test.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.Matcher in pkg:golang/go.uber.org/mock@v0.5.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.uber.org/mock@v0.5.2
Demonstrate these symbols/APIs:
  - go.uber.org/mock/gomock.Matcher

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:4db397604037ed5c33c32a6087331ca945b946628ba0659fb836c6f80013ce1b","contract":["Eq and Any built-in matchers validate exact values and arbitrary arguments","Nil and Not matchers verify nil references and negate inner matchers","All combines multiple matchers requiring all conditions to be satisfied","Len and Cond matchers evaluate slice length and custom typed predicates","Custom types implementing gomock.Matcher interface provide domain-specific argument verification"],"goal":"verify go.uber.org/mock/gomock.Matcher in pkg:golang/go.uber.org/mock@v0.5.2","kind":"HOW","packages":["pkg:golang/go.uber.org/mock@v0.5.2"],"schemaVersion":1,"symbols":["go.uber.org/mock/gomock.Matcher"]},"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.2"],"schemaVersion":1,"subject":"pkg:golang/go.uber.org/mock@v0.5.2","symbols":["go.uber.org/mock/gomock.Matcher"],"verifierAdapter":"golang@1"}
go.mod
module example.com/gomock-matcher

go 1.26.6

require go.uber.org/mock v0.5.2
go.sum
go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko=
go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o=
mock.go
package sample

import (
	"context"
	"reflect"

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

// UserRepository defines operations on user accounts.
type UserRepository interface {
	GetUser(ctx context.Context, id string) (string, error)
	SaveUser(ctx context.Context, id string, roles []string) error
	DeleteUser(ctx context.Context, id string, metadata map[string]string) error
}

// MockUserRepository is a mock implementation of UserRepository.
type MockUserRepository struct {
	ctrl     *gomock.Controller
	recorder *MockUserRepositoryMockRecorder
}

// MockUserRepositoryMockRecorder is the mock recorder for MockUserRepository.
type MockUserRepositoryMockRecorder struct {
	mock *MockUserRepository
}

// NewMockUserRepository creates a new mock instance.
func NewMockUserRepository(ctrl *gomock.Controller) *MockUserRepository {
	mock := &MockUserRepository{ctrl: ctrl}
	mock.recorder = &MockUserRepositoryMockRecorder{mock: mock}
	return mock
}

// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockUserRepository) EXPECT() *MockUserRepositoryMockRecorder {
	return m.recorder
}

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

// GetUser indicates an expected call of GetUser.
func (mr *MockUserRepositoryMockRecorder) GetUser(ctx, id any) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUser", reflect.TypeOf((*MockUserRepository)(nil).GetUser), ctx, id)
}

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

// SaveUser indicates an expected call of SaveUser.
func (mr *MockUserRepositoryMockRecorder) SaveUser(ctx, id, roles any) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveUser", reflect.TypeOf((*MockUserRepository)(nil).SaveUser), ctx, id, roles)
}

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

// DeleteUser indicates an expected call of DeleteUser.
func (mr *MockUserRepositoryMockRecorder) DeleteUser(ctx, id, metadata any) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUser", reflect.TypeOf((*MockUserRepository)(nil).DeleteUser), ctx, id, metadata)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify go.uber.org/mock/gomock.Matcher in pkg:golang/go.uber.org/mock@v0.5.2",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.uber.org/mock@v0.5.2"
  ],
  "symbols": [
    "go.uber.org/mock/gomock.Matcher"
  ]
}
test/contract_test.go
package test

import (
	"context"
	"strings"
	"testing"

	sample "example.com/gomock-matcher"
	"go.uber.org/mock/gomock"
)

type prefixMatcher struct {
	prefix string
}

func (p prefixMatcher) Matches(x any) bool {
	s, ok := x.(string)
	return ok && strings.HasPrefix(s, p.prefix)
}

func (p prefixMatcher) String() string {
	return "has prefix " + p.prefix
}

func TestGomockMatcherBuiltinContract(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	mockRepo := sample.NewMockUserRepository(ctrl)
	ctx := context.Background()

	// 1. Eq and Any built-in matchers validate exact values and arbitrary arguments
	mockRepo.EXPECT().
		GetUser(gomock.Any(), gomock.Eq("alice")).
		Return("alice_profile", nil).
		Times(1)

	val, err := mockRepo.GetUser(ctx, "alice")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if val != "alice_profile" {
		t.Fatalf("expected 'alice_profile', got %q", val)
	}

	// 2. Nil and Not matchers verify nil references and negate inner matchers
	mockRepo.EXPECT().
		DeleteUser(gomock.Any(), gomock.Not(gomock.Eq("admin")), gomock.Nil()).
		Return(nil).
		Times(1)

	if err := mockRepo.DeleteUser(ctx, "guest", nil); err != nil {
		t.Fatalf("unexpected DeleteUser error: %v", err)
	}

	// 3. All combines multiple matchers requiring all conditions to be satisfied
	mockRepo.EXPECT().
		SaveUser(gomock.Any(), gomock.Eq("bob"), gomock.All(gomock.Len(2), gomock.InAnyOrder([]string{"reader", "writer"}))).
		Return(nil).
		Times(1)

	if err := mockRepo.SaveUser(ctx, "bob", []string{"writer", "reader"}); err != nil {
		t.Fatalf("unexpected SaveUser error: %v", err)
	}
}

func TestGomockMatcherCustomAndPredicatesContract(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	mockRepo := sample.NewMockUserRepository(ctrl)
	ctx := context.Background()

	// 4. Len and Cond matchers evaluate slice length and custom typed predicates
	mockRepo.EXPECT().
		GetUser(gomock.Any(), gomock.Cond(func(x string) bool { return len(x) > 5 })).
		Return("long_user", nil).
		Times(1)

	val, err := mockRepo.GetUser(ctx, "charlie")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if val != "long_user" {
		t.Fatalf("expected 'long_user', got %q", val)
	}

	// 5. Custom types implementing gomock.Matcher interface provide domain-specific argument verification
	mockRepo.EXPECT().
		GetUser(gomock.Any(), prefixMatcher{prefix: "team:"}).
		Return("team_data", nil).
		Times(1)

	val, err = mockRepo.GetUser(ctx, "team:ops")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if val != "team_data" {
		t.Fatalf("expected 'team_data', got %q", val)
	}
}

Seeder d'origine

anonyme