forked from b3scale/b3scale
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_test.go
293 lines (248 loc) · 5.72 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
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
package api
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/golang-jwt/jwt"
"github.com/labstack/echo/v4"
"github.com/b3scale/b3scale/pkg/store"
)
func init() {
ctx := context.Background()
if err := store.ConnectTest(ctx); err != nil {
fmt.Println("WARNING: can not connect to DB. tests will fail.")
}
}
// ResponseRecorder is a response recorder with
// convenience functions for testing
type ResponseRecorder struct {
*httptest.ResponseRecorder
}
// AssertOK checks the http status code of the response
func (rec *ResponseRecorder) StatusOK() error {
res := rec.Result()
code := res.StatusCode
if code != http.StatusOK && code != http.StatusAccepted {
return fmt.Errorf("unexpected status code: %v", res.StatusCode)
}
return nil
}
func (rec *ResponseRecorder) Body() string {
res := rec.Result()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err)
}
return string(body)
}
func (rec *ResponseRecorder) JSON() map[string]interface{} {
res := rec.Result()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err)
}
data := map[string]interface{}{}
if err := json.Unmarshal(body, &data); err != nil {
panic(err)
}
return data
}
// MakeTestContext creates a new testing context
func MakeTestContext(req *http.Request) (*API, *ResponseRecorder) {
ctx := context.Background()
// Acquire connection
conn, err := store.Acquire(ctx)
if err != nil {
panic(err)
}
// Make request if not present
if req == nil {
req = httptest.NewRequest("GET", "http:///", nil)
}
req = req.WithContext(ctx)
rec := &ResponseRecorder{httptest.NewRecorder()}
e := echo.New()
context := e.NewContext(req, rec)
return &API{
Conn: conn,
Context: context,
}, rec
}
type TestRequest struct {
body []byte
contentType string
sub string
scopes []string
query string
keep bool
}
func NewTestRequest() *TestRequest {
return &TestRequest{
contentType: "application/json", // default
}
}
// Authorize adds scope and subject to request
func (req *TestRequest) Authorize(
sub string,
scopes ...string,
) *TestRequest {
req.sub = sub
req.scopes = scopes
return req
}
func (req *TestRequest) Query(q string) *TestRequest {
req.query = q
return req
}
// KeepState will prevent invoking a state reset after
// the context was created
func (req *TestRequest) KeepState() *TestRequest {
req.keep = true
return req
}
// JSON adds a request body
func (req *TestRequest) JSON(payload interface{}) *TestRequest {
body, err := json.Marshal(payload)
if err != nil {
panic(err)
}
req.body = body
req.contentType = "application/json"
return req
}
// Binary adds a binary request body
func (req *TestRequest) Binary(blob []byte) *TestRequest {
req.body = blob
req.contentType = "application/octet-stream"
return req
}
// Context creates the Context for a test request
func (req *TestRequest) Context() (*API, *ResponseRecorder) {
url := "http:///"
if req.query != "" {
url += "?" + req.query
}
httpReq, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
panic(err)
}
if req.body != nil {
httpReq, err = http.NewRequest(
http.MethodPost, "http:///", bytes.NewBuffer(req.body))
if err != nil {
panic(err)
}
httpReq.Header.Set("content-type", req.contentType)
}
api, rec := MakeTestContext(httpReq)
if req.sub != "" {
api.Authorize(req.sub, req.scopes)
}
if req.keep == false {
if err := api.ClearState(); err != nil {
panic(err)
}
}
return api, rec
}
func (api *API) Release() {
if api.Conn != nil {
api.Conn.Release()
}
}
// Invoke the endpoint handler in the api context
func (api *API) Handle(endpoint ResourceHandler) error {
return endpoint(api.Ctx(), api)
}
// Authorize authorizes the context
func (api *API) Authorize(
sub string,
scopes []string,
) *API {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, &AuthClaims{
StandardClaims: jwt.StandardClaims{
Subject: sub,
},
Scope: strings.Join(scopes, " "),
})
api.Set("user", token)
// Add authorization to context
api.Ref = sub
api.Scopes = scopes
return api
}
func (api *API) ClearState() error {
ctx := api.Ctx()
tx, err := api.Conn.Begin(ctx)
if err != nil {
return err
}
if _, err := tx.Exec(ctx, "DELETE FROM commands"); err != nil {
return err
}
if _, err := tx.Exec(ctx, "DELETE FROM meetings"); err != nil {
return err
}
if _, err := tx.Exec(ctx, "DELETE FROM backends"); err != nil {
return err
}
if _, err := tx.Exec(ctx, "DELETE FROM frontends"); err != nil {
return err
}
if err := tx.Commit(ctx); err != nil {
return err
}
return nil
}
func TestContextHasScope(t *testing.T) {
api, _ := MakeTestContext(nil)
defer api.Release()
api.Authorize("user23", []string{"foo", "b3scale"})
if !api.HasScope("b3scale") {
t.Error("b3scale should be a scope in an authorized context")
}
if api.HasScope("aaaaaaaa") {
t.Error("unexpected scope in context")
}
}
func TestStatus(t *testing.T) {
endpoint := Endpoint(apiStatusShow)
api, rec := MakeTestContext(nil)
defer api.Release()
if err := endpoint(api); err != nil {
t.Fatal(err)
}
t.Log(rec)
}
func TestParamID(t *testing.T) {
api, _ := MakeTestContext(nil)
defer api.Release()
api.SetParamNames("id")
api.SetParamValues("foo-bar")
id, internal := api.ParamID()
if id != "foo-bar" {
t.Error("unexpected id", id)
}
if internal == true {
t.Error("should not have been an internal ID")
}
}
func TestParamIDInternal(t *testing.T) {
api, _ := MakeTestContext(nil)
defer api.Release()
api.SetParamNames("id")
api.SetParamValues("internal:fnord")
id, internal := api.ParamID()
if id != "fnord" {
t.Error("unexpected id", id)
}
if !internal {
t.Error("should have been an internal ID")
}
}