-
Notifications
You must be signed in to change notification settings - Fork 1
/
net_test.go
87 lines (74 loc) · 1.44 KB
/
net_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
package main
import (
"net"
"testing"
"time"
)
const expected = 1024
func listen(t *testing.T, addr string, fn func(net.Conn)) {
ln, err := net.Listen("tcp", addr)
if err != nil {
t.Fatal(err)
}
go func() {
conn, _ := ln.Accept()
fn(conn)
conn.Close()
}()
}
func TestDownload(t *testing.T) {
addr := ":1616"
listen(t, addr, func(conn net.Conn) {
for {
conn.Write([]byte(sampleData))
}
})
conn, err := net.Dial("tcp", addr)
if err != nil {
t.Fatal(err)
}
bytes, err := download(conn, time.Millisecond)
if err != nil {
t.Fatal(err)
} else if bytes < expected {
t.Fatalf("too few bytes read: got %d want %d", bytes, expected)
}
}
func TestUpload(t *testing.T) {
addr := ":1617"
listen(t, addr, func(conn net.Conn) {
data := make([]byte, 1024)
for {
conn.Read(data)
}
})
conn, err := net.Dial("tcp", addr)
if err != nil {
t.Fatal(err)
}
bytes, err := upload(conn, time.Millisecond)
if err != nil {
t.Fatal(err)
} else if bytes < expected {
t.Fatalf("too few bytes written: got %d want %d", bytes, expected)
}
}
func TestEcho(t *testing.T) {
addr := ":1618"
msg := "echo\r\n"
listen(t, addr, func(conn net.Conn) {
resp := make([]byte, 6)
for {
conn.Write([]byte(msg))
conn.Read(resp)
if string(resp) != msg {
t.Fatalf("invalid echo: got %v want %v", resp, []byte(msg))
}
}
})
conn, err := net.Dial("tcp", addr)
if err != nil {
t.Fatal(err)
}
echo(conn, time.Millisecond)
}