github.com/flower-corp/rosedb@v1.1.2-0.20230117132829-21dc4f7b319a/util/str_test.go (about) 1 package util 2 3 import ( 4 "github.com/stretchr/testify/assert" 5 "math" 6 "testing" 7 ) 8 9 func TestStrToFloat64(t *testing.T) { 10 testCases := []struct { 11 name string 12 val string 13 expVal float64 14 expErr bool 15 }{ 16 { 17 name: "valid value", 18 val: "3434.4455664545", 19 expVal: 3434.4455664545, 20 }, 21 { 22 name: "out of range", 23 val: "1.7e+309", // max float64 = 1.7e+308 24 expVal: math.Inf(1), 25 expErr: true, 26 }, 27 { 28 name: "invalid value", 29 val: "invalid", 30 expVal: 0, 31 expErr: true, 32 }, 33 } 34 35 for _, tc := range testCases { 36 t.Run(tc.name, func(t *testing.T) { 37 res, err := StrToFloat64(tc.val) 38 if tc.expErr { 39 assert.NotNil(t, err) 40 } else { 41 assert.Nil(t, err) 42 } 43 assert.Equal(t, tc.expVal, res) 44 }) 45 } 46 } 47 48 func TestFloat64ToStr(t *testing.T) { 49 val := 9902.99355664 50 res := Float64ToStr(val) 51 assert.Equal(t, res, "9902.99355664") 52 } 53 54 func TestStrToInt64(t *testing.T) { 55 testCases := []struct { 56 name string 57 val string 58 expVal int64 59 expErr bool 60 }{ 61 { 62 name: "valid", 63 val: "12345678910", 64 expVal: 12345678910, 65 }, 66 { 67 name: "out of range", 68 val: "9243372036854775909", // Bigger than MaxInt64 69 expVal: math.MaxInt64, 70 expErr: true, 71 }, 72 { 73 name: "invalid", 74 val: "invalid", 75 expVal: 0, 76 expErr: true, 77 }, 78 } 79 80 for _, tc := range testCases { 81 t.Run(tc.name, func(t *testing.T) { 82 res, err := StrToInt64(tc.val) 83 if tc.expErr { 84 assert.NotNil(t, err) 85 } else { 86 assert.Nil(t, err) 87 } 88 assert.Equal(t, tc.expVal, res) 89 }) 90 } 91 } 92 93 func TestStrToUint(t *testing.T) { 94 testCases := []struct { 95 name string 96 val string 97 expVal uint64 98 expErr bool 99 }{ 100 { 101 name: "valid", 102 val: "12345678910", 103 expVal: 12345678910, 104 }, 105 { 106 name: "out of range - exceeds max limit", 107 val: "18446744073709551620", // MaxUint64 = 18446744073709551615 108 expVal: math.MaxUint64, 109 expErr: true, 110 }, 111 { 112 name: "out of range - negative value", 113 val: "-123", 114 expVal: 0, 115 expErr: true, 116 }, 117 { 118 name: "invalid", 119 val: "invalid", 120 expVal: 0, 121 expErr: true, 122 }, 123 } 124 125 for _, tc := range testCases { 126 t.Run(tc.name, func(t *testing.T) { 127 res, err := StrToUint(tc.val) 128 if tc.expErr { 129 assert.NotNil(t, err) 130 } else { 131 assert.Nil(t, err) 132 } 133 assert.Equal(t, tc.expVal, res) 134 }) 135 } 136 }