CodeSampleX

Пример

github.com/stretchr/testify v1.8.1

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

sha256:fd8521a20b7145e327a07a2e227d7cd7735498fa0b359004812bddceefd27aad

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

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

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

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
2
Ключи подписи, собравшие его
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 SKIPPED compile:SKIPPED · contract:SKIPPED · load:SKIPPED · resolve:FAIL
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-04
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-04

Кейс

HOW
Цель
verify pkg:golang/github.com/stretchr/testify@v1.8.1
Пакеты
Окружение
go 1.26.6
Создан
2026-09-04T14:24:04Z

Контракт

  1. assert.Equal returns true and records no error on equal values, and returns false with error formatting on inequality or type mismatch
  2. assert.NotEqual returns true when comparing distinct values and returns false when values are identical
  3. assert.NoError returns true for nil errors, while assert.Error returns true and records failure when error is expected
  4. assert.ErrorContains returns true when error message contains expected substring and returns false on missing substring
  5. assert.Panics returns true when target function triggers a panic and returns false when function completes normally
  6. assert.NotPanics returns true and records no error when executed function does not panic
  7. assert.ElementsMatch returns true when two slices contain identical elements regardless of ordering
  8. assert.InDelta returns true when numeric difference is within delta threshold and returns false when exceeding threshold

Файлы

  • 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.8.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/stretchr/testify@v1.8.1
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:9ed416690901e74c27934276352f92896c112b7c7550a7ebb54bd94ec38f7f49","contract":["assert.Equal returns true and records no error on equal values, and returns false with error formatting on inequality or type mismatch","assert.NotEqual returns true when comparing distinct values and returns false when values are identical","assert.NoError returns true for nil errors, while assert.Error returns true and records failure when error is expected","assert.ErrorContains returns true when error message contains expected substring and returns false on missing substring","assert.Panics returns true when target function triggers a panic and returns false when function completes normally","assert.NotPanics returns true and records no error when executed function does not panic","assert.ElementsMatch returns true when two slices contain identical elements regardless of ordering","assert.InDelta returns true when numeric difference is within delta threshold and returns false when exceeding threshold"],"goal":"verify pkg:golang/github.com/stretchr/testify@v1.8.1","kind":"HOW","packages":["pkg:golang/github.com/stretchr/testify@v1.8.1"],"schemaVersion":1},"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.8.1"],"schemaVersion":1,"subject":"pkg:golang/github.com/stretchr/testify@v1.8.1","verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require github.com/stretchr/testify v1.8.1

require (
	github.com/davecgh/go-spew v1.1.1 // indirect
	github.com/pmezard/go-difflib v1.0.0 // indirect
	gopkg.in/yaml.v3 v3.0.1 // indirect
)
go.sum
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
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.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
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/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
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"

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

// ValidationReport implements assert.TestingT to record assertion results.
type ValidationReport struct {
	Errors []string
	Passed int
	Failed int
}

func (r *ValidationReport) Errorf(format string, args ...interface{}) {
	msg := fmt.Sprintf(format, args...)
	r.Errors = append(r.Errors, msg)
	r.Failed++
}

// UserRecord represents a data structure to validate.
type UserRecord struct {
	ID    int
	Name  string
	Roles []string
	Score float64
}

// ValidateRecord applies assertions to check user record invariants.
func ValidateRecord(r *ValidationReport, user *UserRecord) {
	if assert.NotNil(r, user, "user record must not be nil") {
		r.Passed++
	}

	if assert.NotEmpty(r, user.Name, "user name must not be empty") {
		r.Passed++
	}

	if assert.True(r, user.ID > 0, "user id must be positive") {
		r.Passed++
	}

	if assert.Contains(r, user.Roles, "member", "user must contain member role") {
		r.Passed++
	}

	if assert.InDelta(r, 100.0, user.Score, 50.0, "user score must be in expected range") {
		r.Passed++
	}
}

// ProcessUser performs business logic on a user record.
func ProcessUser(user *UserRecord) error {
	if user == nil {
		return errors.New("invalid user: nil pointer")
	}
	if user.ID <= 0 {
		return errors.New("invalid user: negative or zero ID")
	}
	return nil
}

func main() {
	report := &ValidationReport{}

	user := &UserRecord{
		ID:    101,
		Name:  "TestUser",
		Roles: []string{"guest", "member"},
		Score: 98.5,
	}

	ValidateRecord(report, user)

	err := ProcessUser(user)
	if assert.NoError(report, err, "ProcessUser should succeed for valid user") {
		report.Passed++
	}

	fmt.Printf("Validation completed: %d passed, %d failed\n", report.Passed, report.Failed)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/stretchr/testify@v1.8.1",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/stretchr/testify@v1.8.1"
  ],
  "runtimeConditions": {
    "ecosystem": "golang",
    "language": "go",
    "packageManager": "go@1.26.6",
    "runtime": "go@1.26.6"
  }
}
test/contract.go
package main

import (
	"errors"
	"fmt"
	"os"

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

type contractTestingT struct {
	errors []string
	failed bool
}

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

func main() {
	// Assertion 1: assert.Equal returns true and records no error on equal values, and returns false with error formatting on inequality or type mismatch
	{
		t := &contractTestingT{}
		if !assert.Equal(t, "expected-string", "expected-string") || t.failed || len(t.errors) != 0 {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: Equal should succeed on matching strings\n")
			os.Exit(1)
		}

		tMismatch := &contractTestingT{}
		if assert.Equal(tMismatch, "value1", "value2") || !tMismatch.failed || len(tMismatch.errors) == 0 {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: Equal should return false on mismatched values\n")
			os.Exit(1)
		}

		tTypeMismatch := &contractTestingT{}
		if assert.Equal(tTypeMismatch, int(42), int64(42)) || !tTypeMismatch.failed || len(tTypeMismatch.errors) == 0 {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: Equal should return false on type mismatch\n")
			os.Exit(1)
		}
	}

	// Assertion 2: assert.NotEqual returns true when comparing distinct values and returns false when values are identical
	{
		t := &contractTestingT{}
		if !assert.NotEqual(t, 10, 20) || t.failed || len(t.errors) != 0 {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: NotEqual should succeed on distinct values\n")
			os.Exit(1)
		}

		tEqual := &contractTestingT{}
		if assert.NotEqual(tEqual, 10, 10) || !tEqual.failed || len(tEqual.errors) == 0 {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: NotEqual should return false on identical values\n")
			os.Exit(1)
		}
	}

	// Assertion 3: assert.NoError returns true for nil errors, while assert.Error returns true and records failure when error is expected
	{
		t := &contractTestingT{}
		if !assert.NoError(t, nil) || t.failed || len(t.errors) != 0 {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: NoError should succeed on nil error\n")
			os.Exit(1)
		}

		tErrFail := &contractTestingT{}
		sampleErr := errors.New("operation failed")
		if assert.NoError(tErrFail, sampleErr) || !tErrFail.failed || len(tErrFail.errors) == 0 {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: NoError should fail on non-nil error\n")
			os.Exit(1)
		}

		tErrExpected := &contractTestingT{}
		if !assert.Error(tErrExpected, sampleErr) || tErrExpected.failed || len(tErrExpected.errors) != 0 {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: Error should return true when error is present\n")
			os.Exit(1)
		}

		tNilErrExpected := &contractTestingT{}
		if assert.Error(tNilErrExpected, nil) || !tNilErrExpected.failed || len(tNilErrExpected.errors) == 0 {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: Error should return false and report failure when error is nil\n")
			os.Exit(1)
		}
	}

	// Assertion 4: assert.ErrorContains returns true when error message contains expected substring and returns false on missing substring
	{
		t := &contractTestingT{}
		err := errors.New("resource not found: item 404")
		if !assert.ErrorContains(t, err, "not found") || t.failed || len(t.errors) != 0 {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: ErrorContains should succeed on matching substring\n")
			os.Exit(1)
		}

		tMissing := &contractTestingT{}
		if assert.ErrorContains(tMissing, err, "access denied") || !tMissing.failed || len(tMissing.errors) == 0 {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: ErrorContains should fail on missing substring\n")
			os.Exit(1)
		}
	}

	// Assertion 5: assert.Panics returns true when target function triggers a panic and returns false when function completes normally
	{
		t := &contractTestingT{}
		didPanic := assert.Panics(t, func() {
			panic("critical failure")
		})
		if !didPanic || t.failed || len(t.errors) != 0 {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: Panics should return true on panic\n")
			os.Exit(1)
		}

		tNoPanic := &contractTestingT{}
		didPanicClean := assert.Panics(tNoPanic, func() {
			// clean execution
		})
		if didPanicClean || !tNoPanic.failed || len(tNoPanic.errors) == 0 {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: Panics should return false and report error on clean function\n")
			os.Exit(1)
		}
	}

	// Assertion 6: assert.NotPanics returns true and records no error when executed function does not panic
	{
		t := &contractTestingT{}
		noPanic := assert.NotPanics(t, func() {
			_ = 1 + 1
		})
		if !noPanic || t.failed || len(t.errors) != 0 {
			fmt.Fprintf(os.Stderr, "assertion 6 failed: NotPanics should succeed when function completes cleanly\n")
			os.Exit(1)
		}

		tPanic := &contractTestingT{}
		noPanicOnCrash := assert.NotPanics(tPanic, func() {
			panic("unexpected crash")
		})
		if noPanicOnCrash || !tPanic.failed || len(tPanic.errors) == 0 {
			fmt.Fprintf(os.Stderr, "assertion 6 failed: NotPanics should return false and report error on panic\n")
			os.Exit(1)
		}
	}

	// Assertion 7: assert.ElementsMatch returns true when two slices contain identical elements regardless of ordering
	{
		t := &contractTestingT{}
		sliceA := []string{"apple", "banana", "cherry"}
		sliceB := []string{"cherry", "apple", "banana"}
		if !assert.ElementsMatch(t, sliceA, sliceB) || t.failed || len(t.errors) != 0 {
			fmt.Fprintf(os.Stderr, "assertion 7 failed: ElementsMatch should succeed on permutations\n")
			os.Exit(1)
		}

		tDiff := &contractTestingT{}
		sliceC := []string{"apple", "cherry", "date"}
		if assert.ElementsMatch(tDiff, sliceA, sliceC) || !tDiff.failed || len(tDiff.errors) == 0 {
			fmt.Fprintf(os.Stderr, "assertion 7 failed: ElementsMatch should return false on mismatched elements\n")
			os.Exit(1)
		}
	}

	// Assertion 8: assert.InDelta returns true when numeric difference is within delta threshold and returns false when exceeding threshold
	{
		t := &contractTestingT{}
		if !assert.InDelta(t, 3.14159, 3.14, 0.01) || t.failed || len(t.errors) != 0 {
			fmt.Fprintf(os.Stderr, "assertion 8 failed: InDelta should succeed within threshold\n")
			os.Exit(1)
		}

		tExceed := &contractTestingT{}
		if assert.InDelta(tExceed, 3.14159, 3.10, 0.01) || !tExceed.failed || len(tExceed.errors) == 0 {
			fmt.Fprintf(os.Stderr, "assertion 8 failed: InDelta should return false when difference exceeds delta\n")
			os.Exit(1)
		}
	}

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

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

аноним