-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
conn_test.go
113 lines (90 loc) · 2.21 KB
/
conn_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
// Copyright (c) Liam Stanley <[email protected]>. All rights reserved. Use
// of this source code is governed by the MIT license that can be found in
// the LICENSE file.
package girc
import (
"bufio"
"bytes"
"net"
"testing"
"time"
)
func mockBuffers() (in, out *bytes.Buffer, irc *ircConn) {
in = &bytes.Buffer{}
out = &bytes.Buffer{}
irc = &ircConn{
io: bufio.NewReadWriter(bufio.NewReader(in), bufio.NewWriter(out)),
connected: true,
}
return in, out, irc
}
func TestDecode(t *testing.T) {
in, _, c := mockBuffers()
e := mockEvent()
in.Write(e.Bytes())
in.Write(endline)
de := <-c.decode()
if de.err != nil {
t.Fatalf("received error during decode: %s", de.err)
}
if de.event.String() != e.String() {
t.Fatalf("event returned from decode not the same as mock event. want %#v, got %#v", e, de.event)
}
// Test a failure.
in.WriteString("::abcd\r\n")
de = <-c.decode()
if de.err == nil {
t.Fatalf("should have failed to parse decoded event. got: %#v", de.event)
}
}
func TestEncode(t *testing.T) {
_, out, c := mockBuffers()
e := mockEvent()
err := c.encode(e)
if err != nil {
t.Fatalf("received error during encode: %s", err)
}
line, err := out.ReadString(delim)
if err != nil {
t.Fatalf("received error during check for encoded event: %s", err)
}
want := e.String() + "\r\n"
if want != line {
t.Fatalf("encoded line wanted: %q, got: %q", want, line)
}
}
func TestRate(t *testing.T) {
_, _, c := mockBuffers()
c.lastWrite = time.Now()
if delay := c.rate(100); delay > time.Second {
t.Fatal("first instance of rate is > second")
}
for i := 0; i < 500; i++ {
c.rate(200)
}
if delay := c.rate(200); delay > (3 * time.Second) {
t.Fatal("rate delay too high")
}
}
func genMockConn() (client *Client, clientConn, serverConn net.Conn) {
client = New(Config{
Server: "dummy.int",
Port: 6667,
Nick: "test",
User: "test",
Name: "Testing123",
})
conn1, conn2 := net.Pipe()
return client, conn1, conn2
}
func mockReadBuffer(conn net.Conn) {
// Accept all outgoing writes from the client.
b := bufio.NewReader(conn)
for {
conn.SetReadDeadline(time.Now().Add(10 * time.Second))
_, err := b.ReadString(byte('\n'))
if err != nil {
return
}
}
}