CodeSampleX

サンプル

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

検証済みサンプル — golang github.com/stretchr/testify v1.7.0: suite. go 1.26 · linux debian/x64 · docker で contract を実行し、成功しました: suite.Run executes all exported test…

sha256:762956c30783c5e0bac92d690c4a636c8989249b6547bec977049ef8464e0e5f

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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 suite in pkg:golang/github.com/stretchr/testify@v1.7.0
パッケージ
シンボル
  • suite
環境
go 1.26.6
作成日
2026-09-06T06:09:35Z

コントラクト

  1. suite.Run executes all exported test methods on the suite whose names begin with Test
  2. suite executes SetupSuite once before any tests run and TearDownSuite once after all tests complete
  3. suite executes SetupTest and BeforeTest before each test method and AfterTest and TearDownTest after each test method in order
  4. suite.Suite provides embedded assertions and Require provides fail-now assertions bound to the active test context
  5. suite.Run method enables nested subtest execution with fresh child test contexts
  6. suite implementing WithStats receives completed SuiteInformation with valid timings and test results via HandleStats

ファイル

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract_test.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 suite in 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:
  - suite

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:5e4acec195913b9cffb3d22369d4cb60947912da611c60cb87d3f8a61e984b3c","contract":["suite.Run executes all exported test methods on the suite whose names begin with Test","suite executes SetupSuite once before any tests run and TearDownSuite once after all tests complete","suite executes SetupTest and BeforeTest before each test method and AfterTest and TearDownTest after each test method in order","suite.Suite provides embedded assertions and Require provides fail-now assertions bound to the active test context","suite.Run method enables nested subtest execution with fresh child test contexts","suite implementing WithStats receives completed SuiteInformation with valid timings and test results via HandleStats"],"goal":"verify suite in pkg:golang/github.com/stretchr/testify@v1.7.0","kind":"HOW","packages":["pkg:golang/github.com/stretchr/testify@v1.7.0"],"schemaVersion":1,"symbols":["suite"]},"contractCommand":["go","test","-v","./..."],"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":["suite"],"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/suite"
)

// ItemRepository defines operations on an in-memory item set.
type ItemRepository struct {
	items map[string]int
}

// NewItemRepository initializes a repository with empty state.
func NewItemRepository() *ItemRepository {
	return &ItemRepository{
		items: make(map[string]int),
	}
}

// Set adds or updates an item count.
func (r *ItemRepository) Set(name string, count int) {
	r.items[name] = count
}

// Get retrieves an item count.
func (r *ItemRepository) Get(name string) (int, bool) {
	val, ok := r.items[name]
	return val, ok
}

// ItemRepositorySuite demonstrates using testify/suite to test ItemRepository.
type ItemRepositorySuite struct {
	suite.Suite
	repo *ItemRepository
}

// SetupTest prepares fresh state before each test.
func (s *ItemRepositorySuite) SetupTest() {
	s.repo = NewItemRepository()
}

// TestSetAndGet verifies that stored values can be accurately retrieved.
func (s *ItemRepositorySuite) TestSetAndGet() {
	s.repo.Set("widget", 42)
	val, ok := s.repo.Get("widget")
	s.True(ok)
	s.Equal(42, val)
}

func main() {
	repo := NewItemRepository()
	repo.Set("example", 1)
	val, _ := repo.Get("example")
	fmt.Printf("Item repository initialized with %d item(s)\n", val)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify suite in pkg:golang/github.com/stretchr/testify@v1.7.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/stretchr/testify@v1.7.0"
  ],
  "symbols": [
    "suite"
  ]
}
test/contract_test.go
package test

import (
	"fmt"
	"testing"

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

// DiscoverySuite verifies method discovery and exclusion of non-test methods.
type DiscoverySuite struct {
	suite.Suite
	testOneRun bool
	testTwoRun bool
	helperRun  bool
}

func (s *DiscoverySuite) TestOne() {
	s.testOneRun = true
}

func (s *DiscoverySuite) TestTwo() {
	s.testTwoRun = true
}

func (s *DiscoverySuite) HelperMethod() {
	s.helperRun = true
}

// SuiteLifecycleSuite verifies SetupSuite and TearDownSuite invocation counts.
type SuiteLifecycleSuite struct {
	suite.Suite
	setupSuiteCount    int
	tearDownSuiteCount int
	testsRun           int
}

func (s *SuiteLifecycleSuite) SetupSuite() {
	s.setupSuiteCount++
}

func (s *SuiteLifecycleSuite) TestAlpha() {
	s.testsRun++
}

func (s *SuiteLifecycleSuite) TestBeta() {
	s.testsRun++
}

func (s *SuiteLifecycleSuite) TearDownSuite() {
	s.tearDownSuiteCount++
}

// MethodLifecycleSuite verifies per-test setup and teardown ordering.
type MethodLifecycleSuite struct {
	suite.Suite
	eventLog []string
}

func (s *MethodLifecycleSuite) SetupTest() {
	s.eventLog = append(s.eventLog, "SetupTest")
}

func (s *MethodLifecycleSuite) BeforeTest(suiteName, testName string) {
	s.eventLog = append(s.eventLog, fmt.Sprintf("BeforeTest:%s:%s", suiteName, testName))
}

func (s *MethodLifecycleSuite) TestFirst() {
	s.eventLog = append(s.eventLog, "TestFirst")
}

func (s *MethodLifecycleSuite) TestSecond() {
	s.eventLog = append(s.eventLog, "TestSecond")
}

func (s *MethodLifecycleSuite) AfterTest(suiteName, testName string) {
	s.eventLog = append(s.eventLog, fmt.Sprintf("AfterTest:%s:%s", suiteName, testName))
}

func (s *MethodLifecycleSuite) TearDownTest() {
	s.eventLog = append(s.eventLog, "TearDownTest")
}

// AssertionsBindingSuite verifies embedded assert methods and Require accessors.
type AssertionsBindingSuite struct {
	suite.Suite
	assertionsPassed bool
}

func (s *AssertionsBindingSuite) TestAssertions() {
	if s.T() == nil {
		return
	}
	s.Equal(100, 100)
	s.True(true)
	s.False(false)
	s.NoError(nil)

	req := s.Require()
	if req == nil {
		return
	}
	req.Equal("alpha", "alpha")
	req.NotNil(s.T())

	as := s.Assert()
	if as == nil {
		return
	}
	as.Equal(200, 200)

	s.assertionsPassed = true
}

// SubtestExecutionSuite verifies nested subtest execution context management.
type SubtestExecutionSuite struct {
	suite.Suite
	subtestExecuted bool
	parentContext   *testing.T
	childContext    *testing.T
	restoredContext *testing.T
}

func (s *SubtestExecutionSuite) TestSubtest() {
	s.parentContext = s.T()
	s.Run("child_subtest", func() {
		s.childContext = s.T()
		s.subtestExecuted = true
	})
	s.restoredContext = s.T()
}

// WithStatsSuite verifies WithStats interface implementation.
type WithStatsSuite struct {
	suite.Suite
	statsHandled bool
	suiteName    string
	statsValid   bool
}

func (s *WithStatsSuite) TestExecution() {
	s.Equal("hello", "hello")
}

func (s *WithStatsSuite) HandleStats(suiteName string, stats *suite.SuiteInformation) {
	s.statsHandled = true
	s.suiteName = suiteName
	if stats != nil && !stats.Start.IsZero() && !stats.End.IsZero() && stats.Passed() {
		if testStat, exists := stats.TestStats["TestExecution"]; exists && testStat.Passed {
			s.statsValid = true
		}
	}
}

func TestContract(t *testing.T) {
	// Assertion 1: suite.Run executes all exported test methods on the suite whose names begin with Test
	{
		s := new(DiscoverySuite)
		suite.Run(t, s)
		if !s.testOneRun || !s.testTwoRun || s.helperRun {
			t.Fatalf("assertion 1 failed: suite.Run did not execute expected Test methods or invoked non-Test method")
		}
	}

	// Assertion 2: suite executes SetupSuite once before any tests run and TearDownSuite once after all tests complete
	{
		s := new(SuiteLifecycleSuite)
		suite.Run(t, s)
		if s.setupSuiteCount != 1 || s.tearDownSuiteCount != 1 || s.testsRun != 2 {
			t.Fatalf("assertion 2 failed: SetupSuite and TearDownSuite call count mismatch")
		}
	}

	// Assertion 3: suite executes SetupTest and BeforeTest before each test method and AfterTest and TearDownTest after each test method in order
	{
		s := new(MethodLifecycleSuite)
		suite.Run(t, s)
		expected := []string{
			"SetupTest",
			"BeforeTest:MethodLifecycleSuite:TestFirst",
			"TestFirst",
			"AfterTest:MethodLifecycleSuite:TestFirst",
			"TearDownTest",
			"SetupTest",
			"BeforeTest:MethodLifecycleSuite:TestSecond",
			"TestSecond",
			"AfterTest:MethodLifecycleSuite:TestSecond",
			"TearDownTest",
		}
		if len(s.eventLog) != len(expected) {
			t.Fatalf("assertion 3 failed: event log length mismatch (%d vs %d)", len(s.eventLog), len(expected))
		}
		for i, exp := range expected {
			if s.eventLog[i] != exp {
				t.Fatalf("assertion 3 failed: step %d expected %s, got %s", i, exp, s.eventLog[i])
			}
		}
	}

	// Assertion 4: suite.Suite provides embedded assertions and Require provides fail-now assertions bound to the active test context
	{
		s := new(AssertionsBindingSuite)
		suite.Run(t, s)
		if !s.assertionsPassed {
			t.Fatalf("assertion 4 failed: embedded assertions or Require did not pass")
		}
	}

	// Assertion 5: suite.Run method enables nested subtest execution with fresh child test contexts
	{
		s := new(SubtestExecutionSuite)
		suite.Run(t, s)
		if !s.subtestExecuted || s.childContext == nil || s.childContext == s.parentContext || s.restoredContext != s.parentContext {
			t.Fatalf("assertion 5 failed: subtest execution context handling mismatch")
		}
	}

	// Assertion 6: suite implementing WithStats receives completed SuiteInformation with valid timings and test results via HandleStats
	{
		s := new(WithStatsSuite)
		suite.Run(t, s)
		if !s.statsHandled || s.suiteName != "WithStatsSuite" || !s.statsValid {
			t.Fatalf("assertion 6 failed: WithStats HandleStats was not invoked with expected SuiteInformation")
		}
	}
}

オリジンシーダー

匿名