-
Notifications
You must be signed in to change notification settings - Fork 14
/
pack_test.go
92 lines (86 loc) · 2.41 KB
/
pack_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
package sproto
import (
"bytes"
"testing"
)
type PackTestCase struct {
Name string
Unpacked []byte
Origin []byte
Packed []byte
}
var packTestCases []*PackTestCase = []*PackTestCase{
{
Name: "SimplePack",
Origin: []byte{0x08, 0x00, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, 0x19, 0x00, 0x00, 0x00, 0xaa, 0x01, 0x00, 0x00},
Packed: []byte{0x51, 0x08, 0x03, 0x02, 0x31, 0x19, 0xaa, 0x01},
Unpacked: []byte{0x08, 0x00, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, 0x19, 0x00, 0x00, 0x00, 0xaa, 0x01, 0x00, 0x00},
},
{
Name: "FFPack",
Origin: bytes.Join([][]byte{
bytes.Repeat([]byte{0x8a}, 30),
{0x00, 0x00},
}, nil),
Packed: bytes.Join([][]byte{
{0xff, 0x03},
bytes.Repeat([]byte{0x8a}, 30),
{0x00, 0x00},
}, nil),
Unpacked: bytes.Join([][]byte{
bytes.Repeat([]byte{0x8a}, 30),
{0x00, 0x00},
}, nil),
},
{
Name: "FFPack2",
Origin: []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E},
Packed: []byte{0xFF, 0x01, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x00, 0x00},
Unpacked: []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x00, 0x00},
},
}
func TestPack(t *testing.T) {
for _, tc := range packTestCases {
packed := Pack(tc.Origin)
if !bytes.Equal(packed, tc.Packed) {
t.Log("packed:", packed)
t.Log("expected:", tc.Packed)
t.Fatalf("test case *%s* failed", tc.Name)
}
}
}
func TestUnpack(t *testing.T) {
var allUnpacked, allPacked []byte
for _, tc := range packTestCases {
unpacked, err := Unpack(tc.Packed)
if err != nil {
t.Fatalf("test case *%s* failed with error:%s", tc.Name, err)
}
if !bytes.Equal(unpacked, tc.Unpacked) {
t.Log("unpacked:", unpacked)
t.Log("expected:", tc.Unpacked)
t.Fatalf("test case *%s* failed", tc.Name)
}
allUnpacked = Append(allUnpacked, tc.Unpacked)
allPacked = Append(allPacked, tc.Packed)
}
unpacked, err := Unpack(allPacked)
if err != nil {
t.Fatalf("test case *total* failed with error:%s", err)
}
if !bytes.Equal(unpacked, allUnpacked) {
t.Log("unpacked:", unpacked)
t.Log("expected:", allUnpacked)
t.Fatal("test case *total* failed")
}
}
func TestPackUnpack(t *testing.T) {
for n := 1; n < 2500; n++ {
origin := bytes.Repeat([]byte{0x61}, n)
packed := Pack(origin)
_, err := Unpack(packed)
if err != nil {
t.Fatalf("unpack failed for length: %d", n)
}
}
}