Distinguish metadata slice views from cycles

This commit is contained in:
2026-11-26 01:30:49 +00:00
parent b6f04297d4
commit 97bcf8cae6
4 changed files with 78 additions and 3 deletions

View File

@@ -0,0 +1,58 @@
package source
import (
"reflect"
"strings"
"testing"
)
func TestCloneMetadataSharedSliceViews(t *testing.T) {
values := []any{"one", nil}
values[1] = values[:1]
shared := []string{"original"}
var nilSlice []string
input := map[string]any{"values": values, "first": shared, "second": shared, "nil": nilSlice, "empty": []string{}}
cloned, err := CloneMetadata(input)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(cloned, input) {
t.Fatalf("clone = %#v, want %#v", cloned, input)
}
outer := cloned["values"].([]any)
outer[1].([]any)[0] = "changed"
cloned["first"].([]string)[0] = "changed"
if values[0] != "one" || outer[0] != "one" || shared[0] != "original" || cloned["second"].([]string)[0] != "original" {
t.Fatal("cloned slice views share mutable elements")
}
if cloned["nil"].([]string) != nil || cloned["empty"].([]string) == nil {
t.Fatal("clone did not preserve nil and empty slices")
}
values[1] = values[:0]
cloned, err = CloneMetadata(map[string]any{"values": values})
if err != nil || cloned["values"].([]any)[1].([]any) == nil {
t.Fatalf("empty shared view clone = %#v, error = %v", cloned, err)
}
}
func TestCloneMetadataRejectsActualCycles(t *testing.T) {
slice := make([]any, 1)
slice[0] = slice
object := map[string]any{}
object["self"] = object
for _, tc := range []struct {
name string
value any
path string
}{
{"slice", slice, "metadata.value[0]"},
{"map", object, "metadata.value.self"},
} {
t.Run(tc.name, func(t *testing.T) {
_, err := CloneMetadata(map[string]any{"value": tc.value})
if err == nil || !strings.Contains(err.Error(), tc.path+" contains a cycle") {
t.Fatalf("CloneMetadata() error = %v, want cycle at %s", err, tc.path)
}
})
}
}