-
-
Notifications
You must be signed in to change notification settings - Fork 95
/
cmd_test.go
407 lines (377 loc) · 8.67 KB
/
cmd_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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
// Copyright 2014 Martin Angers and Contributors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package fetchbot
import (
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"sort"
"strings"
"sync/atomic"
"testing"
)
type basicAuthCmd struct {
*Cmd
user, pwd string
}
func (ba *basicAuthCmd) BasicAuth() (string, string) {
return ba.user, ba.pwd
}
func TestBasicAuth(t *testing.T) {
creds := base64.StdEncoding.EncodeToString([]byte("me:you"))
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
auth := req.Header.Get("Authorization")
if auth != "Basic "+creds {
w.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
w.Write([]byte("ok"))
}))
defer srv.Close()
cases := []struct {
cmd Command
status int
}{
0: {
&basicAuthCmd{&Cmd{U: mustParse(t, srv.URL+"/a"), M: "GET"}, "me", "you"},
http.StatusOK,
},
1: {
&Cmd{U: mustParse(t, srv.URL+"/b"), M: "GET"},
http.StatusUnauthorized,
},
2: {
&basicAuthCmd{&Cmd{U: mustParse(t, srv.URL+"/c"), M: "GET"}, "some", "other"},
http.StatusUnauthorized,
},
3: {
&readerCmd{&Cmd{U: mustParse(t, srv.URL+"/d"), M: "POST"},
strings.NewReader("a")},
http.StatusUnauthorized,
},
4: {
&valuesCmd{&Cmd{U: mustParse(t, srv.URL+"/e"), M: "POST"},
url.Values{"k": {"v"}}},
http.StatusUnauthorized,
},
}
sh := &spyHandler{}
f := New(sh)
f.CrawlDelay = 0
q := f.Start()
for i, c := range cases {
if err := q.Send(c.cmd); err != nil {
t.Errorf("%d: error sending command: %s", i, err)
}
}
q.Close()
var urls []string
for i, c := range cases {
urls = append(urls, c.cmd.URL().String())
if st := sh.StatusFor(c.cmd.URL().String()); st != c.status {
t.Errorf("%d: expected status %d, got %d", i, c.status, st)
}
}
if !sh.CalledWithExactly(urls...) {
t.Error("expected handler to be called for all cases")
}
if cnt := sh.Errors(); cnt > 0 {
t.Errorf("expected no error, got %d", cnt)
}
}
type readerCmd struct {
*Cmd
r io.Reader
}
func (rc *readerCmd) Reader() io.Reader {
return rc.r
}
type valuesCmd struct {
*Cmd
vals url.Values
}
func (vc *valuesCmd) Values() url.Values {
return vc.vals
}
type cookiesCmd struct {
*Cmd
cooks []*http.Cookie
}
func (cc *cookiesCmd) Cookies() []*http.Cookie {
return cc.cooks
}
func TestBody(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
cooks := req.Cookies()
if len(cooks) == 0 {
b, err := ioutil.ReadAll(req.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.Write(b)
} else {
for i, c := range cooks {
if i > 0 {
w.Write([]byte{'&'})
}
w.Write([]byte(c.Name))
}
}
}))
defer srv.Close()
cases := []struct {
cmd Command
body string
}{
0: {
&readerCmd{&Cmd{U: mustParse(t, srv.URL+"/a"), M: "POST"},
strings.NewReader("a")},
"a",
},
1: {
&valuesCmd{&Cmd{U: mustParse(t, srv.URL+"/b"), M: "POST"},
url.Values{"k": {"v"}}},
"k=v",
},
2: {
&Cmd{U: mustParse(t, srv.URL+"/c"), M: "POST"},
"",
},
3: {
&basicAuthCmd{&Cmd{U: mustParse(t, srv.URL+"/d"), M: "POST"}, "me", "you"},
"",
},
4: {
&cookiesCmd{&Cmd{U: mustParse(t, srv.URL+"/e"), M: "GET"},
[]*http.Cookie{&http.Cookie{Name: "e"}}},
"e",
},
5: {
&cookiesCmd{&Cmd{U: mustParse(t, srv.URL+"/f"), M: "GET"},
[]*http.Cookie{&http.Cookie{Name: "f1"}, &http.Cookie{Name: "f2"}}},
"f1&f2",
},
}
sh := &spyHandler{}
f := New(sh)
f.CrawlDelay = 0
q := f.Start()
for i, c := range cases {
if err := q.Send(c.cmd); err != nil {
t.Errorf("%d: error sending command: %s", i, err)
}
}
q.Close()
var urls []string
for i, c := range cases {
urls = append(urls, c.cmd.URL().String())
if b := sh.BodyFor(c.cmd.URL().String()); b != c.body {
t.Errorf("%d: expected body '%s', got '%s'", i, c.body, b)
}
}
if !sh.CalledWithExactly(urls...) {
t.Error("expected handler to be called for all cases")
}
if cnt := sh.Errors(); cnt > 0 {
t.Errorf("expected no error, got %d", cnt)
}
}
type headerCmd struct {
*Cmd
hdr http.Header
}
func (hc *headerCmd) Header() http.Header {
return hc.hdr
}
func TestHeader(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
// Write headers in lexical order so that result is predictable
keys := make([]string, 0, len(req.Header))
for k := range req.Header {
if len(k) == 1 {
keys = append(keys, k)
}
}
sort.Strings(keys)
for _, k := range keys {
w.Write([]byte(fmt.Sprintf("%s:%s\n", k, req.Header[k][0])))
}
}))
defer srv.Close()
cases := []struct {
cmd Command
body string
}{
0: {
&headerCmd{&Cmd{U: mustParse(t, srv.URL+"/a"), M: "GET"},
http.Header{"A": {"a"}}},
"A:a\n",
},
1: {
&Cmd{U: mustParse(t, srv.URL+"/b"), M: "GET"},
"",
},
2: {
&headerCmd{&Cmd{U: mustParse(t, srv.URL+"/c"), M: "GET"},
http.Header{"C": {"c"}, "D": {"d"}}},
"C:c\nD:d\n",
},
}
sh := &spyHandler{}
f := New(sh)
f.CrawlDelay = 0
q := f.Start()
for i, c := range cases {
if err := q.Send(c.cmd); err != nil {
t.Errorf("%d: error sending command: %s", i, err)
}
}
q.Close()
var urls []string
for i, c := range cases {
urls = append(urls, c.cmd.URL().String())
if b := sh.BodyFor(c.cmd.URL().String()); b != c.body {
t.Errorf("%d: expected body '%s', got '%s'", i, c.body, b)
}
}
if !sh.CalledWithExactly(urls...) {
t.Error("expected handler to be called for all cases")
}
if cnt := sh.Errors(); cnt > 0 {
t.Errorf("expected no error, got %d", cnt)
}
}
type fullCmd struct {
*Cmd
user, pwd string
r io.Reader
vals url.Values
cooks []*http.Cookie
hdr http.Header
}
func (f *fullCmd) BasicAuth() (string, string) {
return f.user, f.pwd
}
func (f *fullCmd) Reader() io.Reader {
return f.r
}
func (f *fullCmd) Values() url.Values {
return f.vals
}
func (f *fullCmd) Cookies() []*http.Cookie {
return f.cooks
}
func (f *fullCmd) Header() http.Header {
return f.hdr
}
func TestFullCmd(t *testing.T) {
creds := base64.StdEncoding.EncodeToString([]byte("me:you"))
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
// Basic auth
auth := req.Header.Get("Authorization")
if auth != "Basic "+creds {
w.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Cookies
for i, c := range req.Cookies() {
if i > 0 {
w.Write([]byte{'&'})
}
w.Write([]byte(c.Name))
}
// Header
for k, v := range req.Header {
if len(k) == 1 {
w.Write([]byte(fmt.Sprintf("%s:%s\n", k, v[0])))
}
}
// Body
b, err := ioutil.ReadAll(req.Body)
if err != nil {
t.Fatal(err)
}
w.Write(b)
}))
defer srv.Close()
sh := &spyHandler{}
f := New(sh)
f.CrawlDelay = 0
q := f.Start()
cmd := &fullCmd{
&Cmd{U: mustParse(t, srv.URL+"/a"), M: "POST"},
"me", "you",
strings.NewReader("body"),
url.Values{"ignored": {"val"}},
[]*http.Cookie{&http.Cookie{Name: "a"}},
http.Header{"A": {"a"}},
}
if err := q.Send(cmd); err != nil {
t.Fatal(err)
}
q.Close()
// Assert 200 status
if st := sh.StatusFor(cmd.URL().String()); st != 200 {
t.Errorf("expected status %d, got %d", 200, st)
}
// Assert body (Cookies + Header)
exp := "aA:a\nbody"
if b := sh.BodyFor(cmd.URL().String()); b != exp {
t.Errorf("expected body '%s', got '%s'", exp, b)
}
}
func TestHandlerCmd(t *testing.T) {
var result int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {}))
defer srv.Close()
cases := []struct {
cmd Command
want int32
}{
0: {
mustCmd(NewHandlerCmd("GET", srv.URL+"/a", func(ctx *Context, res *http.Response, err error) {
atomic.AddInt32(&result, 1)
})), 1,
},
1: {
&Cmd{U: mustParse(t, srv.URL+"/b"), M: "GET"}, -1,
},
}
f := New(HandlerFunc(func(ctx *Context, res *http.Response, err error) {
atomic.AddInt32(&result, -1)
}))
f.CrawlDelay = 0
for i, c := range cases {
result = 0
q := f.Start()
if err := q.Send(c.cmd); err != nil {
t.Errorf("%d: error sending command: %s", i, err)
}
q.Close()
if result != c.want {
t.Errorf("%d: want %d, got %d", i, c.want, result)
}
}
}
func mustCmd(cmd Command, err error) Command {
if err != nil {
panic(err)
}
return cmd
}
func mustParse(t *testing.T, raw string) *url.URL {
parsed, err := url.Parse(raw)
if err != nil {
t.Fatal(err)
}
return parsed
}