/
server_test.go
101 lines (93 loc) · 2.3 KB
/
server_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
package rgo
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"testing"
)
func startTestServer(t *testing.T) *server {
s, err := newServer()
if err != nil {
t.Errorf("failed to start server: %v", err)
}
return s
}
func TestServerShutdown(t *testing.T) {
s := startTestServer(t)
err := s.s.Stop()
if err != nil {
t.Errorf("error after stopping server: %v", err)
}
}
func TestServerData(t *testing.T) {
s := startTestServer(t)
s.putData("hello", []byte("world"))
resp, err := http.Get(fmt.Sprintf("http://localhost:%d/hello", s.port))
if err != nil {
t.Errorf("failed to get 'hello': %v", err)
}
b, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
t.Errorf("error while reading data: %v", err)
}
if string(b) != "world" {
t.Errorf("expected %q, got %q", "world", b)
}
s.rmData("hello")
resp, err = http.Get(fmt.Sprintf("http://localhost:%d/hello", s.port))
if err != nil {
t.Errorf("unexpected error requesting 'hello': %v", err)
}
if resp.StatusCode == http.StatusOK {
t.Errorf("expected non-OK status after removing 'hello'")
}
s.s.Stop()
}
func TestServerFwd(t *testing.T) {
data := "this #@ THE_data"
s := startTestServer(t)
rch := make(chan readerDone)
s.putFwd("abc.xyz", rch)
done := make(chan struct{})
go func() {
rd := <-rch
b, err := ioutil.ReadAll(rd.r)
close(rd.done)
if err != nil {
t.Errorf("error while reading body: %v", err)
}
if string(b) != data {
t.Errorf("expected %q, got %q", data, b)
}
close(done)
}()
var client http.Client
var url = fmt.Sprintf("http://localhost:%d/abc.xyz", s.port)
req, err := http.NewRequest("PUT", url, bytes.NewBufferString(data))
if err != nil {
t.Errorf("unexpected error building request: %v", err)
}
resp, err := client.Do(req)
if err != nil {
t.Errorf("unexpected error PUT-ing data: %v", err)
}
if resp.StatusCode != http.StatusOK {
t.Errorf("unexpected status PUT-ing data: %v", resp.Status)
}
<-done
s.rmFwd("abc.xyz")
req, err = http.NewRequest("PUT", url, bytes.NewBufferString(data))
if err != nil {
t.Errorf("unexpected error building request: %v", err)
}
resp, err = client.Do(req)
if err != nil {
t.Errorf("unexpected error PUT-ing data: %v", err)
}
if resp.StatusCode == http.StatusOK {
t.Errorf("unexpected status PUT-ing data: %v", resp.Status)
}
s.s.Stop()
}