-
Notifications
You must be signed in to change notification settings - Fork 3
/
api_test.go
124 lines (113 loc) · 2.51 KB
/
api_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
package patrol
import (
"bytes"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"go.uber.org/zap"
)
func TestAPI(t *testing.T) {
repo := NewLocalRepo(time.Now, &Bucket{
name: "foo",
created: time.Now(),
})
log, err := zap.NewDevelopment()
if err != nil {
t.Fatal(err)
}
api := NewAPI(log, time.Now, repo)
srv := httptest.NewServer(api)
for _, tc := range []struct {
name string
req *http.Request
assert func(testing.TB, *http.Response)
}{
{
name: "bucket name too long",
req: request("POST", srv.URL+"/take/"+strings.Repeat("A", maxBucketNameLength+1)),
assert: response(
code(http.StatusBadRequest),
body([]byte(ErrNameTooLarge.Error())),
),
},
{
name: "default rate is zero",
req: request("POST", srv.URL+"/take/default-rate"),
assert: response(
code(http.StatusTooManyRequests),
body([]byte("0")),
),
},
{
name: "default count is one",
req: request("POST", srv.URL+"/take/default-count?rate=2:s"),
assert: response(
code(http.StatusOK),
body([]byte("1")), // 1 remaining
),
},
{
name: "ok",
req: request("POST", srv.URL+"/take/pass?rate=2:s&count=1"),
assert: response(
code(http.StatusOK),
body([]byte("1")), // 1 remaining
),
},
{
name: "too many requests",
req: request("POST", srv.URL+"/take/fail?rate=0:s&count=1"),
assert: response(
code(http.StatusTooManyRequests),
body([]byte("0")),
),
},
} {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
res, err := http.DefaultClient.Do(tc.req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
tc.assert(t, res)
})
}
}
func response(asserts ...func(testing.TB, *http.Response)) func(testing.TB, *http.Response) {
return func(t testing.TB, r *http.Response) {
t.Helper()
for _, assert := range asserts {
assert(t, r)
}
}
}
func code(want int) func(testing.TB, *http.Response) {
return func(t testing.TB, r *http.Response) {
t.Helper()
if have := r.StatusCode; have != want {
t.Errorf("have code %d, want %d", have, want)
}
}
}
func body(want []byte) func(testing.TB, *http.Response) {
return func(t testing.TB, r *http.Response) {
t.Helper()
if have, err := ioutil.ReadAll(r.Body); err != nil {
t.Fatal(err)
} else if !bytes.Equal(have, want) {
t.Errorf("have body %q, want %q", have, want)
}
}
}
func request(method, rawurl string) *http.Request {
req, err := http.NewRequest(method, rawurl, nil)
if err != nil {
panic(err)
}
return req
}