-
Notifications
You must be signed in to change notification settings - Fork 15
/
http_test.go
99 lines (85 loc) · 2.39 KB
/
http_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
package lmdrouter
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/jgroeneveld/trial/assert"
)
func TestHTTPHandler(t *testing.T) {
lmd := NewRouter("/api", logger)
lmd.Route("GET", "/", listSomethings)
lmd.Route("POST", "/", postSomething, auth)
lmd.Route("GET", "/:id", getSomething)
lmd.Route("GET", "/:id/stuff", listStuff)
lmd.Route("GET", "/:id/stuff/:fake", listStuff)
ts := httptest.NewServer(http.HandlerFunc(lmd.ServeHTTP))
defer ts.Close()
t.Run("POST /api without auth", func(t *testing.T) {
res, err := http.Post(
ts.URL+"/api",
"application/json; charset=UTF-8",
nil,
)
assert.Equal(t, nil, err, "Error must not be nil")
assert.Equal(t, http.StatusUnauthorized, res.StatusCode, "Status code must be 401")
assert.True(t, len(log) > 0, "Log must have items")
})
t.Run("POST /api with auth", func(t *testing.T) {
req, err := http.NewRequest(
"POST",
ts.URL+"/api",
nil,
)
if err != nil {
t.Fatalf("Request creation unexpectedly failed: %s", err)
}
req.Header.Set("Authorization", "Bearer fake-token")
res, err := http.DefaultClient.Do(req)
assert.Equal(t, nil, err, "Error must not be nil")
assert.Equal(t, http.StatusBadRequest, res.StatusCode, "Status code must be 400")
})
t.Run("GET /api", func(t *testing.T) {
res, err := http.Get(ts.URL + "/api")
assert.Equal(t, nil, err, "Error must not be nil")
assert.Equal(t, http.StatusOK, res.StatusCode, "Status code must be 200")
assert.True(t, len(log) > 0, "Log must have items")
})
t.Run("GET /api/something/stuff", func(t *testing.T) {
req, _ := http.NewRequest(
"GET",
ts.URL+"/api/something/stuff?terms=one&terms=two&terms=three",
nil,
)
req.Header.Set("Accept-Language", "en-us")
res, err := http.DefaultClient.Do(req)
assert.Equal(t, nil, err, "Response error must be nil")
assert.Equal(t, http.StatusOK, res.StatusCode, "Status code must be 200")
var data []mockItem
err = json.NewDecoder(res.Body).Decode(&data)
assert.Equal(t, nil, err, "Decode error must be nil")
assert.DeepEqual(
t,
[]mockItem{
{
ID: "something",
Name: "one in en-us",
Date: time.Time{},
},
{
ID: "something",
Name: "two in en-us",
Date: time.Time{},
},
{
ID: "something",
Name: "three in en-us",
Date: time.Time{},
},
},
data,
"Response body must match",
)
})
}