CodeSampleX

샘플

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

검증된 샘플 — golang go.yaml.in/yaml/v3 v3.0.5: Unmarshaler. go 1.26 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: yaml.Unmarshaler unmarshals custom scalar…

sha256:963234745979aec2e74b0761c8aff3ab882a7ec2090c1f053bb384e12de81bc8

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

실행 증거

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

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

검증 실행 환경

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

케이스

HOW
목표
verify Unmarshaler in pkg:golang/go.yaml.in/yaml/v3@v3.0.5
패키지
심벌
  • Unmarshaler
환경
go 1.26.6
생성일
2026-09-05T09:23:43Z

컨트랙트

  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

파일

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

소스 아티팩트 내려받기 (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 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"
  ]
}

오리진 시더

익명