CodeSampleX

샘플

github.com/google/go-cmp v0.5.5: cmp.Comparer

코드 샘플 — golang github.com/google/go-cmp v0.5.5: cmp.Comparer. 공개된 소스만 있으며, 아직 기록된 contract 실행이 없습니다.

sha256:292f57f7b55f31986fc634761507634e03cd599a972ee77378bfa4bf2103d9cc

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

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
게시된 소스만 있음
검증 영수증
0
빌드한 서명 키
0
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 go go

아직 영수증이 없습니다.

케이스

HOW
목표
verify pkg:golang/github.com/google/go-cmp@v0.5.5
패키지
심벌
  • github.com/google/go-cmp/cmp.Comparer
생성일
2026-09-03T07:43:24Z

컨트랙트

  1. cmp.Comparer defines custom equality predicate overriding default equality in cmp.Equal
  2. cmp.Comparer custom equality applies transitively to matching struct fields
  3. cmp.Comparer panics when argument is not a function
  4. cmp.Comparer panics when function inputs are not exactly two arguments of identical type
  5. cmp.Comparer panics when function does not return exactly one boolean value
  6. cmp.Diff with cmp.Comparer produces empty diff for equal values and non-empty diff otherwise

파일

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • sample.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/google/go-cmp@v0.5.5
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/google/go-cmp@v0.5.5

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:eeb4d23fc700353673eeee594be39d1e94580f6ca5c10ae0adea7a7f66f9689a","contract":["cmp.Comparer defines custom equality predicate overriding default equality in cmp.Equal","cmp.Comparer custom equality applies transitively to matching struct fields","cmp.Comparer panics when argument is not a function","cmp.Comparer panics when function inputs are not exactly two arguments of identical type","cmp.Comparer panics when function does not return exactly one boolean value","cmp.Diff with cmp.Comparer produces empty diff for equal values and non-empty diff otherwise"],"goal":"verify pkg:golang/github.com/google/go-cmp@v0.5.5","kind":"HOW","packages":["pkg:golang/github.com/google/go-cmp@v0.5.5"],"schemaVersion":1,"symbols":["github.com/google/go-cmp/cmp.Comparer"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/google/go-cmp@v0.5.5"],"schemaVersion":1,"subject":"pkg:golang/github.com/google/go-cmp@v0.5.5","symbols":["github.com/google/go-cmp/cmp.Comparer"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.22

require github.com/google/go-cmp v0.5.5
go.sum
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
sample.go
package sample

import (
	"fmt"
	"math"
	"strings"

	"github.com/google/go-cmp/cmp"
)

// Coordinate represents geographic coordinates.
type Coordinate struct {
	Latitude  float64
	Longitude float64
}

// UserAccount represents a user account record with a case-insensitive email and unique ID.
type UserAccount struct {
	ID    int
	Email string
}

// ApproxFloatComparer returns a cmp.Option that treats float64 values as equal
// if their absolute difference does not exceed epsilon.
func ApproxFloatComparer(epsilon float64) cmp.Option {
	return cmp.Comparer(func(x, y float64) bool {
		return math.Abs(x-y) <= epsilon
	})
}

// CaseInsensitiveComparer is a cmp.Option that compares strings case-insensitively.
var CaseInsensitiveComparer = cmp.Comparer(func(x, y string) bool {
	return strings.EqualFold(x, y)
})

// CompareCoordinates compares two Coordinate structs using the provided float tolerance.
func CompareCoordinates(a, b Coordinate, tolerance float64) bool {
	return cmp.Equal(a, b, ApproxFloatComparer(tolerance))
}

// CompareAccountsCaseInsensitive compares UserAccount structs equating emails case-insensitively.
func CompareAccountsCaseInsensitive(a, b UserAccount) bool {
	return cmp.Equal(a, b, CaseInsensitiveComparer)
}

// TryCreateComparer attempts to construct a cmp.Comparer option with the given argument,
// returning the recovered panic message if the argument signature is invalid.
func TryCreateComparer(fn interface{}) (opt cmp.Option, panicMsg string) {
	defer func() {
		if r := recover(); r != nil {
			panicMsg = fmt.Sprint(r)
		}
	}()
	opt = cmp.Comparer(fn)
	return opt, ""
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/google/go-cmp@v0.5.5",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/google/go-cmp@v0.5.5"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"
	"strings"

	"example.com/sample"
	"github.com/google/go-cmp/cmp"
)

func main() {
	if err := runContractTests(); err != nil {
		fmt.Fprintf(os.Stderr, "Contract test failed: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("All contract tests passed successfully.")
}

func runContractTests() error {
	// 1. cmp.Comparer defines custom equality predicate overriding default equality in cmp.Equal
	f1 := 1.0001
	f2 := 1.0004
	if cmp.Equal(f1, f2) {
		return fmt.Errorf("expected default float comparison to be false for different values")
	}
	approx := sample.ApproxFloatComparer(0.001)
	if !cmp.Equal(f1, f2, approx) {
		return fmt.Errorf("expected approx comparer with tolerance 0.001 to evaluate %v and %v as equal", f1, f2)
	}

	// 2. cmp.Comparer custom equality applies transitively to matching struct fields
	coordA := sample.Coordinate{Latitude: 37.77490, Longitude: -122.41940}
	coordB := sample.Coordinate{Latitude: 37.77492, Longitude: -122.41943}
	if cmp.Equal(coordA, coordB) {
		return fmt.Errorf("expected coordinates to differ under default comparison")
	}
	if !sample.CompareCoordinates(coordA, coordB, 0.0001) {
		return fmt.Errorf("expected coordinates to match within 0.0001 tolerance")
	}

	// 3. cmp.Comparer panics when argument is not a function
	_, panicNonFn := sample.TryCreateComparer("not_a_function")
	if panicNonFn == "" {
		return fmt.Errorf("expected panic when non-function is passed to cmp.Comparer")
	}
	if !strings.Contains(panicNonFn, "invalid function") && !strings.Contains(panicNonFn, "function") {
		return fmt.Errorf("expected invalid function panic message, got: %s", panicNonFn)
	}

	// 4. cmp.Comparer panics when function inputs are not exactly two arguments of identical type
	_, panicArgCount := sample.TryCreateComparer(func(x int) bool { return true })
	if panicArgCount == "" {
		return fmt.Errorf("expected panic when 1-arg function is passed to cmp.Comparer")
	}

	_, panicMismatchedTypes := sample.TryCreateComparer(func(x int, y string) bool { return true })
	if panicMismatchedTypes == "" {
		return fmt.Errorf("expected panic when function arguments have mismatched types")
	}

	// 5. cmp.Comparer panics when function does not return exactly one boolean value
	_, panicRetCount := sample.TryCreateComparer(func(x, y int) (bool, error) { return true, nil })
	if panicRetCount == "" {
		return fmt.Errorf("expected panic when function returns multiple values")
	}

	_, panicNonBoolRet := sample.TryCreateComparer(func(x, y int) int { return 0 })
	if panicNonBoolRet == "" {
		return fmt.Errorf("expected panic when function return type is not bool")
	}

	// 6. cmp.Diff with cmp.Comparer produces empty diff for equal values and non-empty diff otherwise
	user1 := sample.UserAccount{ID: 101, Email: "User@Example.com"}
	user2 := sample.UserAccount{ID: 101, Email: "user@example.com"}
	diffDefault := cmp.Diff(user1, user2)
	if diffDefault == "" {
		return fmt.Errorf("expected non-empty diff under default comparison for different cased emails")
	}

	diffComparer := cmp.Diff(user1, user2, sample.CaseInsensitiveComparer)
	if diffComparer != "" {
		return fmt.Errorf("expected empty diff when using CaseInsensitiveComparer, got: %s", diffComparer)
	}

	return nil
}

오리진 시더

익명