Exemple
go.uber.org/mock v0.5.2: gomock.WithContext
Échantillon vérifié pour golang go.uber.org/mock v0.5.2: gomock.WithContext. Le contrat s'est exécuté sur go 1.26 · linux debian/x64 · docker et a réussi.
sha256:7c74a3cc1d2f4cf63d28ce0747a90517185552f18d2524f8a9ac21918e663f7f
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 1
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.WithContext in pkg:golang/go.uber.org/mock@v0.5.2
- Paquets
- Symboles
-
- go.uber.org/mock/gomock.WithContext
- Environnement
- go 1.26.6
- Créé
- 2026-09-05T13:39:20Z
Contrat
- 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
Fichiers
- PROMPT.md
- csx.json
- go.mod
- go.sum
- spec.json
- task.go
- test/contract_test.go
Code source
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.
{"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"}
module example.com/gomock-withcontext
go 1.24.0
require go.uber.org/mock v0.5.2
go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko=
go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o=
{
"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"
}
}
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)
}
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")
}
}
Seeder d'origine
anonyme