package nmath_test import ( "encoding/json" "git.noahlan.cn/noahlan/ntool/nmath" "git.noahlan.cn/noahlan/ntool/ntest/assert" "testing" "time" ) func TestToInt(t *testing.T) { is := assert.New(t) tests := []any{ 2, int8(2), int16(2), int32(2), int64(2), uint(2), uint8(2), uint16(2), uint32(2), uint64(2), float32(2.2), 2.3, "2", time.Duration(2), json.Number("2"), } errTests := []any{ nil, "2a", []int{1}, } // To int intVal, err := nmath.Int("2") is.Nil(err) is.Eq(2, intVal) intVal, err = nmath.ToInt("-2") is.Nil(err) is.Eq(-2, intVal) is.Eq(2, nmath.StrInt("2")) intVal, err = nmath.IntOrErr("-2") is.Nil(err) is.Eq(-2, intVal) is.Eq(-2, nmath.MustInt("-2")) for _, in := range tests { is.Eq(2, nmath.MustInt(in)) is.Eq(2, nmath.QuietInt(in)) } for _, in := range errTests { is.Eq(0, nmath.MustInt(in)) } // To uint uintVal, err := nmath.Uint("2") is.Nil(err) is.Eq(uint64(2), uintVal) uintVal, err = nmath.UintOrErr("2") is.Nil(err) is.Eq(uint64(2), uintVal) _, err = nmath.ToUint("-2") is.Err(err) is.Eq(uint64(0), nmath.MustUint("-2")) for _, in := range tests { is.Eq(uint64(2), nmath.MustUint(in)) } for _, in := range errTests { is.Eq(uint64(0), nmath.QuietUint(in)) is.Eq(uint64(0), nmath.MustUint(in)) } // To int64 i64Val, err := nmath.ToInt64("2") is.Nil(err) is.Eq(int64(2), i64Val) i64Val, err = nmath.Int64("-2") is.Nil(err) is.Eq(int64(-2), i64Val) i64Val, err = nmath.Int64OrErr("-2") is.Nil(err) is.Eq(int64(-2), i64Val) for _, in := range tests { is.Eq(int64(2), nmath.MustInt64(in)) } for _, in := range errTests { is.Eq(int64(0), nmath.MustInt64(in)) is.Eq(int64(0), nmath.QuietInt64(in)) is.Eq(int64(0), nmath.SafeInt64(in)) } } func TestToString(t *testing.T) { is := assert.New(t) tests := []any{ 2, int8(2), int16(2), int32(2), int64(2), uint(2), uint8(2), uint16(2), uint32(2), uint64(2), float32(2), float64(2), // "2", time.Duration(2), json.Number("2"), } for _, in := range tests { is.Eq("2", nmath.String(in)) is.Eq("2", nmath.QuietString(in)) is.Eq("2", nmath.MustString(in)) val, err := nmath.ToString(in) is.NoErr(err) is.Eq("2", val) } val, err := nmath.StringOrErr(2) is.NoErr(err) is.Eq("2", val) val, err = nmath.ToString(nil) is.NoErr(err) is.Eq("", val) is.Panics(func() { nmath.MustString("2") }) } func TestToFloat(t *testing.T) { is := assert.New(t) tests := []any{ 2, int8(2), int16(2), int32(2), int64(2), uint(2), uint8(2), uint16(2), uint32(2), uint64(2), float32(2), float64(2), "2", time.Duration(2), json.Number("2"), } for _, in := range tests { is.Eq(float64(2), nmath.MustFloat(in)) } is.Eq(123.5, nmath.MustFloat("123.5")) is.Eq(123.5, nmath.QuietFloat("123.5")) is.Panics(func() { nmath.MustFloat("invalid") }, "ok") is.Eq(float64(0), nmath.QuietFloat("invalid")) fltVal, err := nmath.ToFloat("123.5") is.Nil(err) is.Eq(123.5, fltVal) fltVal, err = nmath.Float("-123.5") is.Nil(err) is.Eq(-123.5, fltVal) fltVal, err = nmath.FloatOrErr("-123.5") is.Nil(err) is.Eq(-123.5, fltVal) }