CodeSampleX

Ejemplo

github.com/go-logr/logr v1.4.1: testr.NewWithInterface

Muestra verificada para golang github.com/go-logr/logr v1.4.1: testr.NewWithInterface. El contrato se ejecutó en go 1.26 · linux alpine/x64 · docker y pasó.

sha256:ef7a119df58d6ba9df6873ee3e70bc41a77744844ca46efc47453433cf76e6d4

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 go

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-27

Caso

HOW
Objetivo
verify github.com/go-logr/logr/testr.NewWithInterface in pkg:golang/github.com/go-logr/logr@v1.4.1
Paquetes
Símbolos
  • github.com/go-logr/logr/testr.NewWithInterface
Creado
2026-08-27T10:30:04Z

Contrato

  1. testr.NewWithInterface creates a logr.Logger wrapping a custom TestingT implementation
  2. logger.Info logs structured messages and key-value pairs through TestingT
  3. logger.Error logs error details and messages through TestingT
  4. testr.Options Verbosity controls V-level logging enablement and filtering
  5. logger.WithName and logger.WithValues enrich log context prefix and attributes
  6. logger sink implements testr.UnderlierInterface returning the original TestingT instance

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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 github.com/go-logr/logr/testr.NewWithInterface in pkg:golang/github.com/go-logr/logr@v1.4.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/go-logr/logr@v1.4.1
Demonstrate these symbols/APIs:
  - github.com/go-logr/logr/testr.NewWithInterface

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:6513b4d8dc64f7361dfdab99091129fd82e37d6c1dc6b796aff6e721627c8cfc","contract":["testr.NewWithInterface creates a logr.Logger wrapping a custom TestingT implementation","logger.Info logs structured messages and key-value pairs through TestingT","logger.Error logs error details and messages through TestingT","testr.Options Verbosity controls V-level logging enablement and filtering","logger.WithName and logger.WithValues enrich log context prefix and attributes","logger sink implements testr.UnderlierInterface returning the original TestingT instance"],"goal":"verify github.com/go-logr/logr/testr.NewWithInterface in pkg:golang/github.com/go-logr/logr@v1.4.1","kind":"HOW","packages":["pkg:golang/github.com/go-logr/logr@v1.4.1"],"schemaVersion":1,"symbols":["github.com/go-logr/logr/testr.NewWithInterface"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/go-logr/logr@v1.4.1"],"schemaVersion":1,"subject":"pkg:golang/github.com/go-logr/logr@v1.4.1","symbols":["github.com/go-logr/logr/testr.NewWithInterface"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.22.0

require github.com/go-logr/logr v1.4.1
go.sum
github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ=
github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
main.go
package main

import (
	"errors"
	"fmt"

	"github.com/go-logr/logr"
	"github.com/go-logr/logr/testr"
)

// CustomTestingT implements testr.TestingT for test or custom runtime logging.
type CustomTestingT struct {
	logs []string
}

// Helper marks the calling function as a test helper.
func (c *CustomTestingT) Helper() {}

// Log prints formatted test log messages and records them.
func (c *CustomTestingT) Log(args ...any) {
	msg := fmt.Sprint(args...)
	c.logs = append(c.logs, msg)
	fmt.Println("[TEST-LOG]", msg)
}

// Logs returns all recorded log messages.
func (c *CustomTestingT) Logs() []string {
	return c.logs
}

// CreateTestLogger creates a logr.Logger wrapping any testr.TestingT with configured options.
func CreateTestLogger(t testr.TestingT, verbosity int, logTimestamp bool) logr.Logger {
	opts := testr.Options{
		Verbosity:    verbosity,
		LogTimestamp: logTimestamp,
	}
	return testr.NewWithInterface(t, opts)
}

func main() {
	tester := &CustomTestingT{}

	// Initialize logger with custom TestingT interface
	logger := CreateTestLogger(tester, 1, false)

	// Log standard info with structured key-values
	logger.Info("application initialized", "component", "main", "attempts", 1)

	// Log error with structured details
	err := errors.New("temporary connection drop")
	logger.Error(err, "network warning occurred", "retryCount", 2)

	// Log with verbosity levels
	logger.V(1).Info("debug details enabled at V(1)", "status", "active")
	logger.V(2).Info("trace details suppressed at V(2)", "status", "ignored")

	// Create contextual child loggers
	subLogger := logger.WithName("subsystem").WithValues("subsystem_id", "sub-01")
	subLogger.Info("subsystem task completed", "result", "success")

	fmt.Printf("Total log lines recorded: %d\n", len(tester.Logs()))
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/go-logr/logr/testr.NewWithInterface in pkg:golang/github.com/go-logr/logr@v1.4.1",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/go-logr/logr@v1.4.1"
  ],
  "symbols": [
    "github.com/go-logr/logr/testr.NewWithInterface"
  ]
}
test/contract.go
package main

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

	"github.com/go-logr/logr"
	"github.com/go-logr/logr/testr"
)

type recordTestingT struct {
	helperCalled bool
	logs         []string
}

func (r *recordTestingT) Helper() {
	r.helperCalled = true
}

func (r *recordTestingT) Log(args ...any) {
	r.logs = append(r.logs, fmt.Sprint(args...))
}

func main() {
	t := &recordTestingT{}
	opts := testr.Options{
		LogTimestamp: false,
		Verbosity:    1,
	}

	// Assertion 1: testr.NewWithInterface creates a logr.Logger wrapping a custom TestingT implementation
	var logger logr.Logger = testr.NewWithInterface(t, opts)
	if logger.GetSink() == nil {
		fmt.Fprintf(os.Stderr, "FAIL: logger.GetSink() returned nil\n")
		os.Exit(1)
	}

	// Assertion 2: logger.Info logs structured messages and key-value pairs through TestingT
	t.logs = nil
	logger.Info("service started", "port", 8080, "env", "test")
	if len(t.logs) != 1 {
		fmt.Fprintf(os.Stderr, "FAIL: expected 1 log entry, got %d\n", len(t.logs))
		os.Exit(1)
	}
	infoLog := t.logs[0]
	if !strings.Contains(infoLog, `"msg"="service started"`) || !strings.Contains(infoLog, `"port"=8080`) || !strings.Contains(infoLog, `"env"="test"`) {
		fmt.Fprintf(os.Stderr, "FAIL: info log format unexpected: %s\n", infoLog)
		os.Exit(1)
	}

	// Assertion 3: logger.Error logs error details and messages through TestingT
	t.logs = nil
	sampleErr := errors.New("connection reset")
	logger.Error(sampleErr, "operation failed", "retry", 3)
	if len(t.logs) != 1 {
		fmt.Fprintf(os.Stderr, "FAIL: expected 1 error log entry, got %d\n", len(t.logs))
		os.Exit(1)
	}
	errLog := t.logs[0]
	if !strings.Contains(errLog, `"msg"="operation failed"`) || !strings.Contains(errLog, `"error"="connection reset"`) || !strings.Contains(errLog, `"retry"=3`) {
		fmt.Fprintf(os.Stderr, "FAIL: error log format unexpected: %s\n", errLog)
		os.Exit(1)
	}

	// Assertion 4: testr.Options Verbosity controls V-level logging enablement and filtering
	if !logger.V(1).Enabled() {
		fmt.Fprintf(os.Stderr, "FAIL: logger.V(1) should be enabled with Verbosity=1\n")
		os.Exit(1)
	}
	if logger.V(2).Enabled() {
		fmt.Fprintf(os.Stderr, "FAIL: logger.V(2) should be disabled with Verbosity=1\n")
		os.Exit(1)
	}
	t.logs = nil
	logger.V(1).Info("v1 log message", "detail", "verbose")
	logger.V(2).Info("v2 log message", "detail", "silent")
	if len(t.logs) != 1 {
		fmt.Fprintf(os.Stderr, "FAIL: expected only V(1) log, got %d logs\n", len(t.logs))
		os.Exit(1)
	}
	if !strings.Contains(t.logs[0], "v1 log message") {
		fmt.Fprintf(os.Stderr, "FAIL: unexpected V(1) log content: %s\n", t.logs[0])
		os.Exit(1)
	}

	// Assertion 5: logger.WithName and logger.WithValues enrich log context prefix and attributes
	t.logs = nil
	namedLogger := logger.WithName("worker").WithValues("worker_id", "w-42")
	namedLogger.Info("job completed", "status", "ok")
	if len(t.logs) != 1 {
		fmt.Fprintf(os.Stderr, "FAIL: expected 1 named log entry, got %d\n", len(t.logs))
		os.Exit(1)
	}
	contextLog := t.logs[0]
	if !strings.Contains(contextLog, "worker:") || !strings.Contains(contextLog, `"worker_id"="w-42"`) || !strings.Contains(contextLog, `"status"="ok"`) {
		fmt.Fprintf(os.Stderr, "FAIL: contextual log format unexpected: %s\n", contextLog)
		os.Exit(1)
	}

	// Assertion 6: logger sink implements testr.UnderlierInterface returning the original TestingT instance
	sink := logger.GetSink()
	underlier, ok := sink.(testr.UnderlierInterface)
	if !ok {
		fmt.Fprintf(os.Stderr, "FAIL: sink does not implement testr.UnderlierInterface\n")
		os.Exit(1)
	}
	if underlier.GetUnderlying() != t {
		fmt.Fprintf(os.Stderr, "FAIL: underlier.GetUnderlying() did not return original TestingT pointer\n")
		os.Exit(1)
	}

	fmt.Println("PASS: github.com/go-logr/logr/testr.NewWithInterface contract passed")
}

Seeder de origen

anónimo