/
httpc_test.go
112 lines (102 loc) · 2.16 KB
/
httpc_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
package httpc
import (
"bytes"
"http"
"io"
"io/ioutil"
"net"
"testing"
)
type HandlerString string
func (s HandlerString) ServeHTTP(c *http.Conn, r *http.Request) {
io.WriteString(c, string(s))
}
func echo(c *http.Conn, r *http.Request) {
c.SetHeader("Content-Type", r.Header["Content-Type"])
io.Copy(c, r.Body)
}
const port = "12345"
func init() {
http.Handle("/", HandlerString("hello"))
http.HandleFunc("/echo", echo)
go func() {
l, e := net.Listen("tcp", ":"+port)
if e != nil {
panic(e)
}
e = http.Serve(l, nil)
l.Close()
panic(e)
}()
}
func TestGet(t *testing.T) {
c := NewClient(10, 10)
if c == nil {
t.Fatal("nil conn")
}
resp, err := Get(c, "http://localhost:"+port+"/")
if err != nil {
t.Error("unexpedted err", err)
}
if resp == nil {
t.Fatal("nil resp")
}
s, err := ioutil.ReadAll(resp[0].Body)
if err != nil {
t.Error("unexpedted err", err)
}
if string(s) != "hello" {
t.Errorf("expected hello, got %q\n", s)
}
//resp.Body.Close()
}
func TestPost(t *testing.T) {
ctype, exp := "text/plain", "abc"
c := NewClient(10, 10)
if c == nil {
t.Fatal("nil conn")
}
resp, err := Post(c, "http://localhost:"+port+"/echo", ctype, bytes.NewBufferString(exp))
if err != nil {
t.Error("unexpedted err", err)
}
if resp == nil {
t.Fatal("nil resp")
}
if s := resp.GetHeader("Content-Type"); s != ctype {
t.Errorf("wrong content type %q", s)
}
got, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Error("unexpedted err", err)
}
if string(got) != exp {
t.Errorf("expected %q, got %q\n", exp, got)
}
//resp.Body.Close()
}
func TestPut(t *testing.T) {
ctype, exp := "text/plain", "abc"
c := NewClient(10, 10)
if c == nil {
t.Fatal("nil conn")
}
resp, err := Put(c, "http://localhost:"+port+"/echo", ctype, bytes.NewBufferString(exp))
if err != nil {
t.Error("unexpedted err", err)
}
if resp == nil {
t.Fatal("nil resp")
}
if s := resp.GetHeader("Content-Type"); s != ctype {
t.Errorf("wrong content type %q", s)
}
got, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Error("unexpedted err", err)
}
if string(got) != exp {
t.Errorf("expected %q, got %q\n", exp, got)
}
//resp.Body.Close()
}