CodeSampleX

Exemplo

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

Amostra verificada para golang github.com/google/go-cmp v0.5.5: cmp.Comparer. O contrato rodou em go 1.26 · linux debian/x64 · docker e passou: cmp.Comparer…

sha256:292f57f7b55f31986fc634761507634e03cd599a972ee77378bfa4bf2103d9cc

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado linux 24 · ubuntu · glibc 2.39 x64 go go

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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-03

Caso

HOW
Objetivo
verify pkg:golang/github.com/google/go-cmp@v0.5.5
Pacotes
Símbolos
  • github.com/google/go-cmp/cmp.Comparer
Criado
2026-09-03T07:43:24Z

Contrato

  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

Arquivos

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • sample.go
  • spec.json
  • test/contract.go

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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
}

Seeder de origem

anônimo