CodeSampleX

Beispiel

go.yaml.in/yaml/v3 v3.0.5: Unmarshaler

Verifiziertes Beispiel für golang go.yaml.in/yaml/v3 v3.0.5: Unmarshaler. Der Vertrag lief auf go 1.26 · linux debian/x64 · docker und bestand.

sha256:e83d2dac20241001a7b8bf059388022642e99fdabffad1622c781dd45e83ea16

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
1
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
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-05

Fall

HOW
Ziel
verify pkg:golang/go.yaml.in/yaml/v3@v3.0.5
Pakete
Symbole
  • Unmarshaler
Umgebung
go 1.26.6
Erstellt
2026-09-05T09:16:51Z

Contract

  1. yaml.Unmarshaler unmarshals custom scalar node values into domain types
  2. yaml.Unmarshaler unmarshals custom mapping node values into structured types with default values
  3. yaml.Unmarshaler unmarshals custom types within nested struct fields and slices
  4. yaml.Unmarshaler propagates custom validation errors during decoding

Dateien

  • PROMPT.md
  • contract_test.go
  • csx.json
  • go.mod
  • go.sum
  • spec.json

Quellartefakt herunterladen (tar.gz)

Quelltext

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/go.yaml.in/yaml/v3@v3.0.5
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.yaml.in/yaml/v3@v3.0.5
Demonstrate these symbols/APIs:
  - Unmarshaler

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.
contract_test.go
package sample

import (
	"errors"
	"strings"
	"testing"
	"time"

	"go.yaml.in/yaml/v3"
)

// CustomDuration implements yaml.Unmarshaler for a time.Duration represented as a scalar string.
type CustomDuration struct {
	time.Duration
}

func (d *CustomDuration) UnmarshalYAML(value *yaml.Node) error {
	if value.Kind != yaml.ScalarNode {
		return errors.New("expected scalar node for duration")
	}
	dur, err := time.ParseDuration(value.Value)
	if err != nil {
		return err
	}
	d.Duration = dur
	return nil
}

// EndpointConfig implements yaml.Unmarshaler on a mapping node with default fallback values.
type EndpointConfig struct {
	Host    string `yaml:"host"`
	Port    int    `yaml:"port"`
	Timeout time.Duration
}

func (e *EndpointConfig) UnmarshalYAML(value *yaml.Node) error {
	if value.Kind != yaml.MappingNode {
		return errors.New("expected mapping node for endpoint config")
	}

	type alias struct {
		Host    string         `yaml:"host"`
		Port    int            `yaml:"port"`
		Timeout CustomDuration `yaml:"timeout"`
	}
	defaults := alias{
		Port:    8080,
		Timeout: CustomDuration{Duration: 5 * time.Second},
	}

	if err := value.Decode(&defaults); err != nil {
		return err
	}

	if defaults.Host == "" {
		return errors.New("host must not be empty")
	}

	e.Host = defaults.Host
	e.Port = defaults.Port
	e.Timeout = defaults.Timeout.Duration
	return nil
}

// AppConfig contains custom unmarshaler types in struct fields and slices.
type AppConfig struct {
	Name      string           `yaml:"name"`
	Endpoints []EndpointConfig `yaml:"endpoints"`
}

// ValidatedPriority implements yaml.Unmarshaler with strict value validation.
type ValidatedPriority int

func (p *ValidatedPriority) UnmarshalYAML(value *yaml.Node) error {
	var v int
	if err := value.Decode(&v); err != nil {
		return err
	}
	if v < 1 || v > 5 {
		return errors.New("priority must be between 1 and 5")
	}
	*p = ValidatedPriority(v)
	return nil
}

func TestCustomScalarUnmarshaler(t *testing.T) {
	raw := "1500ms"
	var dur CustomDuration
	if err := yaml.Unmarshal([]byte(raw), &dur); err != nil {
		t.Fatalf("yaml.Unmarshal failed: %v", err)
	}
	if dur.Duration != 1500*time.Millisecond {
		t.Fatalf("expected 1500ms, got %v", dur.Duration)
	}
}

func TestCustomMappingUnmarshalerWithDefaults(t *testing.T) {
	raw := `
host: api.example.internal
`
	var ep EndpointConfig
	if err := yaml.Unmarshal([]byte(raw), &ep); err != nil {
		t.Fatalf("yaml.Unmarshal failed: %v", err)
	}
	if ep.Host != "api.example.internal" {
		t.Errorf("expected host 'api.example.internal', got %q", ep.Host)
	}
	if ep.Port != 8080 {
		t.Errorf("expected default port 8080, got %d", ep.Port)
	}
	if ep.Timeout != 5*time.Second {
		t.Errorf("expected default timeout 5s, got %v", ep.Timeout)
	}
}

func TestNestedUnmarshalerFieldsAndSlices(t *testing.T) {
	raw := `
name: gateway-service
endpoints:
  - host: backend-a.internal
    port: 9001
    timeout: 2s
  - host: backend-b.internal
`
	var app AppConfig
	if err := yaml.Unmarshal([]byte(raw), &app); err != nil {
		t.Fatalf("yaml.Unmarshal failed: %v", err)
	}
	if app.Name != "gateway-service" {
		t.Errorf("expected name 'gateway-service', got %q", app.Name)
	}
	if len(app.Endpoints) != 2 {
		t.Fatalf("expected 2 endpoints, got %d", len(app.Endpoints))
	}
	if app.Endpoints[0].Port != 9001 || app.Endpoints[0].Timeout != 2*time.Second {
		t.Errorf("expected endpoint 0 {port: 9001, timeout: 2s}, got %+v", app.Endpoints[0])
	}
	if app.Endpoints[1].Port != 8080 || app.Endpoints[1].Timeout != 5*time.Second {
		t.Errorf("expected endpoint 1 with defaults {port: 8080, timeout: 5s}, got %+v", app.Endpoints[1])
	}
}

func TestUnmarshalerValidationErrorPropagation(t *testing.T) {
	// 1. Invalid scalar value
	rawInvalidScalar := "not-a-valid-duration"
	var dur CustomDuration
	if err := yaml.Unmarshal([]byte(rawInvalidScalar), &dur); err == nil {
		t.Fatal("expected error parsing invalid duration, got nil")
	}

	// 2. Custom validation rule violation in mapping
	rawMissingHost := `
port: 3000
`
	var ep EndpointConfig
	err := yaml.Unmarshal([]byte(rawMissingHost), &ep)
	if err == nil {
		t.Fatal("expected error for missing host, got nil")
	}
	if !strings.Contains(err.Error(), "host must not be empty") {
		t.Errorf("expected error message to contain 'host must not be empty', got %v", err)
	}

	// 3. Custom priority validation
	rawInvalidPriority := "priority: 99"
	var config struct {
		Priority ValidatedPriority `yaml:"priority"`
	}
	err = yaml.Unmarshal([]byte(rawInvalidPriority), &config)
	if err == nil {
		t.Fatal("expected error for priority out of range, got nil")
	}
	if !strings.Contains(err.Error(), "priority must be between 1 and 5") {
		t.Errorf("expected error message to contain 'priority must be between 1 and 5', got %v", err)
	}
}
csx.json
{"case":{"caseId":"case:sha256:10ba545b541833e9368d066633ac2e460c377f104060b7b256634d06200b049b","contract":["yaml.Unmarshaler unmarshals custom scalar node values into domain types","yaml.Unmarshaler unmarshals custom mapping node values into structured types with default values","yaml.Unmarshaler unmarshals custom types within nested struct fields and slices","yaml.Unmarshaler propagates custom validation errors during decoding"],"goal":"verify pkg:golang/go.yaml.in/yaml/v3@v3.0.5","kind":"HOW","packages":["pkg:golang/go.yaml.in/yaml/v3@v3.0.5"],"schemaVersion":1,"symbols":["Unmarshaler"]},"contractCommand":["go","test","-v","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","packageManagerVersion":"1.26.6","runtime":"go","runtimeVersion":"1.26.6","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/go.yaml.in/yaml/v3@v3.0.5"],"schemaVersion":1,"subject":"pkg:golang/go.yaml.in/yaml/v3@v3.0.5","symbols":["Unmarshaler"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.22

require go.yaml.in/yaml/v3 v3.0.5
go.sum
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/go.yaml.in/yaml/v3@v3.0.5",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.yaml.in/yaml/v3@v3.0.5"
  ],
  "symbols": [
    "Unmarshaler"
  ]
}

Ursprungs-Seeder

anonym