CodeSampleX

Exemple

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

Échantillon vérifié pour golang go.yaml.in/yaml/v3 v3.0.5: Unmarshaler. Le contrat s'est exécuté sur go 1.26 · linux debian/x64 · docker et a réussi.

sha256:963234745979aec2e74b0761c8aff3ab882a7ec2090c1f053bb384e12de81bc8

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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

Cas

HOW
Objectif
verify Unmarshaler in pkg:golang/go.yaml.in/yaml/v3@v3.0.5
Paquets
Symboles
  • Unmarshaler
Environnement
go 1.26.6
Créé
2026-09-05T09:23:43Z

Contrat

  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

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

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 Unmarshaler in 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 string-formatted durations.
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 for mapping nodes with default 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 demonstrates nested unmarshaler fields and slices.
type AppConfig struct {
	Name      string           `yaml:"name"`
	Endpoints []EndpointConfig `yaml:"endpoints"`
}

// PriorityLevel implements yaml.Unmarshaler with boundary validation.
type PriorityLevel int

func (p *PriorityLevel) UnmarshalYAML(value *yaml.Node) error {
	var val int
	if err := value.Decode(&val); err != nil {
		return err
	}
	if val < 1 || val > 5 {
		return errors.New("priority must be between 1 and 5")
	}
	*p = PriorityLevel(val)
	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. Boundary validation
	rawInvalidPriority := "priority: 10"
	var config struct {
		Priority PriorityLevel `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:947a67b407abcc0804ad9bb064489f7e238e70b70bce7f3e9b8b0322fbb7ae5b","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 Unmarshaler in 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 Unmarshaler in 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"
  ]
}

Seeder d'origine

anonyme