92 lines
1.9 KiB
Go
92 lines
1.9 KiB
Go
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.ToMap(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.MakeMap[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 (append)
|
|
var s1 []int
|
|
cast.ToSlice(&s1, "123")
|
|
if len(s1) != 1 || s1[0] != 123 {
|
|
t.Errorf("Primitive-to-slice failed: %v", s1)
|
|
}
|
|
|
|
// Test append slice
|
|
cast.ToSlice(&s1, []string{"456"})
|
|
if len(s1) != 2 || s1[1] != 456 {
|
|
t.Errorf("Append slice to slice failed: %v", s1)
|
|
}
|
|
}
|
|
|
|
func TestJSONYAML(t *testing.T) {
|
|
type Config struct {
|
|
Port int `json:"port" yaml:"port"`
|
|
}
|
|
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 MustFromJSON
|
|
c3 := cast.MustFromJSON[Config](data)
|
|
if c3.Port != 8080 {
|
|
t.Errorf("MustFromJSON failed: %v", c3)
|
|
}
|
|
|
|
// YAML
|
|
yData := "port: 9090"
|
|
c4 := cast.MustFromYAML[Config](yData)
|
|
if c4.Port != 9090 {
|
|
t.Errorf("MustFromYAML failed: %v", c4)
|
|
}
|
|
}
|
|
|
|
func TestMakeSlice(t *testing.T) {
|
|
// Test MakeSlice with various inputs
|
|
s1 := cast.MakeSlice[int]("123")
|
|
if len(s1) != 1 || s1[0] != 123 {
|
|
t.Errorf("MakeSlice primitive failed: %v", s1)
|
|
}
|
|
|
|
s2 := cast.MakeSlice[string]([]int{1, 2})
|
|
if len(s2) != 2 || s2[0] != "1" || s2[1] != "2" {
|
|
t.Errorf("MakeSlice slice failed: %v", s2)
|
|
}
|
|
}
|