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[map[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 (append)
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 append slice
cast.FillSlice(&s1, []string{"456"})
2026-05-04 09:22:34 +08:00
if len(s1) != 2 || s1[1] != 456 {
t.Errorf("Append slice to slice failed: %v", s1)
}
}
func TestJSON(t *testing.T) {
2026-05-04 09:22:34 +08:00
type Config struct {
Port int `json:"port"`
2026-05-04 09:22:34 +08:00
}
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, err := cast.FromJSON[Config]([]byte(data))
if err != nil || c2.Port != 8080 {
t.Errorf("FromJSON failed: %v, %v", err, c2)
}
// Test As[T] from JSON
c3 := cast.As[Config](data)
2026-05-04 09:22:34 +08:00
if c3.Port != 8080 {
t.Errorf("As[Config] failed: %v", c3)
2026-05-04 09:22:34 +08:00
}
}
func TestGenericAsSlice(t *testing.T) {
// Test As with various inputs
s1 := cast.As[[]int]("123")
2026-05-04 09:22:34 +08:00
if len(s1) != 1 || s1[0] != 123 {
t.Errorf("As[[]int] primitive failed: %v", s1)
2026-05-04 09:22:34 +08:00
}
s2 := cast.As[[]string]([]int{1, 2})
2026-05-04 09:22:34 +08:00
if len(s2) != 2 || s2[0] != "1" || s2[1] != "2" {
t.Errorf("As[[]string] slice failed: %v", s2)
2026-05-04 09:22:34 +08:00
}
}