CodeSampleX

Пример

github.com/stretchr/testify v1.7.0: require

Проверенный пример — golang github.com/stretchr/testify v1.7.0: require. Контракт выполнен на go 1.26 · linux debian/x64 · docker и пройден.

sha256:f1dd66bc71151ccd932e2b561d47574a1542ebce0745942fb7f946062f7620f6

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

Среды запусков проверки

Окружение Контракт Этапы Запуск
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-06

Кейс

HOW
Цель
verify pkg:golang/github.com/stretchr/testify@v1.7.0
Пакеты
Символы
  • github.com/stretchr/testify/require
Окружение
go 1.26.6
Создан
2026-09-06T05:30:05Z

Контракт

  1. require.Equal returns silently without error or FailNow when primitive or composite values match
  2. require.Equal invokes Errorf and FailNow when primitive values differ
  3. require.Equal reports failure when numeric types differ even if underlying values match
  4. require.NotEqual succeeds on distinct values and invokes Errorf and FailNow on identical values
  5. require.True and require.False validate boolean values and invoke FailNow on unexpected conditions
  6. require.Nil and require.NotNil differentiate nil and non-nil pointers and invoke FailNow on mismatch
  7. require.NoError and require.Error validate error values and invoke FailNow when expectation is unmet
  8. require.Contains verifies substring and slice element containment and invokes FailNow when absent
  9. require.New creates an Assertions helper that executes assertions and invokes FailNow on failure

Файлы

  • 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 pkg:golang/github.com/stretchr/testify@v1.7.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/stretchr/testify@v1.7.0
Demonstrate these symbols/APIs:
  - github.com/stretchr/testify/require

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:5eed1d57fc642ec0f4e70bf05fd466ef4fbd1c6ce978f776247a0f5be1e87552","contract":["require.Equal returns silently without error or FailNow when primitive or composite values match","require.Equal invokes Errorf and FailNow when primitive values differ","require.Equal reports failure when numeric types differ even if underlying values match","require.NotEqual succeeds on distinct values and invokes Errorf and FailNow on identical values","require.True and require.False validate boolean values and invoke FailNow on unexpected conditions","require.Nil and require.NotNil differentiate nil and non-nil pointers and invoke FailNow on mismatch","require.NoError and require.Error validate error values and invoke FailNow when expectation is unmet","require.Contains verifies substring and slice element containment and invokes FailNow when absent","require.New creates an Assertions helper that executes assertions and invokes FailNow on failure"],"goal":"verify pkg:golang/github.com/stretchr/testify@v1.7.0","kind":"HOW","packages":["pkg:golang/github.com/stretchr/testify@v1.7.0"],"schemaVersion":1,"symbols":["github.com/stretchr/testify/require"]},"contractCommand":["go","run","./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/github.com/stretchr/testify@v1.7.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/stretchr/testify@v1.7.0","symbols":["github.com/stretchr/testify/require"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require github.com/stretchr/testify v1.7.0

require (
	github.com/davecgh/go-spew v1.1.0 // indirect
	github.com/pmezard/go-difflib v1.0.0 // indirect
	gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect
)
go.sum
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/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.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
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.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
main.go
package main

import (
	"fmt"

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

type demoTestingT struct {
	errors []string
	failed bool
}

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

func (t *demoTestingT) FailNow() {
	t.failed = true
}

type ServiceConfig struct {
	Port    int
	Host    string
	Tags    []string
	Enabled bool
}

func main() {
	t := &demoTestingT{}

	// 1. Primitive equality with require.Equal
	expectedHost := "localhost"
	actualHost := "localhost"
	require.Equal(t, expectedHost, actualHost, "host should match")

	// 2. Composite struct and slice equality
	cfgA := ServiceConfig{Port: 8080, Host: "localhost", Tags: []string{"web", "api"}, Enabled: true}
	cfgB := ServiceConfig{Port: 8080, Host: "localhost", Tags: []string{"web", "api"}, Enabled: true}
	require.Equal(t, cfgA, cfgB, "configurations must match")

	// 3. Collection containment
	require.Contains(t, cfgA.Tags, "api", "tags should contain api")

	// 4. Assertions instance via require.New
	req := require.New(t)
	req.True(cfgA.Enabled, "service must be enabled")
	req.NotNil(&cfgA, "config pointer should not be nil")
	req.NoError(nil, "startup error must be nil")

	if !t.failed {
		fmt.Printf("testify require demonstration completed successfully for %s:%d\n", cfgA.Host, cfgA.Port)
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/stretchr/testify@v1.7.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/stretchr/testify@v1.7.0"
  ],
  "symbols": [
    "github.com/stretchr/testify/require"
  ]
}
test/contract.go
package main

import (
	"errors"
	"fmt"
	"os"

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

type contractTestingT struct {
	errors        []string
	failed        bool
	failNowCalled bool
}

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

func (t *contractTestingT) FailNow() {
	t.failNowCalled = true
	panic("failnow_called")
}

func runRequireTest(fn func(t *contractTestingT)) (recordedError bool, failNowCalled bool, errMsg string) {
	mock := &contractTestingT{}
	defer func() {
		if r := recover(); r != nil {
			if str, ok := r.(string); ok && str == "failnow_called" {
				// expected FailNow panic
			} else {
				panic(r)
			}
		}
		recordedError = mock.failed
		failNowCalled = mock.failNowCalled
		if len(mock.errors) > 0 {
			errMsg = mock.errors[0]
		}
	}()
	fn(mock)
	return
}

type UserRecord struct {
	ID   int
	Role string
}

func main() {
	// Assertion 1: require.Equal returns silently without error or FailNow when primitive or composite values match
	{
		failed, failNow, _ := runRequireTest(func(t *contractTestingT) {
			require.Equal(t, 42, 42)
			require.Equal(t, "token-abc", "token-abc")
			require.Equal(t, []string{"alpha", "beta"}, []string{"alpha", "beta"})
			require.Equal(t, map[string]int{"k": 1}, map[string]int{"k": 1})
			require.Equal(t, UserRecord{ID: 1, Role: "admin"}, UserRecord{ID: 1, Role: "admin"})
		})
		if failed || failNow {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: require.Equal should pass with no error or FailNow on matching values\n")
			os.Exit(1)
		}
	}

	// Assertion 2: require.Equal invokes Errorf and FailNow when primitive values differ
	{
		failed, failNow, errMsg := runRequireTest(func(t *contractTestingT) {
			require.Equal(t, "expected", "actual")
		})
		if !failed || !failNow || errMsg == "" {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: require.Equal should invoke Errorf and FailNow on mismatched strings\n")
			os.Exit(1)
		}

		failedInt, failNowInt, _ := runRequireTest(func(t *contractTestingT) {
			require.Equal(t, 100, 200)
		})
		if !failedInt || !failNowInt {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: require.Equal should invoke Errorf and FailNow on mismatched ints\n")
			os.Exit(1)
		}
	}

	// Assertion 3: require.Equal reports failure when numeric types differ even if underlying values match
	{
		failed, failNow, _ := runRequireTest(func(t *contractTestingT) {
			require.Equal(t, int(50), int64(50))
		})
		if !failed || !failNow {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: require.Equal should report failure on int vs int64 type difference\n")
			os.Exit(1)
		}

		failedF, failNowF, _ := runRequireTest(func(t *contractTestingT) {
			require.Equal(t, float32(3.14), float64(3.14))
		})
		if !failedF || !failNowF {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: require.Equal should report failure on float32 vs float64 type difference\n")
			os.Exit(1)
		}
	}

	// Assertion 4: require.NotEqual succeeds on distinct values and invokes Errorf and FailNow on identical values
	{
		failed, failNow, _ := runRequireTest(func(t *contractTestingT) {
			require.NotEqual(t, "left", "right")
			require.NotEqual(t, 10, 20)
		})
		if failed || failNow {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: require.NotEqual should succeed on distinct values\n")
			os.Exit(1)
		}

		failedIdentical, failNowIdentical, _ := runRequireTest(func(t *contractTestingT) {
			require.NotEqual(t, "same", "same")
		})
		if !failedIdentical || !failNowIdentical {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: require.NotEqual should invoke Errorf and FailNow on identical values\n")
			os.Exit(1)
		}
	}

	// Assertion 5: require.True and require.False validate boolean values and invoke FailNow on unexpected conditions
	{
		failed, failNow, _ := runRequireTest(func(t *contractTestingT) {
			require.True(t, true)
			require.False(t, false)
		})
		if failed || failNow {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: require.True/False should pass on valid booleans\n")
			os.Exit(1)
		}

		failedTrue, failNowTrue, _ := runRequireTest(func(t *contractTestingT) {
			require.True(t, false)
		})
		if !failedTrue || !failNowTrue {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: require.True should fail and invoke FailNow on false\n")
			os.Exit(1)
		}

		failedFalse, failNowFalse, _ := runRequireTest(func(t *contractTestingT) {
			require.False(t, true)
		})
		if !failedFalse || !failNowFalse {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: require.False should fail and invoke FailNow on true\n")
			os.Exit(1)
		}
	}

	// Assertion 6: require.Nil and require.NotNil differentiate nil and non-nil pointers and invoke FailNow on mismatch
	{
		var nilPtr *string
		val := "active"
		failed, failNow, _ := runRequireTest(func(t *contractTestingT) {
			require.Nil(t, nil)
			require.Nil(t, nilPtr)
			require.NotNil(t, &val)
		})
		if failed || failNow {
			fmt.Fprintf(os.Stderr, "assertion 6 failed: require.Nil/NotNil should succeed on correct pointer types\n")
			os.Exit(1)
		}

		failedNil, failNowNil, _ := runRequireTest(func(t *contractTestingT) {
			require.Nil(t, &val)
		})
		if !failedNil || !failNowNil {
			fmt.Fprintf(os.Stderr, "assertion 6 failed: require.Nil should fail and invoke FailNow on non-nil pointer\n")
			os.Exit(1)
		}

		failedNotNil, failNowNotNil, _ := runRequireTest(func(t *contractTestingT) {
			require.NotNil(t, nil)
		})
		if !failedNotNil || !failNowNotNil {
			fmt.Fprintf(os.Stderr, "assertion 6 failed: require.NotNil should fail and invoke FailNow on nil\n")
			os.Exit(1)
		}
	}

	// Assertion 7: require.NoError and require.Error validate error values and invoke FailNow when expectation is unmet
	{
		testErr := errors.New("io timeout")
		failed, failNow, _ := runRequireTest(func(t *contractTestingT) {
			require.NoError(t, nil)
			require.Error(t, testErr)
		})
		if failed || failNow {
			fmt.Fprintf(os.Stderr, "assertion 7 failed: require.NoError/Error should succeed on expected error states\n")
			os.Exit(1)
		}

		failedNoErr, failNowNoErr, _ := runRequireTest(func(t *contractTestingT) {
			require.NoError(t, testErr)
		})
		if !failedNoErr || !failNowNoErr {
			fmt.Fprintf(os.Stderr, "assertion 7 failed: require.NoError should invoke FailNow when an error is present\n")
			os.Exit(1)
		}

		failedErr, failNowErr, _ := runRequireTest(func(t *contractTestingT) {
			require.Error(t, nil)
		})
		if !failedErr || !failNowErr {
			fmt.Fprintf(os.Stderr, "assertion 7 failed: require.Error should invoke FailNow when error is nil\n")
			os.Exit(1)
		}
	}

	// Assertion 8: require.Contains verifies substring and slice element containment and invokes FailNow when absent
	{
		items := []string{"apple", "banana", "cherry"}
		failed, failNow, _ := runRequireTest(func(t *contractTestingT) {
			require.Contains(t, "testify require package", "require")
			require.Contains(t, items, "banana")
		})
		if failed || failNow {
			fmt.Fprintf(os.Stderr, "assertion 8 failed: require.Contains should succeed when item is present\n")
			os.Exit(1)
		}

		failedStr, failNowStr, _ := runRequireTest(func(t *contractTestingT) {
			require.Contains(t, "hello world", "moon")
		})
		if !failedStr || !failNowStr {
			fmt.Fprintf(os.Stderr, "assertion 8 failed: require.Contains should invoke FailNow on missing substring\n")
			os.Exit(1)
		}

		failedSlice, failNowSlice, _ := runRequireTest(func(t *contractTestingT) {
			require.Contains(t, items, "orange")
		})
		if !failedSlice || !failNowSlice {
			fmt.Fprintf(os.Stderr, "assertion 8 failed: require.Contains should invoke FailNow on missing slice element\n")
			os.Exit(1)
		}
	}

	// Assertion 9: require.New creates an Assertions helper that executes assertions and invokes FailNow on failure
	{
		failed, failNow, _ := runRequireTest(func(t *contractTestingT) {
			req := require.New(t)
			req.Equal(10, 10)
			req.True(true)
			req.NotNil(t)
		})
		if failed || failNow {
			fmt.Fprintf(os.Stderr, "assertion 9 failed: require.New helper assertions should succeed on valid conditions\n")
			os.Exit(1)
		}

		failedReq, failNowReq, _ := runRequireTest(func(t *contractTestingT) {
			req := require.New(t)
			req.Equal("alpha", "beta")
		})
		if !failedReq || !failNowReq {
			fmt.Fprintf(os.Stderr, "assertion 9 failed: require.New helper should invoke FailNow on assertion failure\n")
			os.Exit(1)
		}
	}

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

Исходный сидер

аноним