60 lines
2.0 KiB
Go
60 lines
2.0 KiB
Go
package jsonvalue
|
|
|
|
import (
|
|
"encoding/json"
|
|
"reflect"
|
|
"testing"
|
|
)
|
|
|
|
type trustedNamed string
|
|
|
|
func TestCloneTrustedDoesNotCopySpareCapacity(t *testing.T) {
|
|
type namedSlice []string
|
|
for name, original := range map[string]any{
|
|
"any": make([]any, 1, 64),
|
|
"empty": make([]any, 0, 64),
|
|
"strings": make([]string, 1, 64),
|
|
"bytes": make([]byte, 1, 64),
|
|
"named": make(namedSlice, 1, 64),
|
|
} {
|
|
t.Run(name, func(t *testing.T) {
|
|
copied := CloneTrusted(original)
|
|
if !reflect.DeepEqual(copied, original) {
|
|
t.Fatalf("copy changed slice contents or type: %#v", copied)
|
|
}
|
|
value := reflect.ValueOf(copied)
|
|
if value.Cap() != value.Len() {
|
|
t.Fatalf("copy reserves unused storage: len=%d cap=%d", value.Len(), value.Cap())
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestCloneTrustedPreservesTypesAndDetaches(t *testing.T) {
|
|
named := trustedNamed("value")
|
|
original := map[string]any{"": map[string]any{"number": json.Number("9007199254740993")}, "typed": []string{"original"}, "pointer": &named, "nilmap": map[string]any(nil), "nilslice": []string(nil), "empty": []any{}}
|
|
copy := CloneTrusted(original).(map[string]any)
|
|
if !reflect.DeepEqual(copy, original) {
|
|
t.Fatalf("clone = %#v", copy)
|
|
}
|
|
copy[""].(map[string]any)["number"] = json.Number("1")
|
|
copy["typed"].([]string)[0] = "changed"
|
|
*copy["pointer"].(*trustedNamed) = "changed"
|
|
if original[""].(map[string]any)["number"] != json.Number("9007199254740993") || original["typed"].([]string)[0] != "original" || named != "value" {
|
|
t.Fatal("clone shares mutable storage")
|
|
}
|
|
if copy["nilmap"].(map[string]any) != nil || copy["nilslice"].([]string) != nil || copy["empty"].([]any) == nil {
|
|
t.Fatal("nil/empty shape changed")
|
|
}
|
|
}
|
|
|
|
func TestCloneTrustedDetachesCycles(t *testing.T) {
|
|
original := map[string]any{}
|
|
original["self"] = original
|
|
copy := CloneTrusted(original).(map[string]any)
|
|
copy["self"].(map[string]any)["changed"] = true
|
|
if copy["changed"] != true || original["changed"] != nil {
|
|
t.Fatal("cyclic copy did not preserve its cycle independently")
|
|
}
|
|
}
|