-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathplugin_test.go
More file actions
97 lines (88 loc) · 2.4 KB
/
plugin_test.go
File metadata and controls
97 lines (88 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// Copyright 2026 The go-yaml Project Contributors
// SPDX-License-Identifier: Apache-2.0
package yaml_test
import (
"bytes"
"strings"
"testing"
"go.yaml.in/yaml/v4"
"go.yaml.in/yaml/v4/plugin/limit"
)
// generateAliases builds YAML with n aliases referencing a large anchor.
func generateAliases(n int) []byte {
var sb strings.Builder
sb.WriteString("anchor: &anchor [1, 2, 3]\nrefs:\n")
for i := 0; i < n; i++ {
sb.WriteString("- *anchor\n")
}
return []byte(sb.String())
}
// generateDeepNesting builds deeply nested flow YAML.
func generateDeepNesting(depth int) []byte {
var sb strings.Builder
for i := 0; i < depth; i++ {
sb.WriteString("[")
}
sb.WriteString("x")
for i := 0; i < depth; i++ {
sb.WriteString("]")
}
return []byte(sb.String())
}
func TestWithPlugin_Limit_AliasFunc(t *testing.T) {
called := false
fn := func(aliasCount, constructCount int) error {
called = true
return nil
}
data := generateAliases(200)
var result any
err := yaml.Load(data, &result, yaml.WithPlugin(limit.New(limit.AliasFunc(fn))))
if err != nil {
t.Fatalf("Expected success with custom AliasFunc, got: %v", err)
}
if !called {
t.Error("Expected custom AliasFunc to be called")
}
}
func TestWithPlugin_Limit_DepthFunc(t *testing.T) {
called := false
fn := func(depth int, ctx *yaml.DepthContext) error {
called = true
return nil
}
data := generateDeepNesting(5)
var result any
err := yaml.Load(data, &result, yaml.WithPlugin(limit.New(limit.DepthFunc(fn))))
if err != nil {
t.Fatalf("Expected success with custom DepthFunc, got: %v", err)
}
if !called {
t.Error("Expected custom DepthFunc to be called")
}
}
func TestWithPlugin_UnsupportedType(t *testing.T) {
data := []byte(`key: value`)
var result map[string]any
// Pass an unsupported type (integer) as a plugin
err := yaml.Load(data, &result, yaml.WithPlugin(42))
if err == nil {
t.Fatal("Expected error for unsupported plugin type, got nil")
}
if err.Error() != "yaml: unsupported plugin type: int" {
t.Errorf("Unexpected error message: %v", err)
}
}
func TestDefaultBehavior_HasLimit(t *testing.T) {
// Bare NewLoader should have default depth limits
data := generateDeepNesting(10001)
loader, err := yaml.NewLoader(bytes.NewReader(data))
if err != nil {
t.Fatalf("NewLoader failed: %v", err)
}
var result any
err = loader.Load(&result)
if err == nil {
t.Fatal("Expected error from default depth limits, got nil")
}
}