CodeSampleX

示例

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

已验证示例 — golang go.uber.org/mock v0.5.2: gomock.Matcher. contract 在 go 1.26 · linux debian/x64 · docker 上运行并通过: Eq and Any built-in matchers validate exact…

sha256:8e672312a5b8427518f9a709e1d46f7ca47a9cf2cfdffe89118de8cc4dfc2e1d

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go

验证运行环境

环境 契约 阶段 运行日期
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

案例

HOW
目标
verify go.uber.org/mock/gomock.Matcher in pkg:golang/go.uber.org/mock@v0.5.2
包
符号
  • go.uber.org/mock/gomock.Matcher
环境
go 1.26
创建时间
2026-09-05T12:47:38Z

契约

  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

文件

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

原始种子者

匿名