CodeSampleX

샘플

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

검증된 샘플 — golang github.com/go-logr/logr v1.4.1: testr.NewWithInterface. go 1.26 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:ef7a119df58d6ba9df6873ee3e70bc41a77744844ca46efc47453433cf76e6d4

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

실행 증거

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

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 go

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
verify github.com/go-logr/logr/testr.NewWithInterface in pkg:golang/github.com/go-logr/logr@v1.4.1
패키지
심벌
  • github.com/go-logr/logr/testr.NewWithInterface
생성일
2026-08-27T10:30:04Z

컨트랙트

  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

파일

  • 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 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")
}

오리진 시더

익명