package cast_test import ( "testing" "apigo.cc/go/cast" ) func TestToMap(t *testing.T) { // Test struct-to-map with inheritance type Base struct { ID int } type User struct { Base Name string } u := User{Base: Base{ID: 1}, Name: "Tom"} m1 := make(map[string]any) cast.FillMap(m1, u) if m1["ID"] != 1 || m1["name"] != "Tom" { t.Errorf("Struct inheritance to map failed: %v", m1) } // Test slice-to-map (KV) m2 := cast.As(cast.ToMap[int, string]([]any{"1", "a", 2, 200})) if m2[1] != "a" || m2[2] != "200" { t.Errorf("Slice-to-map failed: %v", m2) } } func TestToSlice(t *testing.T) { // Test primitive-to-slice (overwrite) var s1 []int cast.FillSlice(&s1, "123") if len(s1) != 1 || s1[0] != 123 { t.Errorf("Primitive-to-slice failed: %v", s1) } // Test slice-to-slice (overwrite) cast.FillSlice(&s1, []string{"456"}) if len(s1) != 1 || s1[0] != 456 { t.Errorf("Slice-to-slice overwrite failed: %v", s1) } } func TestJSON(t *testing.T) { type Config struct { Port int } data := `{"port": 8080}` // Test UnmarshalJSON var c1 Config err := cast.UnmarshalJSON(data, &c1) if err != nil || c1.Port != 8080 { t.Errorf("UnmarshalJSON failed: %v, %v", err, c1) } // Test FromJSON c2 := cast.As(cast.FromJSON[Config]([]byte(data))) if c2.Port != 8080 { t.Errorf("FromJSON failed: %v", c2) } // Test To[T] from JSON c3 := cast.To[Config](data) if c3.Port != 8080 { t.Errorf("To[Config] failed: %v", c3) } } func TestGenericToSlice(t *testing.T) { // Test To with various inputs s1 := cast.To[[]int]("123") if len(s1) != 1 || s1[0] != 123 { t.Errorf("To[[]int] primitive failed: %v", s1) } s2 := cast.To[[]string]([]int{1, 2}) if len(s2) != 2 || s2[0] != "1" || s2[1] != "2" { t.Errorf("To[[]string] slice failed: %v", s2) } }