package cast_test import ( "strings" "testing" "apigo.cc/go/cast" ) func TestGenerics(t *testing.T) { // Test If if cast.If(true, 1, 2) != 1 { t.Error("If int failed") } if cast.If(false, "A", "B") != "B" { t.Error("If string failed") } // Test In if !cast.In([]int{1, 2, 3}, 2) { t.Error("In int failed") } if cast.In([]string{"A", "B"}, "C") { t.Error("In string negative failed") } // Test Switch if cast.Switch(1, "A", "B", "C") != "B" { t.Error("Switch failed") } if cast.Switch(5, 1, 2) != 0 { t.Error("Switch out of range failed") } } func TestSpecialJson(t *testing.T) { // 关键测试:特殊 HTML 字符序列化不应被转义 type Content struct { Text string `json:"text"` } c := Content{Text: " & "} // 标准 json.Marshal 会变成 " \u0026 " // 我们期望输出原始字符 " & " js := cast.Json(c) expected := `{"text":" & "}` if js != expected { t.Errorf("Special JSON failed.\nExpected: %s\nActual: %s", expected, js) } // 漂亮打印测试 jsP := cast.JsonP(c) if !strings.Contains(jsP, "&") || !strings.Contains(jsP, "\n") { t.Error("JsonP special content failed") } } func TestComplexJsonType(t *testing.T) { // 测试 map[interface{}]interface{} 这种标准库无法处理的类型 data := map[interface{}]interface{}{ "name": "Tom", 123: "numeric key", "sub": map[interface{}]interface{}{ "ok": true, }, } js := cast.Json(data) // 期望 123 被转为 "123" 且内容正确 if !strings.Contains(js, `"123":"numeric key"`) || !strings.Contains(js, `"ok":true`) { t.Errorf("Complex JSON type failed: %s", js) } } func TestPointerHelpers(t *testing.T) { s := "hello" if *cast.StringPtr(s) != s { t.Error("StringPtr failed") } i := 100 if *cast.IntPtr(i) != i { t.Error("IntPtr failed") } if *cast.BoolPtr(true) != true || *cast.BoolPtr(false) != false { t.Error("BoolPtr failed") } } func TestNameConversions(t *testing.T) { if cast.GetLowerName("UserName") != "userName" { t.Error("GetLowerName failed") } if cast.GetUpperName("userName") != "UserName" { t.Error("GetUpperName failed") } } func TestEmptyValues(t *testing.T) { if cast.Int(nil) != 0 { t.Error("Int(nil) failed") } if cast.String(nil) != "" { t.Error("String(nil) failed") } if cast.Bool(nil) != false { t.Error("Bool(nil) failed") } }