cast/conversion_test.go

85 lines
1.8 KiB
Go
Raw Normal View History

2026-05-04 09:22:34 +08:00
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)
2026-05-04 09:22:34 +08:00
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}))
2026-05-04 09:22:34 +08:00
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)
2026-05-04 09:22:34 +08:00
var s1 []int
cast.FillSlice(&s1, "123")
2026-05-04 09:22:34 +08:00
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)
2026-05-04 09:22:34 +08:00
}
}
func TestJSON(t *testing.T) {
2026-05-04 09:22:34 +08:00
type Config struct {
2026-05-09 16:30:01 +08:00
Port int
2026-05-04 09:22:34 +08:00
}
data := `{"port": 8080}`
2026-05-09 16:30:01 +08:00
2026-05-04 09:22:34 +08:00
// 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)
2026-05-04 09:22:34 +08:00
}
// Test To[T] from JSON
c3 := cast.To[Config](data)
2026-05-04 09:22:34 +08:00
if c3.Port != 8080 {
t.Errorf("To[Config] failed: %v", c3)
2026-05-04 09:22:34 +08:00
}
}
func TestGenericToSlice(t *testing.T) {
// Test To with various inputs
s1 := cast.To[[]int]("123")
2026-05-04 09:22:34 +08:00
if len(s1) != 1 || s1[0] != 123 {
t.Errorf("To[[]int] primitive failed: %v", s1)
2026-05-04 09:22:34 +08:00
}
s2 := cast.To[[]string]([]int{1, 2})
2026-05-04 09:22:34 +08:00
if len(s2) != 2 || s2[0] != "1" || s2[1] != "2" {
t.Errorf("To[[]string] slice failed: %v", s2)
2026-05-04 09:22:34 +08:00
}
}