CodeSampleX

샘플

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

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

sha256:40fe2280c831427d7b49d180412337c2788b106e0c1dc8f49a7b2ad5662bf15c

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

실행 증거

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

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 go 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.Options in pkg:golang/github.com/go-logr/logr@v1.4.1
패키지
심벌
  • github.com/go-logr/logr/testr.Options
생성일
2026-08-27T10:32:49Z

컨트랙트

  1. testr.Options configures test logger Verbosity level and LogTimestamp formatting
  2. testr.Options Verbosity enables V-level logging up to configured threshold and suppresses higher levels
  3. testr.Options LogTimestamp true prepends timestamp ts field to log output
  4. testr.Options LogTimestamp false omits timestamp ts field from log output
  5. zero value testr.Options defaults to Verbosity 0 and disabled timestamp logging
  6. testr.Options applies to contextual loggers derived with WithName and WithValues

파일

  • 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.Options 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.Options
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: esm
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:e4ce6a58b6288ee62c350bd52ea3a69857d3dee4ab7faae8727dd5d15eb3082c","contract":["testr.Options configures test logger Verbosity level and LogTimestamp formatting","testr.Options Verbosity enables V-level logging up to configured threshold and suppresses higher levels","testr.Options LogTimestamp true prepends timestamp ts field to log output","testr.Options LogTimestamp false omits timestamp ts field from log output","zero value testr.Options defaults to Verbosity 0 and disabled timestamp logging","testr.Options applies to contextual loggers derived with WithName and WithValues"],"goal":"verify github.com/go-logr/logr/testr.Options 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.Options"]},"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/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.Options"],"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 (
	"fmt"

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

// RecordTestingT captures log output for inspection.
type RecordTestingT struct {
	logs []string
}

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

// Log appends formatted message to logs.
func (r *RecordTestingT) Log(args ...any) {
	msg := fmt.Sprint(args...)
	r.logs = append(r.logs, msg)
	fmt.Println(msg)
}

// NewConfiguredLogger creates a test logger with explicit testr.Options.
func NewConfiguredLogger(t testr.TestingT, verbosity int, logTimestamp bool) logr.Logger {
	opts := testr.Options{
		Verbosity:    verbosity,
		LogTimestamp: logTimestamp,
	}
	return testr.NewWithInterface(t, opts)
}

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

	// Create logger with Verbosity 1 and timestamp enabled
	logger := NewConfiguredLogger(tester, 1, true)

	logger.Info("application started", "mode", "production-sim")
	logger.V(1).Info("verbose debugging line", "step", 1)
	logger.V(2).Info("suppressed higher verbosity line", "step", 2)

	subLogger := logger.WithName("subsystem").WithValues("component", "worker")
	subLogger.Info("subsystem processed task", "items", 5)

	fmt.Printf("Recorded %d log statements\n", len(tester.logs))
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/go-logr/logr/testr.Options 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.Options"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "esm",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.go
package main

import (
	"fmt"
	"os"
	"strings"

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

type recordTestingT struct {
	logs []string
}

func (r *recordTestingT) Helper() {}

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

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 {
	t := &recordTestingT{}

	// 1. testr.Options configures test logger Verbosity level and LogTimestamp formatting
	opts := testr.Options{
		Verbosity:    2,
		LogTimestamp: true,
	}
	var logger logr.Logger = testr.NewWithInterface(t, opts)
	if logger.GetSink() == nil {
		return fmt.Errorf("logger sink is nil")
	}

	// 2. testr.Options Verbosity enables V-level logging up to configured threshold and suppresses higher levels
	if !logger.V(0).Enabled() {
		return fmt.Errorf("expected V(0) to be enabled with Verbosity=2")
	}
	if !logger.V(1).Enabled() {
		return fmt.Errorf("expected V(1) to be enabled with Verbosity=2")
	}
	if !logger.V(2).Enabled() {
		return fmt.Errorf("expected V(2) to be enabled with Verbosity=2")
	}
	if logger.V(3).Enabled() {
		return fmt.Errorf("expected V(3) to be disabled with Verbosity=2")
	}

	t.logs = nil
	logger.V(1).Info("v1 message", "k1", "v1")
	logger.V(2).Info("v2 message", "k2", "v2")
	logger.V(3).Info("v3 message", "k3", "v3")

	if len(t.logs) != 2 {
		return fmt.Errorf("expected exactly 2 logs, got %d", len(t.logs))
	}
	if !strings.Contains(t.logs[0], `"msg"="v1 message"`) {
		return fmt.Errorf("unexpected v1 log content: %s", t.logs[0])
	}
	if !strings.Contains(t.logs[1], `"msg"="v2 message"`) {
		return fmt.Errorf("unexpected v2 log content: %s", t.logs[1])
	}

	// 3. testr.Options LogTimestamp true prepends timestamp ts field to log output
	t.logs = nil
	logger.Info("timestamp check", "test", "active")
	if len(t.logs) != 1 {
		return fmt.Errorf("expected 1 log entry, got %d", len(t.logs))
	}
	if !strings.Contains(t.logs[0], `"ts"=`) {
		return fmt.Errorf("expected log line to contain \"ts\"= when LogTimestamp is true, got: %s", t.logs[0])
	}

	// 4. testr.Options LogTimestamp false omits timestamp ts field from log output
	t.logs = nil
	noTSOpts := testr.Options{
		Verbosity:    1,
		LogTimestamp: false,
	}
	noTSLogger := testr.NewWithInterface(t, noTSOpts)
	noTSLogger.Info("no timestamp check", "test", "active")
	if len(t.logs) != 1 {
		return fmt.Errorf("expected 1 log entry, got %d", len(t.logs))
	}
	if strings.Contains(t.logs[0], `"ts"=`) {
		return fmt.Errorf("expected log line not to contain \"ts\"= when LogTimestamp is false, got: %s", t.logs[0])
	}

	// 5. zero value testr.Options defaults to Verbosity 0 and disabled timestamp logging
	t.logs = nil
	zeroOpts := testr.Options{}
	zeroLogger := testr.NewWithInterface(t, zeroOpts)
	if !zeroLogger.V(0).Enabled() {
		return fmt.Errorf("zero value options should enable V(0)")
	}
	if zeroLogger.V(1).Enabled() {
		return fmt.Errorf("zero value options should disable V(1)")
	}
	zeroLogger.Info("zero options message")
	zeroLogger.V(1).Info("suppressed zero options message")
	if len(t.logs) != 1 {
		return fmt.Errorf("expected 1 log entry from zero options logger, got %d", len(t.logs))
	}
	if strings.Contains(t.logs[0], `"ts"=`) {
		return fmt.Errorf("zero options should not include timestamp, got: %s", t.logs[0])
	}

	// 6. testr.Options applies to contextual loggers derived with WithName and WithValues
	t.logs = nil
	namedLogger := logger.WithName("worker").WithValues("worker_id", "w-101")
	namedLogger.V(2).Info("child worker job finished", "status", "success")
	namedLogger.V(3).Info("child worker trace suppressed")
	if len(t.logs) != 1 {
		return fmt.Errorf("expected 1 contextual log entry, got %d", len(t.logs))
	}
	childLog := t.logs[0]
	if !strings.Contains(childLog, `"ts"=`) {
		return fmt.Errorf("child logger should retain timestamp formatting: %s", childLog)
	}
	if !strings.Contains(childLog, "worker:") || !strings.Contains(childLog, `"worker_id"="w-101"`) || !strings.Contains(childLog, `"status"="success"`) {
		return fmt.Errorf("unexpected child log structure: %s", childLog)
	}

	return nil
}

오리진 시더

익명