forked from cosmos/cosmos-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrest_test.go
476 lines (400 loc) · 14.3 KB
/
rest_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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
package rest_test
import (
"errors"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"sort"
"strings"
"testing"
"github.com/spf13/viper"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/secp256k1"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/rest"
)
func TestBaseReq_Sanitize(t *testing.T) {
t.Parallel()
sanitized := rest.BaseReq{ChainID: " test",
Memo: "memo ",
From: " cosmos1cq0sxam6x4l0sv9yz3a2vlqhdhvt2k6jtgcse0 ",
Gas: " ",
GasAdjustment: " 0.3",
}.Sanitize()
require.Equal(t, rest.BaseReq{ChainID: "test",
Memo: "memo",
From: "cosmos1cq0sxam6x4l0sv9yz3a2vlqhdhvt2k6jtgcse0",
Gas: "",
GasAdjustment: "0.3",
}, sanitized)
}
func TestBaseReq_ValidateBasic(t *testing.T) {
fromAddr := "cosmos1cq0sxam6x4l0sv9yz3a2vlqhdhvt2k6jtgcse0"
tenstakes, err := types.ParseCoins("10stake")
require.NoError(t, err)
onestake, err := types.ParseDecCoins("1.0stake")
require.NoError(t, err)
req1 := rest.NewBaseReq(
fromAddr, "", "nonempty", "", "", 0, 0, tenstakes, nil, false,
)
req2 := rest.NewBaseReq(
"", "", "nonempty", "", "", 0, 0, tenstakes, nil, false,
)
req3 := rest.NewBaseReq(
fromAddr, "", "", "", "", 0, 0, tenstakes, nil, false,
)
req4 := rest.NewBaseReq(
fromAddr, "", "nonempty", "", "", 0, 0, tenstakes, onestake, false,
)
req5 := rest.NewBaseReq(
fromAddr, "", "nonempty", "", "", 0, 0, types.Coins{}, types.DecCoins{}, false,
)
tests := []struct {
name string
req rest.BaseReq
w http.ResponseWriter
want bool
}{
{"ok", req1, httptest.NewRecorder(), true},
{"neither fees nor gasprices provided", req5, httptest.NewRecorder(), true},
{"empty from", req2, httptest.NewRecorder(), false},
{"empty chain-id", req3, httptest.NewRecorder(), false},
{"fees and gasprices provided", req4, httptest.NewRecorder(), false},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
require.Equal(t, tt.want, tt.req.ValidateBasic(tt.w))
})
}
}
func TestParseHTTPArgs(t *testing.T) {
t.Parallel()
req0 := mustNewRequest(t, "", "/", nil)
req1 := mustNewRequest(t, "", "/?limit=5", nil)
req2 := mustNewRequest(t, "", "/?page=5", nil)
req3 := mustNewRequest(t, "", "/?page=5&limit=5", nil)
reqE1 := mustNewRequest(t, "", "/?page=-1", nil)
reqE2 := mustNewRequest(t, "", "/?limit=-1", nil)
req4 := mustNewRequest(t, "", "/?foo=faa", nil)
reqTxH := mustNewRequest(t, "", "/?tx.minheight=12&tx.maxheight=14", nil)
tests := []struct {
name string
req *http.Request
w http.ResponseWriter
tags []string
page int
limit int
err bool
}{
{"no params", req0, httptest.NewRecorder(), []string{}, rest.DefaultPage, rest.DefaultLimit, false},
{"Limit", req1, httptest.NewRecorder(), []string{}, rest.DefaultPage, 5, false},
{"Page", req2, httptest.NewRecorder(), []string{}, 5, rest.DefaultLimit, false},
{"Page and limit", req3, httptest.NewRecorder(), []string{}, 5, 5, false},
{"error page 0", reqE1, httptest.NewRecorder(), []string{}, rest.DefaultPage, rest.DefaultLimit, true},
{"error limit 0", reqE2, httptest.NewRecorder(), []string{}, rest.DefaultPage, rest.DefaultLimit, true},
{"tags", req4, httptest.NewRecorder(), []string{"foo='faa'"}, rest.DefaultPage, rest.DefaultLimit, false},
{"tags", reqTxH, httptest.NewRecorder(), []string{"tx.height<=14", "tx.height>=12"}, rest.DefaultPage, rest.DefaultLimit, false},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
tags, page, limit, err := rest.ParseHTTPArgs(tt.req)
sort.Strings(tags)
if tt.err {
require.NotNil(t, err)
} else {
require.Nil(t, err)
require.Equal(t, tt.tags, tags)
require.Equal(t, tt.page, page)
require.Equal(t, tt.limit, limit)
}
})
}
}
func TestParseQueryHeight(t *testing.T) {
t.Parallel()
var emptyHeight int64
height := int64(1256756)
req0 := mustNewRequest(t, "", "/", nil)
req1 := mustNewRequest(t, "", "/?height=1256756", nil)
req2 := mustNewRequest(t, "", "/?height=456yui4567", nil)
req3 := mustNewRequest(t, "", "/?height=-1", nil)
tests := []struct {
name string
req *http.Request
w http.ResponseWriter
cliCtx context.CLIContext
expectedHeight int64
expectedOk bool
}{
{"no height", req0, httptest.NewRecorder(), context.CLIContext{}, emptyHeight, true},
{"height", req1, httptest.NewRecorder(), context.CLIContext{}, height, true},
{"invalid height", req2, httptest.NewRecorder(), context.CLIContext{}, emptyHeight, false},
{"negative height", req3, httptest.NewRecorder(), context.CLIContext{}, emptyHeight, false},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(tt.w, tt.cliCtx, tt.req)
if tt.expectedOk {
require.True(t, ok)
require.Equal(t, tt.expectedHeight, cliCtx.Height)
} else {
require.False(t, ok)
require.Empty(t, tt.expectedHeight, cliCtx.Height)
}
})
}
}
func TestProcessPostResponse(t *testing.T) {
// mock account
// PubKey field ensures amino encoding is used first since standard
// JSON encoding will panic on crypto.PubKey
t.Parallel()
type mockAccount struct {
Address types.AccAddress `json:"address"`
Coins types.Coins `json:"coins"`
PubKey crypto.PubKey `json:"public_key"`
AccountNumber uint64 `json:"account_number"`
Sequence uint64 `json:"sequence"`
}
// setup
viper.Set(flags.FlagOffline, true)
ctx := context.NewCLIContext()
height := int64(194423)
privKey := secp256k1.GenPrivKey()
pubKey := privKey.PubKey()
addr := types.AccAddress(pubKey.Address())
coins := types.NewCoins(types.NewCoin("atom", types.NewInt(100)), types.NewCoin("tree", types.NewInt(125)))
accNumber := uint64(104)
sequence := uint64(32)
acc := mockAccount{addr, coins, pubKey, accNumber, sequence}
cdc := codec.New()
codec.RegisterCrypto(cdc)
cdc.RegisterConcrete(&mockAccount{}, "cosmos-sdk/mockAccount", nil)
ctx = ctx.WithCodec(cdc)
// setup expected results
jsonNoIndent, err := ctx.Codec.MarshalJSON(acc)
require.Nil(t, err)
respNoIndent := rest.NewResponseWithHeight(height, jsonNoIndent)
expectedNoIndent, err := ctx.Codec.MarshalJSON(respNoIndent)
require.Nil(t, err)
expectedWithIndent, err := codec.MarshalIndentFromJSON(expectedNoIndent)
require.Nil(t, err)
// check that negative height writes an error
w := httptest.NewRecorder()
ctx = ctx.WithHeight(-1)
rest.PostProcessResponse(w, ctx, acc)
require.Equal(t, http.StatusInternalServerError, w.Code)
// check that height returns expected response
ctx = ctx.WithHeight(height)
runPostProcessResponse(t, ctx, acc, expectedNoIndent, false)
// check height with indent
runPostProcessResponse(t, ctx, acc, expectedWithIndent, true)
}
func TestReadRESTReq(t *testing.T) {
t.Parallel()
reqBody := ioutil.NopCloser(strings.NewReader(`{"chain_id":"alessio","memo":"text"}`))
req := &http.Request{Body: reqBody}
w := httptest.NewRecorder()
var br rest.BaseReq
// test OK
rest.ReadRESTReq(w, req, codec.New(), &br)
res := w.Result() //nolint:bodyclose
t.Cleanup(func() { res.Body.Close() })
require.Equal(t, rest.BaseReq{ChainID: "alessio", Memo: "text"}, br)
require.Equal(t, http.StatusOK, res.StatusCode)
// test non valid JSON
reqBody = ioutil.NopCloser(strings.NewReader(`MALFORMED`))
req = &http.Request{Body: reqBody}
br = rest.BaseReq{}
w = httptest.NewRecorder()
rest.ReadRESTReq(w, req, codec.New(), &br)
require.Equal(t, br, br)
res = w.Result() //nolint:bodyclose
t.Cleanup(func() { res.Body.Close() })
require.Equal(t, http.StatusBadRequest, res.StatusCode)
}
func TestWriteSimulationResponse(t *testing.T) {
t.Parallel()
w := httptest.NewRecorder()
rest.WriteSimulationResponse(w, codec.New(), 10)
res := w.Result() //nolint:bodyclose
t.Cleanup(func() { res.Body.Close() })
require.Equal(t, http.StatusOK, res.StatusCode)
bs, err := ioutil.ReadAll(res.Body)
require.NoError(t, err)
t.Cleanup(func() { res.Body.Close() })
require.Equal(t, `{"gas_estimate":"10"}`, string(bs))
}
func TestParseUint64OrReturnBadRequest(t *testing.T) {
t.Parallel()
w := httptest.NewRecorder()
_, ok := rest.ParseUint64OrReturnBadRequest(w, "100")
require.True(t, ok)
require.Equal(t, http.StatusOK, w.Result().StatusCode) //nolint:bodyclose
w = httptest.NewRecorder()
_, ok = rest.ParseUint64OrReturnBadRequest(w, "-100")
require.False(t, ok)
require.Equal(t, http.StatusBadRequest, w.Result().StatusCode) //nolint:bodyclose
}
func TestParseFloat64OrReturnBadRequest(t *testing.T) {
t.Parallel()
w := httptest.NewRecorder()
_, ok := rest.ParseFloat64OrReturnBadRequest(w, "100", 0)
require.True(t, ok)
require.Equal(t, http.StatusOK, w.Result().StatusCode) //nolint:bodyclose
w = httptest.NewRecorder()
_, ok = rest.ParseFloat64OrReturnBadRequest(w, "bad request", 0)
require.False(t, ok)
require.Equal(t, http.StatusBadRequest, w.Result().StatusCode) //nolint:bodyclose
w = httptest.NewRecorder()
ret, ok := rest.ParseFloat64OrReturnBadRequest(w, "", 9.0)
require.Equal(t, float64(9), ret)
require.True(t, ok)
require.Equal(t, http.StatusOK, w.Result().StatusCode) //nolint:bodyclose
}
func TestParseQueryParamBool(t *testing.T) {
req := httptest.NewRequest("GET", "/target?boolean=true", nil)
require.True(t, rest.ParseQueryParamBool(req, "boolean"))
require.False(t, rest.ParseQueryParamBool(req, "nokey"))
req = httptest.NewRequest("GET", "/target?boolean=false", nil)
require.False(t, rest.ParseQueryParamBool(req, "boolean"))
require.False(t, rest.ParseQueryParamBool(req, ""))
}
func TestPostProcessResponseBare(t *testing.T) {
t.Parallel()
// write bytes
ctx := context.CLIContext{}
w := httptest.NewRecorder()
bs := []byte("text string")
rest.PostProcessResponseBare(w, ctx, bs)
res := w.Result() //nolint:bodyclose
require.Equal(t, http.StatusOK, res.StatusCode)
got, err := ioutil.ReadAll(res.Body)
require.NoError(t, err)
t.Cleanup(func() { res.Body.Close() })
require.Equal(t, "text string", string(got))
// write struct and indent response
ctx = context.CLIContext{Indent: true}.WithCodec(codec.New())
w = httptest.NewRecorder()
data := struct {
X int `json:"x"`
S string `json:"s"`
}{X: 10, S: "test"}
rest.PostProcessResponseBare(w, ctx, data)
res = w.Result() //nolint:bodyclose
require.Equal(t, http.StatusOK, res.StatusCode)
got, err = ioutil.ReadAll(res.Body)
require.NoError(t, err)
t.Cleanup(func() { res.Body.Close() })
require.Equal(t, `{
"s": "test",
"x": "10"
}`, string(got))
// write struct, don't indent response
ctx = context.CLIContext{Indent: false}.WithCodec(codec.New())
w = httptest.NewRecorder()
data = struct {
X int `json:"x"`
S string `json:"s"`
}{X: 10, S: "test"}
rest.PostProcessResponseBare(w, ctx, data)
res = w.Result() //nolint:bodyclose
require.Equal(t, http.StatusOK, res.StatusCode)
got, err = ioutil.ReadAll(res.Body)
require.NoError(t, err)
t.Cleanup(func() { res.Body.Close() })
require.Equal(t, `{"x":"10","s":"test"}`, string(got))
// test marshalling failure
ctx = context.CLIContext{Indent: false}.WithCodec(codec.New())
w = httptest.NewRecorder()
data2 := badJSONMarshaller{}
rest.PostProcessResponseBare(w, ctx, data2)
res = w.Result() //nolint:bodyclose
require.Equal(t, http.StatusInternalServerError, res.StatusCode)
got, err = ioutil.ReadAll(res.Body)
require.NoError(t, err)
t.Cleanup(func() { res.Body.Close() })
require.Equal(t, []string{"application/json"}, res.Header["Content-Type"])
require.Equal(t, `{"error":"couldn't marshal"}`, string(got))
}
type badJSONMarshaller struct{}
func (badJSONMarshaller) MarshalJSON() ([]byte, error) {
return nil, errors.New("couldn't marshal")
}
// asserts that ResponseRecorder returns the expected code and body
// runs PostProcessResponse on the objects regular interface and on
// the marshalled struct.
func runPostProcessResponse(t *testing.T, ctx context.CLIContext, obj interface{}, expectedBody []byte, indent bool) {
if indent {
ctx.Indent = indent
}
// test using regular struct
w := httptest.NewRecorder()
rest.PostProcessResponse(w, ctx, obj)
require.Equal(t, http.StatusOK, w.Code, w.Body)
resp := w.Result() //nolint:bodyclose
t.Cleanup(func() { resp.Body.Close() })
body, err := ioutil.ReadAll(resp.Body)
require.Nil(t, err)
require.Equal(t, expectedBody, body)
marshalled, err := ctx.Codec.MarshalJSON(obj)
require.NoError(t, err)
if indent {
marshalled, err = codec.MarshalIndentFromJSON(marshalled)
require.NoError(t, err)
}
// test using marshalled struct
w = httptest.NewRecorder()
rest.PostProcessResponse(w, ctx, marshalled)
require.Equal(t, http.StatusOK, w.Code, w.Body)
resp = w.Result() //nolint:bodyclose
t.Cleanup(func() { resp.Body.Close() })
body, err = ioutil.ReadAll(resp.Body)
require.Nil(t, err)
require.Equal(t, string(expectedBody), string(body))
}
func mustNewRequest(t *testing.T, method, url string, body io.Reader) *http.Request {
req, err := http.NewRequest(method, url, body)
require.NoError(t, err)
err = req.ParseForm()
require.NoError(t, err)
return req
}
func TestCheckErrors(t *testing.T) {
t.Parallel()
err := errors.New("ERROR")
tests := []struct {
name string
checkerFn func(w http.ResponseWriter, err error) bool
error error
wantErr bool
wantString string
wantStatus int
}{
{"500", rest.CheckInternalServerError, err, true, `{"error":"ERROR"}`, http.StatusInternalServerError},
{"500 (no error)", rest.CheckInternalServerError, nil, false, ``, http.StatusInternalServerError},
{"400", rest.CheckBadRequestError, err, true, `{"error":"ERROR"}`, http.StatusBadRequest},
{"400 (no error)", rest.CheckBadRequestError, nil, false, ``, http.StatusBadRequest},
{"404", rest.CheckNotFoundError, err, true, `{"error":"ERROR"}`, http.StatusNotFound},
{"404 (no error)", rest.CheckNotFoundError, nil, false, ``, http.StatusNotFound},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
w := httptest.NewRecorder()
require.Equal(t, tt.wantErr, tt.checkerFn(w, tt.error))
if tt.wantErr {
require.Equal(t, w.Body.String(), tt.wantString)
require.Equal(t, w.Code, tt.wantStatus)
}
})
}
}