CodeSampleX

示例

github.com/stretchr/testify v1.11.1: Verify testify mock method call expectations, argument matchers, and return values

已验证示例 — golang github.com/stretchr/testify v1.11.1: Verify testify mock method call expectations, argument matchers, and return values. contract 在 go 1.26 …

sha256:1354203e1c5d9064c73519c4f1bf57081ea1dae1494ac6d0643d617b32dc10e0

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

执行证据

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

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

验证运行环境

环境 契约 阶段 运行日期
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-23

案例

HOW
目标
Verify testify mock method call expectations, argument matchers, and return values
包
创建时间
2026-08-23T06:08:36Z

契约

  1. mock.Mock.On registers expected method calls and returns configured values upon mock.Mock.Called
  2. mock.MatchedBy matches method arguments using custom predicate functions
  3. mock.Anything and mock.AnythingOfType match arbitrary arguments and type-specific arguments
  4. mock.Mock.AssertExpectations verifies that all expected calls were executed
  5. mock.Mock.AssertCalled and mock.Mock.AssertNotCalled verify whether specific method invocations occurred

文件

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.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 testify mock method call expectations, argument matchers, and return values
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/stretchr/testify@v1.11.1

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:8df1ca1b03a969101ac8d2ddbbed481fe9752e91b52e7dadef4634bd2981dfe7","contract":["mock.Mock.On registers expected method calls and returns configured values upon mock.Mock.Called","mock.MatchedBy matches method arguments using custom predicate functions","mock.Anything and mock.AnythingOfType match arbitrary arguments and type-specific arguments","mock.Mock.AssertExpectations verifies that all expected calls were executed","mock.Mock.AssertCalled and mock.Mock.AssertNotCalled verify whether specific method invocations occurred"],"goal":"Verify testify mock method call expectations, argument matchers, and return values","kind":"HOW","packages":["pkg:golang/github.com/stretchr/testify@v1.11.1"],"schemaVersion":1},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/stretchr/testify@v1.11.1"],"schemaVersion":1,"subject":"pkg:golang/github.com/stretchr/testify@v1.11.1","verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.26.6

require github.com/stretchr/testify v1.11.1

require (
	github.com/davecgh/go-spew v1.1.1 // indirect
	github.com/pmezard/go-difflib v1.0.0 // indirect
	github.com/stretchr/objx v0.5.2 // indirect
	gopkg.in/yaml.v3 v3.0.1 // indirect
)
go.sum
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
main.go
package main

import (
	"errors"
	"fmt"
	"log"

	"github.com/stretchr/testify/mock"
)

// DataStore represents a service interface to mock.
type DataStore interface {
	GetUser(id int) (string, error)
	SaveUser(id int, name string) bool
	CalculateScore(multiplier int, tag string) int
}

// MockDataStore is a mock implementation of DataStore.
type MockDataStore struct {
	mock.Mock
}

func (m *MockDataStore) GetUser(id int) (string, error) {
	args := m.Called(id)
	return args.String(0), args.Error(1)
}

func (m *MockDataStore) SaveUser(id int, name string) bool {
	args := m.Called(id, name)
	return args.Bool(0)
}

func (m *MockDataStore) CalculateScore(multiplier int, tag string) int {
	args := m.Called(multiplier, tag)
	return args.Int(0)
}

func main() {
	mockStore := new(MockDataStore)

	// 1. Setup exact argument match expectation with Return
	mockStore.On("GetUser", 42).Return("Alice", nil)
	mockStore.On("GetUser", 99).Return("", errors.New("user not found"))

	// 2. Setup mock.MatchedBy predicate matcher
	mockStore.On("SaveUser", mock.MatchedBy(func(id int) bool {
		return id > 0 && id < 1000
	}), mock.AnythingOfType("string")).Return(true)

	// 3. Setup mock.Anything matcher
	mockStore.On("CalculateScore", 10, mock.Anything).Return(100)

	// Execute calls
	user, err := mockStore.GetUser(42)
	if err != nil || user != "Alice" {
		log.Fatalf("unexpected GetUser(42) result: user=%q, err=%v", user, err)
	}
	fmt.Printf("GetUser(42) = %s\n", user)

	_, notFoundErr := mockStore.GetUser(99)
	if notFoundErr == nil {
		log.Fatalf("expected error for GetUser(99), got nil")
	}
	fmt.Printf("GetUser(99) returned expected error: %v\n", notFoundErr)

	saved := mockStore.SaveUser(100, "Bob")
	if !saved {
		log.Fatalf("expected SaveUser to return true")
	}
	fmt.Printf("SaveUser(100, \"Bob\") = %v\n", saved)

	score := mockStore.CalculateScore(10, "admin-priority")
	if score != 100 {
		log.Fatalf("expected score 100, got %d", score)
	}
	fmt.Printf("CalculateScore(10, \"admin-priority\") = %d\n", score)

	fmt.Println("Testify mock demonstration completed successfully.")
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Verify testify mock method call expectations, argument matchers, and return values",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/stretchr/testify@v1.11.1"
  ]
}
test/contract.go
package main

import (
	"errors"
	"fmt"
	"os"

	"github.com/stretchr/testify/mock"
)

type dummyTestingT struct {
	errors []string
	failed bool
}

func (t *dummyTestingT) Logf(format string, args ...interface{}) {}
func (t *dummyTestingT) Errorf(format string, args ...interface{}) {
	t.errors = append(t.errors, fmt.Sprintf(format, args...))
	t.failed = true
}
func (t *dummyTestingT) FailNow() {
	t.failed = true
}

type ServiceMock struct {
	mock.Mock
}

func (m *ServiceMock) Fetch(id int) (string, error) {
	args := m.Called(id)
	return args.String(0), args.Error(1)
}

func (m *ServiceMock) Store(key string, val int) bool {
	args := m.Called(key, val)
	return args.Bool(0)
}

func (m *ServiceMock) Process(category string, count int) int {
	args := m.Called(category, count)
	return args.Int(0)
}

func main() {
	// Assertion 1: mock.Mock.On sets up method call expectations and returns configured Return values upon mock.Mock.Called
	{
		m := new(ServiceMock)
		expectedErr := errors.New("not found")
		m.On("Fetch", 1).Return("data-1", nil)
		m.On("Fetch", 2).Return("", expectedErr)

		gotStr1, gotErr1 := m.Fetch(1)
		if gotStr1 != "data-1" || gotErr1 != nil {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: Fetch(1) = (%q, %v), want (\"data-1\", nil)\n", gotStr1, gotErr1)
			os.Exit(1)
		}

		gotStr2, gotErr2 := m.Fetch(2)
		if gotStr2 != "" || !errors.Is(gotErr2, expectedErr) {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: Fetch(2) = (%q, %v), want (\"\", %v)\n", gotStr2, gotErr2, expectedErr)
			os.Exit(1)
		}
	}

	// Assertion 2: mock.MatchedBy matches method call arguments using custom predicate functions
	{
		m := new(ServiceMock)
		isPositive := func(val int) bool { return val > 0 }
		isNonEmpty := func(key string) bool { return len(key) > 0 }

		m.On("Store", mock.MatchedBy(isNonEmpty), mock.MatchedBy(isPositive)).Return(true)

		if ok := m.Store("session", 42); !ok {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: Store with matched arguments returned false, want true\n")
			os.Exit(1)
		}
	}

	// Assertion 3: mock.Anything and mock.AnythingOfType match any argument or argument of a specific type
	{
		m := new(ServiceMock)
		m.On("Process", mock.AnythingOfType("string"), mock.Anything).Return(999)

		result := m.Process("test-category", 12345)
		if result != 999 {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: Process returned %d, want 999\n", result)
			os.Exit(1)
		}
	}

	// Assertion 4: mock.Mock.AssertExpectations verifies that all expected method calls were executed
	{
		// Subtest A: satisfied expectations
		tSatisfied := &dummyTestingT{}
		mSatisfied := new(ServiceMock)
		mSatisfied.On("Fetch", 10).Return("ten", nil).Once()
		mSatisfied.Fetch(10)

		if !mSatisfied.AssertExpectations(tSatisfied) || tSatisfied.failed {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: AssertExpectations should return true for satisfied mock\n")
			os.Exit(1)
		}

		// Subtest B: unsatisfied expectations
		tUnsatisfied := &dummyTestingT{}
		mUnsatisfied := new(ServiceMock)
		mUnsatisfied.On("Fetch", 20).Return("twenty", nil).Once()
		// Do not call Fetch(20)

		if mUnsatisfied.AssertExpectations(tUnsatisfied) || !tUnsatisfied.failed {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: AssertExpectations should report failure for unsatisfied mock\n")
			os.Exit(1)
		}
	}

	// Assertion 5: mock.Mock.AssertCalled and mock.Mock.AssertNotCalled verify whether specific method invocations occurred
	{
		tCall := &dummyTestingT{}
		m := new(ServiceMock)
		m.On("Store", "config", 1).Return(true)
		m.Store("config", 1)

		if !m.AssertCalled(tCall, "Store", "config", 1) || tCall.failed {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: AssertCalled should return true for called method\n")
			os.Exit(1)
		}

		if !m.AssertNotCalled(tCall, "Fetch", 999) || tCall.failed {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: AssertNotCalled should return true for uncalled method\n")
			os.Exit(1)
		}
	}

	fmt.Println("All contract assertions passed.")
}

原始种子者

匿名