package cast_test import ( "testing" "apigo.cc/go/cast" ) func TestTo(t *testing.T) { // Basic types if v := cast.To[int]("123"); v != 123 { t.Errorf("To[int] failed: %v", v) } if v := cast.To[int]("abc"); v != 0 { t.Errorf("To[int] for invalid input should be 0, got %v", v) } // Slice s := cast.To[[]int]([]string{"1", "2", "3"}) if len(s) != 3 || s[0] != 1 || s[1] != 2 || s[2] != 3 { t.Errorf("To[[]int] failed: %v", s) } // Map m := cast.To[map[string]int](map[string]string{"a": "1", "b": "2"}) if len(m) != 2 || m["a"] != 1 || m["b"] != 2 { t.Errorf("To[map[string]int] failed: %v", m) } // JSON Auto conversion (Struct to String) type User struct { Name string } u := User{Name: "Alice"} js := cast.To[string](u) if js != `{"name":"Alice"}` { t.Errorf("To[string] for struct failed: %v", js) } // JSON Auto conversion (String to Struct) u2 := cast.To[User](`{"name":"Bob"}`) if u2.Name != "Bob" { t.Errorf("To[User] from string failed: %v", u2) } } func TestAsWrapper(t *testing.T) { // As if v := cast.As(123, nil); v != 123 { t.Errorf("As failed: %v", v) } } func TestMapSliceAPIs(t *testing.T) { // ToMap m := cast.As(cast.ToMap[string, int]([]any{"a", "1", "b", 2})) if m["a"] != 1 || m["b"] != 2 { t.Errorf("ToMap failed: %v", m) } // ToSlice s := cast.As(cast.ToSlice[int]([]string{"10", "20"})) if len(s) != 2 || s[0] != 10 || s[1] != 20 { t.Errorf("ToSlice failed: %v", s) } }