CodeSampleX

Beispiel

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

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

sha256:7c74a3cc1d2f4cf63d28ce0747a90517185552f18d2524f8a9ac21918e663f7f

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
1
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

Umgebungen der Verifizierungsläufe

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

Fall

HOW
Ziel
verify go.uber.org/mock/gomock.WithContext in pkg:golang/go.uber.org/mock@v0.5.2
Pakete
Symbole
  • go.uber.org/mock/gomock.WithContext
Umgebung
go 1.26.6
Erstellt
2026-09-05T13:39:20Z

Contract

  1. gomock.WithContext returns a Controller and a Context derived from the parent context
  2. mock expectations registered with the returned Controller execute and verify successfully
  3. the returned Context is cancelled when a fatal mock failure occurs
  4. parent context cancellation propagates to the derived Context returned by WithContext
  5. successful mock executions keep the derived Context active and error-free

Dateien

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • task.go
  • test/contract_test.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.WithContext 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.WithContext
Required runtime conditions:
  - ecosystem: golang
  - language: go
  - packageManager: go@1.26.6
  - runtime: go@1.26.6

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:e52b950c9c0490f50147927c79aa2b01a8074d3091ca8a585981c84ad01b438d","contract":["gomock.WithContext returns a Controller and a Context derived from the parent context","mock expectations registered with the returned Controller execute and verify successfully","the returned Context is cancelled when a fatal mock failure occurs","parent context cancellation propagates to the derived Context returned by WithContext","successful mock executions keep the derived Context active and error-free"],"goal":"verify go.uber.org/mock/gomock.WithContext 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.WithContext"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","packageManagerVersion":"1.26.6","runtime":"go","runtimeVersion":"1.26.6","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.WithContext"],"verifierAdapter":"golang@1"}
go.mod
module example.com/gomock-withcontext

go 1.24.0

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=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify go.uber.org/mock/gomock.WithContext 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.WithContext"
  ],
  "runtimeConditions": {
    "ecosystem": "golang",
    "language": "go",
    "packageManager": "go@1.26.6",
    "runtime": "go@1.26.6"
  }
}
task.go
package sample

import (
	"context"
	"errors"
	"reflect"

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

// TaskProcessor defines operations for processing asynchronous tasks.
type TaskProcessor interface {
	ProcessTask(ctx context.Context, taskID string) (string, error)
}

// MockTaskProcessor is a mock implementation of TaskProcessor.
type MockTaskProcessor struct {
	ctrl     *gomock.Controller
	recorder *MockTaskProcessorMockRecorder
}

// MockTaskProcessorMockRecorder records expected invocations on MockTaskProcessor.
type MockTaskProcessorMockRecorder struct {
	mock *MockTaskProcessor
}

// NewMockTaskProcessor creates a new mock instance.
func NewMockTaskProcessor(ctrl *gomock.Controller) *MockTaskProcessor {
	mock := &MockTaskProcessor{ctrl: ctrl}
	mock.recorder = &MockTaskProcessorMockRecorder{mock: mock}
	return mock
}

// EXPECT returns the mock recorder.
func (m *MockTaskProcessor) EXPECT() *MockTaskProcessorMockRecorder {
	return m.recorder
}

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

// ProcessTask indicates an expected call of ProcessTask.
func (mr *MockTaskProcessorMockRecorder) ProcessTask(ctx, taskID any) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProcessTask", reflect.TypeOf((*MockTaskProcessor)(nil).ProcessTask), ctx, taskID)
}

// Service executes task processing.
type Service struct {
	processor TaskProcessor
}

// NewService creates a new Service.
func NewService(processor TaskProcessor) *Service {
	return &Service{processor: processor}
}

// Run executes the task with context validation.
func (s *Service) Run(ctx context.Context, taskID string) (string, error) {
	if taskID == "" {
		return "", errors.New("task ID cannot be empty")
	}
	return s.processor.ProcessTask(ctx, taskID)
}
test/contract_test.go
package test

import (
	"context"
	"errors"
	"fmt"
	"testing"

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

type fatalCapturingReporter struct {
	fatalCalled bool
	message     string
}

func (r *fatalCapturingReporter) Errorf(format string, args ...any) {}

func (r *fatalCapturingReporter) Fatalf(format string, args ...any) {
	r.fatalCalled = true
	r.message = fmt.Sprintf(format, args...)
	// gomock expects Fatalf to abort execution (like testing.T.FailNow)
	panic("fatal mock failure: " + r.message)
}

func (r *fatalCapturingReporter) Helper() {}

func TestGomockWithContextContract(t *testing.T) {
	// 1. gomock.WithContext returns a Controller and a Context derived from the parent context
	parentCtx := context.Background()
	ctrl, mockCtx := gomock.WithContext(parentCtx, t)
	defer ctrl.Finish()

	if ctrl == nil {
		t.Fatal("expected non-nil Controller from gomock.WithContext")
	}
	if mockCtx == nil {
		t.Fatal("expected non-nil Context from gomock.WithContext")
	}

	// 5. successful mock executions keep the derived Context active and error-free
	if err := mockCtx.Err(); err != nil {
		t.Fatalf("expected active context, got: %v", err)
	}

	// 2. mock expectations registered with the returned Controller execute and verify successfully
	mockProcessor := sample.NewMockTaskProcessor(ctrl)
	service := sample.NewService(mockProcessor)

	mockProcessor.EXPECT().
		ProcessTask(mockCtx, "task-100").
		Return("completed", nil).
		Times(1)

	output, err := service.Run(mockCtx, "task-100")
	if err != nil {
		t.Fatalf("unexpected error running service: %v", err)
	}
	if output != "completed" {
		t.Fatalf("expected output 'completed', got %q", output)
	}
}

func TestWithContextFatalCancelsContext(t *testing.T) {
	// 3. the returned Context is cancelled when a fatal mock failure occurs
	reporter := &fatalCapturingReporter{}
	ctx := context.Background()
	ctrl, mockCtx := gomock.WithContext(ctx, reporter)

	mockProcessor := sample.NewMockTaskProcessor(ctrl)

	func() {
		defer func() {
			_ = recover()
		}()
		// Calling unexpected method triggers Fatalf, cancelling the derived mockCtx
		mockProcessor.ProcessTask(mockCtx, "unregistered-task")
	}()

	if !reporter.fatalCalled {
		t.Fatal("expected reporter.Fatalf to be called for unexpected call")
	}

	select {
	case <-mockCtx.Done():
		if !errors.Is(mockCtx.Err(), context.Canceled) {
			t.Fatalf("expected context.Canceled, got: %v", mockCtx.Err())
		}
	default:
		t.Fatal("expected mockCtx to be cancelled after fatal failure")
	}
}

func TestWithContextParentCancellation(t *testing.T) {
	// 4. parent context cancellation propagates to the derived Context returned by WithContext
	parentCtx, cancel := context.WithCancel(context.Background())
	ctrl, mockCtx := gomock.WithContext(parentCtx, t)
	defer ctrl.Finish()

	cancel()

	select {
	case <-mockCtx.Done():
		if !errors.Is(mockCtx.Err(), context.Canceled) {
			t.Fatalf("expected context.Canceled, got: %v", mockCtx.Err())
		}
	default:
		t.Fatal("expected mockCtx to be cancelled when parent context is cancelled")
	}
}

Ursprungs-Seeder

anonym