103 lines
2.0 KiB
Go
103 lines
2.0 KiB
Go
package cast_test
|
|
|
|
import (
|
|
"testing"
|
|
"apigo.cc/go/cast"
|
|
)
|
|
|
|
type SubConfig struct {
|
|
Level int
|
|
Tag string
|
|
}
|
|
|
|
type MainConfig struct {
|
|
Name string
|
|
Sub SubConfig
|
|
Items []string
|
|
Options map[string]int
|
|
}
|
|
|
|
func TestDeepMergeComplex(t *testing.T) {
|
|
dst := MainConfig{
|
|
Name: "Base",
|
|
Sub: SubConfig{
|
|
Level: 1,
|
|
Tag: "original",
|
|
},
|
|
Items: []string{"a", "b"},
|
|
Options: map[string]int{
|
|
"debug": 1,
|
|
"trace": 0,
|
|
},
|
|
}
|
|
|
|
src := map[string]any{
|
|
"Sub": map[string]any{
|
|
"Level": 2,
|
|
},
|
|
"Options": map[string]any{
|
|
"trace": 1,
|
|
"new": 100,
|
|
},
|
|
}
|
|
|
|
cast.Convert(&dst, src)
|
|
|
|
if dst.Name != "Base" {
|
|
t.Errorf("Expected Name Base, got %s", dst.Name)
|
|
}
|
|
if dst.Sub.Level != 2 {
|
|
t.Errorf("Expected Sub.Level 2, got %d", dst.Sub.Level)
|
|
}
|
|
if dst.Sub.Tag != "original" {
|
|
t.Errorf("Expected Sub.Tag original, got %s", dst.Sub.Tag)
|
|
}
|
|
if len(dst.Items) != 2 {
|
|
t.Errorf("Expected Items length 2, got %d", len(dst.Items))
|
|
}
|
|
if dst.Options["debug"] != 1 {
|
|
t.Errorf("Expected Options.debug 1, got %d", dst.Options["debug"])
|
|
}
|
|
if dst.Options["trace"] != 1 {
|
|
t.Errorf("Expected Options.trace 1, got %d", dst.Options["trace"])
|
|
}
|
|
if dst.Options["new"] != 100 {
|
|
t.Errorf("Expected Options.new 100, got %d", dst.Options["new"])
|
|
}
|
|
}
|
|
|
|
func TestMapToMapMergeComplex(t *testing.T) {
|
|
dst := map[string]MainConfig{
|
|
"c1": {
|
|
Name: "Config1",
|
|
Sub: SubConfig{Level: 10},
|
|
},
|
|
}
|
|
|
|
src := map[string]any{
|
|
"c1": map[string]any{
|
|
"Sub": map[string]any{
|
|
"Tag": "updated",
|
|
},
|
|
},
|
|
"c2": map[string]any{
|
|
"Name": "Config2",
|
|
},
|
|
}
|
|
|
|
cast.Convert(&dst, src)
|
|
|
|
if dst["c1"].Name != "Config1" {
|
|
t.Errorf("Expected c1.Name Config1, got %s", dst["c1"].Name)
|
|
}
|
|
if dst["c1"].Sub.Level != 10 {
|
|
t.Errorf("Expected c1.Sub.Level 10, got %d", dst["c1"].Sub.Level)
|
|
}
|
|
if dst["c1"].Sub.Tag != "updated" {
|
|
t.Errorf("Expected c1.Sub.Tag updated, got %s", dst["c1"].Sub.Tag)
|
|
}
|
|
if dst["c2"].Name != "Config2" {
|
|
t.Errorf("Expected c2.Name Config2, got %s", dst["c2"].Name)
|
|
}
|
|
}
|