CodeSampleX

示例

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

已验证示例 — golang github.com/go-logr/logr v1.4.1: testr.Options. contract 在 go 1.26 · linux alpine/x64 · docker 上运行并通过: testr.Options configures test logger…

sha256:40fe2280c831427d7b49d180412337c2788b106e0c1dc8f49a7b2ad5662bf15c

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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
}

原始种子者

匿名