-
Notifications
You must be signed in to change notification settings - Fork 59
/
session_test.go
373 lines (345 loc) · 8.05 KB
/
session_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
// Copyright (c) 2012-2013 Jason McVetta. This is Free Software, released
// under the terms of the GPL v3. See http://www.gnu.org/copyleft/gpl.html for
// details. Resist intellectual serfdom - the ownership of ideas is akin to
// slavery.
package napping
import (
"bytes"
"crypto/tls"
"encoding/base64"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"strings"
"testing"
"github.com/jmcvetta/randutil"
"github.com/stretchr/testify/assert"
)
func init() {
log.SetFlags(log.Ltime | log.Lshortfile)
}
//
// Request Tests
//
type hfunc http.HandlerFunc
type payload struct {
Foo string
}
var reqTests = []struct {
method string
params bool
payload bool
}{
{"GET", true, false},
{"POST", false, true},
{"PUT", false, true},
{"DELETE", false, false},
}
type pair struct {
r Request
hf hfunc
}
func paramHandler(t *testing.T, p url.Values, f hfunc) hfunc {
return func(w http.ResponseWriter, req *http.Request) {
if f != nil {
f(w, req)
}
q := req.URL.Query()
for k := range p {
if !assert.Equal(t, p[k], q[k]) {
msg := "Bad query params: " + q.Encode()
t.Error(msg)
return
}
}
}
}
func payloadHandler(t *testing.T, p payload, f hfunc) hfunc {
return func(w http.ResponseWriter, req *http.Request) {
if f != nil {
f(w, req)
}
if req.ContentLength <= 0 {
t.Error("Content-Length must be greater than 0.")
return
}
if req.Header.Get("Content-Type") != "application/json" {
t.Error("Bad content type")
return
}
body, err := ioutil.ReadAll(req.Body)
if err != nil {
t.Error("Body is nil")
return
}
var s payload
err = json.Unmarshal(body, &s)
if err != nil {
t.Error("JSON Unmarshal failed: ", err)
return
}
if s != p {
t.Error("Bad request body")
return
}
}
}
func methodHandler(t *testing.T, method string, f hfunc) hfunc {
return func(w http.ResponseWriter, req *http.Request) {
if f != nil {
f(w, req)
}
if req.Method != method {
t.Error("Incorrect method, got ", req.Method, " expected ", method)
}
}
}
func headerHandler(t *testing.T, h http.Header, f hfunc) hfunc {
return func(w http.ResponseWriter, req *http.Request) {
if f != nil {
f(w, req)
}
for k := range h {
expected := h.Get(k)
actual := req.Header.Get(k)
if expected != actual {
t.Error("Missing/bad header")
}
return
}
}
}
func TestRequest(t *testing.T) {
// NOTE: Do we really need to test different combinations for different
// HTTP methods?
pairs := []pair{}
for _, test := range reqTests {
baseReq := Request{
Method: test.method,
}
allReq := baseReq // allRR has all supported attribues for this verb
var allHF hfunc // allHF is combination of all relevant handlers
//
// Generate a random key/value pair
//
key, err := randutil.AlphaString(8)
if err != nil {
t.Error(err)
}
value, err := randutil.AlphaString(8)
if err != nil {
t.Error(err)
}
//
// Method
//
r := baseReq
f := methodHandler(t, test.method, nil)
allHF = methodHandler(t, test.method, allHF)
pairs = append(pairs, pair{r, f})
//
// Header
//
h := http.Header{}
h.Add(key, value)
r = baseReq
r.Header = &h
allReq.Header = &h
f = headerHandler(t, h, nil)
allHF = headerHandler(t, h, allHF)
pairs = append(pairs, pair{r, f})
//
// Params
//
if test.params {
p := Params{key: value}.AsUrlValues()
f = paramHandler(t, p, nil)
allHF = paramHandler(t, p, allHF)
r = baseReq
r.Params = &p
allReq.Params = &p
pairs = append(pairs, pair{r, f})
}
//
// Payload
//
if test.payload {
p := payload{value}
f = payloadHandler(t, p, nil)
allHF = payloadHandler(t, p, allHF)
r = baseReq
r.Payload = p
allReq.Payload = p
pairs = append(pairs, pair{r, f})
}
//
// All
//
pairs = append(pairs, pair{allReq, allHF})
}
for _, p := range pairs {
srv := httptest.NewServer(http.HandlerFunc(p.hf))
defer srv.Close()
//
// Good request
//
p.r.Url = "http://" + srv.Listener.Addr().String()
_, err := Send(&p.r)
if err != nil {
t.Error(err)
}
}
}
func TestInvalidTLS(t *testing.T) {
srv := httptest.NewTLSServer(http.HandlerFunc(handleEmptyOK))
defer srv.Close()
// The first request, which is supposed to fail, will print something similar to
// "20:45:27 server.go:2161: http: TLS handshake error from 127.0.0.1:56293: remote error: bad certificate" to the console.
// NOTE: Is this something that should be capture and silently ignored?
s := Session{}
r := Request{
Url: "https://" + srv.Listener.Addr().String(),
Method: "GET",
}
_, err := s.Send(&r)
if err == nil {
t.Fatal("Invalid TLS without custom Transport object. The request should have errored out!")
}
s2 := Session{}
r2 := Request{
Url: "https://" + srv.Listener.Addr().String(),
Method: "GET",
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
resp2, err2 := s2.Send(&r2)
if err2 != nil {
t.Fatal(err2)
}
if resp2.Status() != http.StatusOK {
t.Fatalf("Expected status %d but got %d", http.StatusOK, resp2.Status())
}
}
func TestBasicAuth(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(handleGetBasicAuth))
defer srv.Close()
s := Session{}
r := Request{
Url: "http://" + srv.Listener.Addr().String(),
Method: "GET",
Userinfo: url.UserPassword("jtkirk", "Beam me up, Scotty!"),
}
resp, err := s.Send(&r)
if err != nil {
t.Fatal(err)
}
if resp.Status() != 200 {
t.Fatalf("Expected status 200 but got %d", resp.Status())
}
}
func TestBasicUrlAuth(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(handleGetBasicAuth))
defer srv.Close()
s := Session{}
testURL, _ := url.Parse("http://" + srv.Listener.Addr().String())
testURL.User = url.UserPassword("jtkirk", "Beam me up, Scotty!")
r := Request{
Url: testURL.String(),
Method: "GET",
}
resp, err := s.Send(&r)
if err != nil {
t.Fatal(err)
}
if resp.Status() != 200 {
t.Fatalf("Expected status 200 but got %d", resp.Status())
}
}
func TestRawPayload(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(handleEmptyOK))
defer srv.Close()
s := Session{}
testURL, _ := url.Parse("http://" + srv.Listener.Addr().String())
r := Request{
Url: testURL.String(),
Method: "POST",
Payload: bytes.NewBuffer([]byte("foobar")),
RawPayload: true,
}
resp, err := s.Send(&r)
if err != nil {
t.Fatal(err)
}
if resp.Status() != 200 {
t.Fatalf("Expected status 200 but got %d", resp.Status())
}
}
func TestRawPayloadFail(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(handleEmptyOK))
defer srv.Close()
s := Session{}
testURL, _ := url.Parse("http://" + srv.Listener.Addr().String())
j := struct{}{}
r := Request{
Url: testURL.String(),
Method: "POST",
Payload: &j,
RawPayload: true,
}
_, err := s.Send(&r)
if err == nil {
t.Fatal("Expect invalid raw payload type")
}
}
//
// TODO: Response Tests
//
func TestErrMsg(t *testing.T) {}
func TestStatus(t *testing.T) {}
func TestUnmarshal(t *testing.T) {}
func TestUnmarshalFail(t *testing.T) {}
func handleEmptyOK(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusOK)
}
func handleGetBasicAuth(w http.ResponseWriter, req *http.Request) {
authRegex := regexp.MustCompile(`[Bb]asic (?P<encoded>\S+)`)
str := req.Header.Get("Authorization")
matches := authRegex.FindStringSubmatch(str)
if len(matches) != 2 {
msg := "Regex doesn't match"
log.Print(msg)
http.Error(w, msg, http.StatusBadRequest)
return
}
encoded := matches[1]
b, err := base64.URLEncoding.DecodeString(encoded)
if err != nil {
msg := "Base64 decode failed"
log.Print(msg)
http.Error(w, msg, http.StatusBadRequest)
return
}
parts := strings.Split(string(b), ":")
if len(parts) != 2 {
msg := "String split failed"
log.Print(msg)
http.Error(w, msg, http.StatusBadRequest)
return
}
username := parts[0]
password := parts[1]
if username != "jtkirk" || password != "Beam me up, Scotty!" {
code := http.StatusUnauthorized
text := http.StatusText(code)
http.Error(w, text, code)
return
}
w.WriteHeader(200)
}