CodeSampleX

샘플

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

검증된 샘플 — golang go.uber.org/mock v0.5.2: gomock.Matcher. go 1.26 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: Eq and Any built-in matchers validate…

sha256:8e672312a5b8427518f9a709e1d46f7ca47a9cf2cfdffe89118de8cc4dfc2e1d

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

오리진 시더

익명