76 lines
1.7 KiB
Go
76 lines
1.7 KiB
Go
|
|
package cast_test
|
||
|
|
|
||
|
|
import (
|
||
|
|
"math"
|
||
|
|
"testing"
|
||
|
|
|
||
|
|
"apigo.cc/go/cast"
|
||
|
|
)
|
||
|
|
|
||
|
|
// --- 黑盒测试 (Black-box / Edge Cases) ---
|
||
|
|
|
||
|
|
func TestEdgeCases(t *testing.T) {
|
||
|
|
// 1. 极端数值
|
||
|
|
if cast.Int64(math.MaxInt64) != math.MaxInt64 { t.Error("MaxInt64 failed") }
|
||
|
|
if cast.Float64("1.7976931348623157e+308") == 0 { t.Error("MaxFloat64 string failed") }
|
||
|
|
|
||
|
|
// 2. 各种非法格式字符串
|
||
|
|
if cast.Int("abc") != 0 { t.Error("Invalid string to int should be 0") }
|
||
|
|
if cast.Float("1.2.3.4") != 0 { t.Error("Invalid float string should be 0") }
|
||
|
|
if cast.Bool("not_a_bool") != false { t.Error("Invalid bool string should be false") }
|
||
|
|
|
||
|
|
// 3. 深度嵌套与空指针
|
||
|
|
var p ***int
|
||
|
|
if cast.Int(p) != 0 { t.Error("Deep nil pointer to int failed") }
|
||
|
|
|
||
|
|
// 4. JSON 异常输入
|
||
|
|
if cast.UnJson("{invalid_json}", nil) == nil { t.Log("UnJson handled invalid input") }
|
||
|
|
}
|
||
|
|
|
||
|
|
// --- 性能测试 (Performance / Benchmarks) ---
|
||
|
|
|
||
|
|
func BenchmarkInt(b *testing.B) {
|
||
|
|
val := "123456"
|
||
|
|
for i := 0; i < b.N; i++ {
|
||
|
|
_ = cast.Int(val)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func BenchmarkIntFromInterface(b *testing.B) {
|
||
|
|
var val interface{} = 123456
|
||
|
|
for i := 0; i < b.N; i++ {
|
||
|
|
_ = cast.Int(val)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func BenchmarkString(b *testing.B) {
|
||
|
|
val := 123456.789
|
||
|
|
for i := 0; i < b.N; i++ {
|
||
|
|
_ = cast.String(val)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func BenchmarkJson(b *testing.B) {
|
||
|
|
type User struct {
|
||
|
|
ID int `json:"id"`
|
||
|
|
Name string `json:"name"`
|
||
|
|
}
|
||
|
|
u := User{ID: 1, Name: "Benchmark User"}
|
||
|
|
for i := 0; i < b.N; i++ {
|
||
|
|
_ = cast.Json(u)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func BenchmarkIf(b *testing.B) {
|
||
|
|
for i := 0; i < b.N; i++ {
|
||
|
|
_ = cast.If(i%2 == 0, "A", "B")
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func BenchmarkSplitTrim(b *testing.B) {
|
||
|
|
s := " a, b, c, d, e, f, g "
|
||
|
|
for i := 0; i < b.N; i++ {
|
||
|
|
_ = cast.SplitTrim(s, ",")
|
||
|
|
}
|
||
|
|
}
|