CodeSampleX

샘플

github.com/stretchr/testify v1.7.1: assert.Contains, assert.ElementsMatch, assert.Equal

검증된 샘플 — golang github.com/stretchr/testify v1.7.1: assert.Contains, assert.ElementsMatch, assert.Equal. go 1.26 · linux debian/x64 · docker에서 contract를 실행해…

sha256:75fdc838f8b3b52d37798d2de3db73d206628e5c30455f2001b23ac5db02e004

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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-10-17

케이스

HOW
목표
verify pkg:golang/github.com/stretchr/testify@v1.7.1
패키지
심벌
  • assert.Contains
  • assert.ElementsMatch
  • assert.Equal
  • assert.EqualError
  • assert.NoError
  • mock.Mock
  • require.Equal
  • require.NoError
환경
go 1.26.6
생성일
2026-10-17T00:39:12Z

컨트랙트

  1. assert.Equal returns true for equal primitives and structs, and false while recording an error on value mismatch or distinct numeric types
  2. assert.Contains and assert.ElementsMatch validate substring, slice membership, and order-independent slice equivalence
  3. assert.EqualError and assert.NoError verify error presence and exact error string matching
  4. require.NoError and require.Equal invoke FailNow immediately on failure and do not call FailNow when passing
  5. mock.Mock expectations created with On and Return verify argument matching, return configured values, and report unmet Once counts via AssertExpectations

파일

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

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/stretchr/testify@v1.7.1
Demonstrate these symbols/APIs:
  - assert.ElementsMatch
  - assert.Equal
  - assert.EqualError
  - mock.Mock
  - require.Equal
  - require.NoError
  - suite.Run

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:79b8fbb7226231d82d2ee25920b9b76f20f4551f15bba615f6c3ae004c80a0a3","contract":["assert.Equal returns true for equal primitives and structs, and false while recording an error on value mismatch or distinct numeric types","assert.Contains and assert.ElementsMatch validate substring, slice membership, and order-independent slice equivalence","assert.EqualError and assert.NoError verify error presence and exact error string matching","require.NoError and require.Equal invoke FailNow immediately on failure and do not call FailNow when passing","mock.Mock expectations created with On and Return verify argument matching, return configured values, and report unmet Once counts via AssertExpectations"],"goal":"verify pkg:golang/github.com/stretchr/testify@v1.7.1","kind":"HOW","packages":["pkg:golang/github.com/stretchr/testify@v1.7.1"],"schemaVersion":1,"symbols":["assert.Contains","assert.ElementsMatch","assert.Equal","assert.EqualError","assert.NoError","mock.Mock","require.Equal","require.NoError"]},"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.1"],"schemaVersion":1,"subject":"pkg:golang/github.com/stretchr/testify@v1.7.1","symbols":["assert.Contains","assert.ElementsMatch","assert.Equal","assert.EqualError","assert.NoError","mock.Mock","require.Equal","require.NoError"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require github.com/stretchr/testify v1.7.1

require (
	github.com/davecgh/go-spew v1.1.0 // indirect
	github.com/pmezard/go-difflib v1.0.0 // indirect
	github.com/stretchr/objx v0.1.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 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=
github.com/stretchr/testify v1.7.1/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 (
	"errors"
	"fmt"

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

type spyTestingT struct {
	messages []string
	failed   bool
	halted   bool
}

func (s *spyTestingT) Errorf(format string, args ...interface{}) {
	s.failed = true
	s.messages = append(s.messages, fmt.Sprintf(format, args...))
}

func (s *spyTestingT) FailNow() {
	s.failed = true
	s.halted = true
}

func (s *spyTestingT) Logf(format string, args ...interface{}) {}

type mockedFetcher struct {
	mock.Mock
}

func (m *mockedFetcher) Fetch(key string) (int, error) {
	args := m.Called(key)
	return args.Int(0), args.Error(1)
}

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

	assert.Equal(t, 42, 42)
	assert.Contains(t, []string{"alpha", "beta"}, "beta")
	assert.ElementsMatch(t, []string{"a", "b"}, []string{"b", "a"})
	assert.EqualError(t, errors.New("bad input"), "bad input")
	assert.NoError(t, nil)
	require.NoError(t, nil)
	require.Equal(t, "ok", "ok")

	m := &mockedFetcher{}
	m.On("Fetch", "k1").Return(99, nil).Once()
	val, err := m.Fetch("k1")
	require.NoError(t, err)
	assert.Equal(t, 99, val)
	m.AssertExpectations(t)

	if !t.failed && !t.halted {
		fmt.Println("ok")
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/stretchr/testify@v1.7.1",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/stretchr/testify@v1.7.1"
  ],
  "symbols": [
    "assert.ElementsMatch",
    "assert.Equal",
    "assert.EqualError",
    "mock.Mock",
    "require.Equal",
    "require.NoError",
    "suite.Run"
  ]
}
test/contract.go
package main

import (
	"errors"
	"fmt"
	"os"
	"strings"

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

type spyTestingT struct {
	messages []string
	failed   bool
	halted   bool
}

func (s *spyTestingT) Errorf(format string, args ...interface{}) {
	s.failed = true
	s.messages = append(s.messages, fmt.Sprintf(format, args...))
}

func (s *spyTestingT) FailNow() {
	s.failed = true
	s.halted = true
}

func (s *spyTestingT) Logf(format string, args ...interface{}) {}

type recordItem struct {
	ID   int
	Tags []string
}

type storeMock struct {
	mock.Mock
}

func (m *storeMock) Lookup(code string) (int, error) {
	ret := m.Called(code)
	return ret.Int(0), ret.Error(1)
}

func fail(msg string) {
	fmt.Fprintln(os.Stderr, msg)
	os.Exit(1)
}

func main() {
	// 1. assert.Equal returns true for equal primitives and structs, and false while recording an error on value mismatch or distinct numeric types
	{
		tOk := &spyTestingT{}
		a := recordItem{ID: 5, Tags: []string{"x", "y"}}
		b := recordItem{ID: 5, Tags: []string{"x", "y"}}
		if !assert.Equal(tOk, a, b) || tOk.failed || len(tOk.messages) != 0 {
			fail("contract 1a failed: expected assert.Equal to pass on equal structs")
		}

		tDiff := &spyTestingT{}
		c := recordItem{ID: 6, Tags: []string{"x", "y"}}
		if assert.Equal(tDiff, a, c) || !tDiff.failed || len(tDiff.messages) == 0 {
			fail("contract 1b failed: expected assert.Equal to fail on mismatched struct field")
		}

		tType := &spyTestingT{}
		if assert.Equal(tType, int32(12), int64(12)) || !tType.failed || len(tType.messages) == 0 {
			fail("contract 1c failed: expected assert.Equal to fail on different numeric types")
		}
	}

	// 2. assert.Contains and assert.ElementsMatch validate substring, slice membership, and order-independent slice equivalence
	{
		tOk := &spyTestingT{}
		if !assert.Contains(tOk, "service-healthy", "healthy") || tOk.failed {
			fail("contract 2a failed: expected assert.Contains to match substring")
		}
		if !assert.ElementsMatch(tOk, []int{10, 20, 20, 30}, []int{20, 30, 10, 20}) || tOk.failed {
			fail("contract 2b failed: expected assert.ElementsMatch to pass on reordered slice with identical multiplicities")
		}

		tFail := &spyTestingT{}
		if assert.ElementsMatch(tFail, []int{10, 20, 20}, []int{10, 20, 30}) || !tFail.failed || len(tFail.messages) == 0 {
			fail("contract 2c failed: expected assert.ElementsMatch to fail when element multiplicities differ")
		}
	}

	// 3. assert.EqualError and assert.NoError verify error presence and exact error string matching
	{
		tOk := &spyTestingT{}
		if !assert.NoError(tOk, nil) || tOk.failed {
			fail("contract 3a failed: expected assert.NoError to pass for nil")
		}
		errVal := errors.New("connection refused")
		if !assert.EqualError(tOk, errVal, "connection refused") || tOk.failed {
			fail("contract 3b failed: expected assert.EqualError to pass on exact message match")
		}

		tNil := &spyTestingT{}
		if assert.EqualError(tNil, nil, "connection refused") || !tNil.failed {
			fail("contract 3c failed: expected assert.EqualError to fail when error is nil")
		}

		tMismatch := &spyTestingT{}
		if assert.EqualError(tMismatch, errVal, "timeout") || !tMismatch.failed {
			fail("contract 3d failed: expected assert.EqualError to fail when error string differs")
		}
	}

	// 4. require.NoError and require.Equal invoke FailNow immediately on failure and do not call FailNow when passing
	{
		tOk := &spyTestingT{}
		require.NoError(tOk, nil)
		require.Equal(tOk, "active", "active")
		if tOk.failed || tOk.halted {
			fail("contract 4a failed: expected require assertions to pass without calling FailNow")
		}

		tHaltErr := &spyTestingT{}
		require.NoError(tHaltErr, errors.New("disk full"), "ctx %d", 7)
		if !tHaltErr.failed || !tHaltErr.halted || len(tHaltErr.messages) == 0 || !strings.Contains(tHaltErr.messages[0], "ctx 7") {
			fail("contract 4b failed: expected require.NoError to record formatted message and invoke FailNow")
		}

		tHaltEq := &spyTestingT{}
		require.Equal(tHaltEq, 1, 2)
		if !tHaltEq.failed || !tHaltEq.halted {
			fail("contract 4c failed: expected require.Equal to invoke FailNow on mismatch")
		}
	}

	// 5. mock.Mock expectations created with On and Return verify argument matching, return configured values, and report unmet Once counts via AssertExpectations
	{
		tOk := &spyTestingT{}
		m := &storeMock{}
		m.On("Lookup", "alpha").Return(42, nil).Once()
		v, err := m.Lookup("alpha")
		if err != nil || v != 42 || !m.AssertExpectations(tOk) || tOk.failed {
			fail("contract 5a failed: expected mock.Mock to return configured values and pass AssertExpectations")
		}

		tUnmet := &spyTestingT{}
		m2 := &storeMock{}
		m2.On("Lookup", "beta").Return(0, errors.New("missing")).Once()
		if m2.AssertExpectations(tUnmet) || !tUnmet.failed {
			fail("contract 5b failed: expected AssertExpectations to fail when Once expectation was not called")
		}
	}

	fmt.Println("contract ok")
}

오리진 시더

익명