| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
package yaml_test |
| 5 |
|
| 6 |
import ( |
| 7 |
"bytes" |
| 8 |
"strings" |
| 9 |
"testing" |
| 10 |
|
| 11 |
"go.yaml.in/yaml/v4" |
| 12 |
"go.yaml.in/yaml/v4/plugin/limit" |
| 13 |
) |
| 14 |
|
| 15 |
|
| 16 |
func generateAliases(n int) []byte { |
| 17 |
var sb strings.Builder |
| 18 |
sb.WriteString("anchor: &anchor [1, 2, 3]\nrefs:\n") |
| 19 |
for i := 0; i < n; i++ { |
| 20 |
sb.WriteString("- *anchor\n") |
| 21 |
} |
| 22 |
return []byte(sb.String()) |
| 23 |
} |
| 24 |
|
| 25 |
|
| 26 |
func generateDeepNesting(depth int) []byte { |
| 27 |
var sb strings.Builder |
| 28 |
for i := 0; i < depth; i++ { |
| 29 |
sb.WriteString("[") |
| 30 |
} |
| 31 |
sb.WriteString("x") |
| 32 |
for i := 0; i < depth; i++ { |
| 33 |
sb.WriteString("]") |
| 34 |
} |
| 35 |
return []byte(sb.String()) |
| 36 |
} |
| 37 |
|
| 38 |
func TestWithPlugin_Limit_AliasFunc(t *testing.T) { |
| 39 |
called := false |
| 40 |
fn := func(aliasCount, constructCount int) error { |
| 41 |
called = true |
| 42 |
return nil |
| 43 |
} |
| 44 |
data := generateAliases(200) |
| 45 |
var result any |
| 46 |
err := yaml.Load(data, &result, yaml.WithPlugin(limit.New(limit.AliasFunc(fn)))) |
| 47 |
if err != nil { |
| 48 |
t.Fatalf("Expected success with custom AliasFunc, got: %v", err) |
| 49 |
} |
| 50 |
if !called { |
| 51 |
t.Error("Expected custom AliasFunc to be called") |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
func TestWithPlugin_Limit_DepthFunc(t *testing.T) { |
| 56 |
called := false |
| 57 |
fn := func(depth int, ctx *yaml.DepthContext) error { |
| 58 |
called = true |
| 59 |
return nil |
| 60 |
} |
| 61 |
data := generateDeepNesting(5) |
| 62 |
var result any |
| 63 |
err := yaml.Load(data, &result, yaml.WithPlugin(limit.New(limit.DepthFunc(fn)))) |
| 64 |
if err != nil { |
| 65 |
t.Fatalf("Expected success with custom DepthFunc, got: %v", err) |
| 66 |
} |
| 67 |
if !called { |
| 68 |
t.Error("Expected custom DepthFunc to be called") |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
func TestWithPlugin_UnsupportedType(t *testing.T) { |
| 73 |
data := []byte(`key: value`) |
| 74 |
var result map[string]any |
| 75 |
|
| 76 |
err := yaml.Load(data, &result, yaml.WithPlugin(42)) |
| 77 |
if err == nil { |
| 78 |
t.Fatal("Expected error for unsupported plugin type, got nil") |
| 79 |
} |
| 80 |
if err.Error() != "yaml: unsupported plugin type: int" { |
| 81 |
t.Errorf("Unexpected error message: %v", err) |
| 82 |
} |
| 83 |
} |
| 84 |
|
| 85 |
func TestDefaultBehavior_HasLimit(t *testing.T) { |
| 86 |
|
| 87 |
data := generateDeepNesting(10001) |
| 88 |
loader, err := yaml.NewLoader(bytes.NewReader(data)) |
| 89 |
if err != nil { |
| 90 |
t.Fatalf("NewLoader failed: %v", err) |
| 91 |
} |
| 92 |
var result any |
| 93 |
err = loader.Load(&result) |
| 94 |
if err == nil { |
| 95 |
t.Fatal("Expected error from default depth limits, got nil") |
| 96 |
} |
| 97 |
} |