-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpacket_test.go
78 lines (75 loc) · 2.18 KB
/
packet_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
package rcon
import (
"bytes"
"fmt"
"testing"
)
func TestPacket_WriteTo(t *testing.T) {
testCases := []struct {
name string
expectedError error
expectedData []byte
packet *Packet
}{
{
name: "auth request",
expectedError: nil,
expectedData: []byte("\x12\x00\x00\x00\x01\x00\x00\x00\x03\x00\x00\x00password\x00\x00"),
packet: &Packet{ID: 1, Type: AuthRequest, Body: []byte("password")},
},
}
for i := range testCases {
tc := testCases[i]
t.Run(tc.name, func(t *testing.T) {
buffer := bytes.NewBuffer(nil)
n, err := tc.packet.WriteTo(buffer)
if fmt.Sprint(err) != fmt.Sprint(tc.expectedError) {
t.Errorf("expected error: %s; got: %s", tc.expectedError, err)
}
if n != int64(len(tc.expectedData)) {
t.Errorf("expected length: %d; got: %d", len(tc.expectedData), n)
}
if !bytes.Equal(buffer.Bytes(), tc.expectedData) {
t.Errorf("expected data: %q; got: %q", tc.expectedData, buffer.Bytes())
}
})
}
}
func TestPacket_ReadFrom(t *testing.T) {
testCases := []struct {
name string
expectedError error
expectedPacket *Packet
data []byte
}{
{
name: "auth request",
expectedError: nil,
expectedPacket: &Packet{ID: 1, Type: AuthRequest, Body: []byte("password")},
data: []byte("\x12\x00\x00\x00\x01\x00\x00\x00\x03\x00\x00\x00password\x00\x00"),
},
}
for i := range testCases {
tc := testCases[i]
t.Run(tc.name, func(t *testing.T) {
buffer := bytes.NewBuffer(tc.data)
packet := &Packet{}
n, err := packet.ReadFrom(buffer)
if fmt.Sprint(err) != fmt.Sprint(tc.expectedError) {
t.Errorf("expected error: %s; got: %s", tc.expectedError, err)
}
if n != int64(len(tc.data)) {
t.Errorf("expected length: %d; got: %d", len(tc.data), n)
}
if packet.Type != tc.expectedPacket.Type {
t.Errorf("expected type: %d; got: %d", tc.expectedPacket.Type, packet.Type)
}
if packet.ID != tc.expectedPacket.ID {
t.Errorf("expected id: %d; got: %d", tc.expectedPacket.ID, packet.ID)
}
if !bytes.Equal(packet.Body, tc.expectedPacket.Body) {
t.Errorf("expected body: %q; got: %q", tc.expectedPacket.Body, packet.Body)
}
})
}
}