Debian Codegraph @

internal/libyaml/structmeta_test.go

raw symbols SCIP
1 // Copyright 2025 The go-yaml Project Contributors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Tests for isYAMLNodePkg and the Node type allowlist.
5
6 package libyaml
7
8 import (
9 "reflect"
10 "testing"
11 )
12
13 func TestIsYAMLNodePkg(t *testing.T) {
14 tests := []struct {
15 pkg string
16 want bool
17 }{
18 {"gopkg.in/yaml.v3", true},
19 {"go.yaml.in/yaml/v3", true},
20 {"example.com/mypkg", false},
21 {"gopkg.in/yaml.v2", false},
22 {"", false},
23 }
24 for _, tt := range tests {
25 if got := isYAMLNodePkg(tt.pkg); got != tt.want {
26 t.Errorf("isYAMLNodePkg(%q) = %v, want %v",
27 tt.pkg, got, tt.want)
28 }
29 }
30 }
31
32 // foreignNode is a user-defined type that happens to be named "Node"
33 // but is NOT from a known yaml package. The allowlist must reject it.
34 type foreignNode struct {
35 Bogus int
36 }
37
38 // foreignNodeReceiver has an UnmarshalYAML method that takes a
39 // *foreignNode — this must NOT be treated as a yaml.Unmarshaler.
40 type foreignNodeReceiver struct {
41 Value string
42 }
43
44 func (f *foreignNodeReceiver) UnmarshalYAML(n *foreignNode) error {
45 f.Value = "should not be called"
46 return nil
47 }
48
49 // yamlNodeReceiver has an UnmarshalYAML method that takes the real
50 // *Node from this package — this MUST be accepted.
51 type yamlNodeReceiver struct {
52 Value string
53 }
54
55 func (y *yamlNodeReceiver) UnmarshalYAML(n *Node) error {
56 if n.Value != "" {
57 y.Value = n.Value
58 }
59 return nil
60 }
61
62 func TestForeignNodeRejected(t *testing.T) {
63 // hasConstructYAMLMethod must return false for foreignNodeReceiver.
64 ft := reflect.TypeOf(foreignNodeReceiver{})
65 if hasConstructYAMLMethod(reflect.PointerTo(ft)) {
66 t.Error("hasConstructYAMLMethod accepted foreignNodeReceiver")
67 }
68 }
69
70 func TestRealNodeNotInAllowlist(t *testing.T) {
71 // v4 types (this package) are no longer in the allowlist — they use
72 // the native constructor interface instead of the unsafe cast path.
73 yt := reflect.TypeOf(yamlNodeReceiver{})
74 if hasConstructYAMLMethod(reflect.PointerTo(yt)) {
75 t.Error("hasConstructYAMLMethod should not match v4 types")
76 }
77 }
78
79 func TestForeignNodeUnmarshal(t *testing.T) {
80 // Unmarshaling into foreignNodeReceiver must silently skip the
81 // UnmarshalYAML method (not panic or corrupt memory).
82 var f foreignNodeReceiver
83 err := Load([]byte("hello"), &f)
84 if err == nil {
85 t.Fatal("expected error unmarshaling scalar into struct")
86 }
87 if f.Value == "should not be called" {
88 t.Error("foreign UnmarshalYAML was incorrectly called")
89 }
90 }
91
92 func TestRealNodeUnmarshal(t *testing.T) {
93 // Unmarshaling into yamlNodeReceiver must call UnmarshalYAML.
94 var y yamlNodeReceiver
95 err := Load([]byte("hello"), &y)
96 if err != nil {
97 t.Fatalf("unexpected error: %v", err)
98 }
99 if y.Value != "hello" {
100 t.Errorf("Value = %q, want %q", y.Value, "hello")
101 }
102 }