2026-05-02 23:00:44 +08:00
|
|
|
package cast_test
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"testing"
|
|
|
|
|
"apigo.cc/go/cast"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func TestFastUnmarshal_Frictionless(t *testing.T) {
|
|
|
|
|
type User struct {
|
|
|
|
|
UserID int
|
|
|
|
|
UserName string
|
|
|
|
|
IsAdmin bool
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 测试各种 Key 格式的匹配
|
|
|
|
|
data := `{"user_id": 1001, "UserName": "Tom", "isadmin": "true"}`
|
|
|
|
|
var u User
|
2026-05-04 09:22:34 +08:00
|
|
|
err := cast.UnmarshalJSON(data, &u)
|
2026-05-02 23:00:44 +08:00
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("UnmarshalJSON failed: %v", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if u.UserID != 1001 || u.UserName != "Tom" || u.IsAdmin != true {
|
|
|
|
|
t.Errorf("Frictionless unmarshal failed: %+v", u)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestFastUnmarshal_Nested(t *testing.T) {
|
|
|
|
|
type Role struct {
|
|
|
|
|
Name string
|
|
|
|
|
}
|
|
|
|
|
type User struct {
|
|
|
|
|
Name string
|
|
|
|
|
Role *Role
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
data := `{"name": "Tom", "role": {"name": "Admin"}}`
|
|
|
|
|
var u User
|
|
|
|
|
cast.UnmarshalJSON(data, &u)
|
|
|
|
|
|
|
|
|
|
if u.Name != "Tom" || u.Role == nil || u.Role.Name != "Admin" {
|
|
|
|
|
t.Errorf("Nested unmarshal failed: %+v", u)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestFastUnmarshal_Slice(t *testing.T) {
|
|
|
|
|
data := `[1, "2", 3.0]`
|
|
|
|
|
var res []int
|
|
|
|
|
cast.UnmarshalJSON(data, &res)
|
|
|
|
|
|
|
|
|
|
if len(res) != 3 || res[1] != 2 {
|
|
|
|
|
t.Errorf("Slice unmarshal failed: %v", res)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestFastUnmarshal_Map(t *testing.T) {
|
|
|
|
|
data := `{"a": 1, "b": "2"}`
|
|
|
|
|
var res map[string]int
|
|
|
|
|
cast.UnmarshalJSON(data, &res)
|
|
|
|
|
|
|
|
|
|
if res["a"] != 1 || res["b"] != 2 {
|
|
|
|
|
t.Errorf("Map unmarshal failed: %v", res)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestFastUnmarshal_ComplexString(t *testing.T) {
|
|
|
|
|
// 测试包含转义和特殊字符的字符串
|
|
|
|
|
data := `{"text": "line1\nline2\t\"quoted\""}`
|
|
|
|
|
var res struct{ Text string }
|
|
|
|
|
cast.UnmarshalJSON(data, &res)
|
|
|
|
|
|
|
|
|
|
expected := "line1\nline2\t\"quoted\""
|
|
|
|
|
if res.Text != expected {
|
|
|
|
|
t.Errorf("Complex string unmarshal failed.\nExpected: %s\nActual: %s", expected, res.Text)
|
|
|
|
|
}
|
|
|
|
|
}
|