-
Notifications
You must be signed in to change notification settings - Fork 311
/
Copy pathheader_test.go
107 lines (87 loc) · 1.7 KB
/
header_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
package websocket
import (
"bytes"
"math/rand"
"strconv"
"testing"
"time"
"github.com/google/go-cmp/cmp"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func randBool() bool {
return rand.Intn(1) == 0
}
func TestHeader(t *testing.T) {
t.Parallel()
t.Run("readNegativeLength", func(t *testing.T) {
t.Parallel()
b := marshalHeader(header{
payloadLength: 1<<16 + 1,
})
// Make length negative
b[2] |= 1 << 7
r := bytes.NewReader(b)
_, err := readHeader(r)
if err == nil {
t.Fatalf("unexpected error value: %+v", err)
}
})
t.Run("lengths", func(t *testing.T) {
t.Parallel()
lengths := []int{
124,
125,
126,
4096,
16384,
65535,
65536,
65537,
131072,
}
for _, n := range lengths {
n := n
t.Run(strconv.Itoa(n), func(t *testing.T) {
t.Parallel()
testHeader(t, header{
payloadLength: int64(n),
})
})
}
})
t.Run("fuzz", func(t *testing.T) {
t.Parallel()
for i := 0; i < 10000; i++ {
h := header{
fin: randBool(),
rsv1: randBool(),
rsv2: randBool(),
rsv3: randBool(),
opcode: opcode(rand.Intn(1 << 4)),
masked: randBool(),
payloadLength: rand.Int63(),
}
if h.masked {
rand.Read(h.maskKey[:])
}
testHeader(t, h)
}
})
}
func testHeader(t *testing.T, h header) {
b := marshalHeader(h)
r := bytes.NewReader(b)
h2, err := readHeader(r)
if err != nil {
t.Logf("header: %#v", h)
t.Logf("bytes: %b", b)
t.Fatalf("failed to read header: %v", err)
}
if !cmp.Equal(h, h2, cmp.AllowUnexported(header{})) {
t.Logf("header: %#v", h)
t.Logf("bytes: %b", b)
t.Fatalf("parsed and read header differ: %v", cmp.Diff(h, h2, cmp.AllowUnexported(header{})))
}
}