-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoder_test.go
115 lines (100 loc) · 2.23 KB
/
encoder_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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package bx
import (
"math/rand"
"strings"
"testing"
"time"
"github.com/matryer/is"
)
type Dummy struct {
Name string
Value int32
}
func (d *Dummy) Encode() ([]byte, error) {
return Encoder().String(d.Name).Int32(d.Value).Encode()
}
func (d *Dummy) Decode(_data []byte) (int, error) {
startLen := len(_data)
dec := Decoder(_data)
var err error
d.Name, err = dec.String()
if err != nil {
return 0, err
}
d.Value, err = dec.Int32()
if err != nil {
return 0, err
}
return startLen - dec.Size(), nil
}
func TestEncoder(t *testing.T) {
is := is.New(t)
valInt := int32(13)
valUint64 := uint64(rand.Int63()) // #nosec
valStr := "my text"
raw, err := Encoder().Int32(valInt).String(valStr).Uint64(valUint64).Encode()
is.NoErr(err)
is.Equal(len(raw), 4+8+len(valStr)+8)
}
func TestEncodeStrings(t *testing.T) {
is := is.New(t)
testVals := []string{"val1", "val2", "val3"}
size := len(strings.Join(testVals, ""))
raw, err := Encoder().Strings(testVals).Encode()
is.NoErr(err)
is.Equal(len(raw), 4*8+size)
}
func TestEncodeFloa32(t *testing.T) {
is := is.New(t)
testVal := float32(1.56)
raw, err := Encoder().Float32(testVal).Encode()
is.NoErr(err)
is.Equal(4, len(raw))
}
func TestEncodeFloa64(t *testing.T) {
is := is.New(t)
testVal := float64(1.56)
raw, err := Encoder().Float64(testVal).Encode()
is.NoErr(err)
is.Equal(8, len(raw))
}
func TestEncodeTime(t *testing.T) {
is := is.New(t)
testVal := time.Date(2020, 03, 01, 12, 00, 45, 0, time.UTC)
raw, err := Encoder().Time(testVal).Encode()
is.NoErr(err)
is.Equal(8, len(raw))
}
func TestEncodeDecodeValueTypeSlice(t *testing.T) {
is := is.New(t)
testData := []Dummy{
{
Name: "test1",
Value: 1,
},
{
Name: "test2",
Value: 2,
},
{
Name: "test3",
Value: 3,
},
}
testDataVt := make([]ValueType, 0, len(testData))
for _, td := range testData {
ltd := td
testDataVt = append(testDataVt, <d)
}
raw, err := Encoder().WriteSlice(testDataVt).Encode()
is.NoErr(err)
dec := Decoder(raw)
result := []Dummy{}
err = dec.ReadSlice(func() ValueType { return &Dummy{} }, func(valueType ValueType) error {
result = append(result, *valueType.(*Dummy))
return nil
})
is.NoErr(err)
is.Equal(3, len(result))
is.Equal(testData, result)
}