-
Notifications
You must be signed in to change notification settings - Fork 3
/
string_test.go
84 lines (76 loc) · 1.94 KB
/
string_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package gocast
import (
"math/rand"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
var stringTypecastTests = []struct {
value any
target string
}{
{value: 1, target: "1"},
{value: int8(1), target: "1"},
{value: int16(1), target: "1"},
{value: int32(1), target: "1"},
{value: int64(1), target: "1"},
{value: uint(1), target: "1"},
{value: uint8(1), target: "1"},
{value: uint16(1), target: "1"},
{value: uint32(1), target: "1"},
{value: uint64(1), target: "1"},
{value: 1.1, target: "1.1"},
{value: float32(1.5), target: "1.5"},
{value: true, target: "true"},
{value: false, target: "false"},
{value: []byte(`byte`), target: "byte"},
{value: `str`, target: "str"},
{value: nil, target: ""},
}
func TestToStringByReflect(t *testing.T) {
for _, test := range stringTypecastTests {
assert.Equal(t, ReflectToString(reflect.ValueOf(test.value)), test.target)
}
}
func TestToString(t *testing.T) {
for _, test := range stringTypecastTests {
assert.Equal(t, ToString(test.value), test.target)
}
}
func TestIsStr(t *testing.T) {
tests := []struct {
value any
target bool
}{
{value: 1, target: false},
{value: nil, target: false},
{value: int8(1), target: false},
{value: int16(1), target: false},
{value: []byte("notstr"), target: false},
{value: []int8{1, 2, 3, 4, 5}, target: false},
{value: []any{'1', '2', '3'}, target: false},
{value: "str", target: true},
}
for _, test := range tests {
assert.Equal(t, IsStr(test.value), test.target)
}
}
func BenchmarkToStringByReflect(b *testing.B) {
b.ReportAllocs()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
i := rand.Intn(len(stringTypecastTests))
v := reflect.ValueOf(stringTypecastTests[i].value)
_ = ReflectToString(v)
}
})
}
func BenchmarkToString(b *testing.B) {
b.ReportAllocs()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
i := rand.Intn(len(stringTypecastTests))
_ = ToString(stringTypecastTests[i].value)
}
})
}