| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 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 |
|
| 33 |
|
| 34 |
type foreignNode struct { |
| 35 |
Bogus int |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
r. |
| 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 |
|
| 50 |
d. |
| 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 |
|
| 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 |
se |
| 72 |
|
| 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 |
|
| 81 |
|
| 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 |
|
| 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 |
} |