Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

types/rest: add unit tests #5779

Merged
merged 5 commits into from
Mar 10, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ and provided directly the IAVL store.
* (types) [\#5533](https://github.com/cosmos/cosmos-sdk/pull/5533) Refactored `AppModuleBasic` and `AppModuleGenesis`
to now accept a `codec.JSONMarshaler` for modular serialization of genesis state.
* (crypto/keys) [\#5735](https://github.com/cosmos/cosmos-sdk/pull/5735) Keyring's Update() function is now no-op.
* (types/rest) [\#5779](https://github.com/cosmos/cosmos-sdk/pull/5779) Drop unused Parse{Int64OrReturnBadRequest,QueryParamBool}() functions.

### Features

Expand Down
25 changes: 0 additions & 25 deletions types/rest/rest.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,20 +171,6 @@ func WriteSimulationResponse(w http.ResponseWriter, cdc *codec.Codec, gas uint64
_, _ = w.Write(resp)
}

// ParseInt64OrReturnBadRequest converts s to a int64 value.
func ParseInt64OrReturnBadRequest(w http.ResponseWriter, s string) (n int64, ok bool) {
var err error

n, err = strconv.ParseInt(s, 10, 64)
if err != nil {
err := fmt.Errorf("'%s' is not a valid int64", s)
WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return n, false
}

return n, true
}

// ParseUint64OrReturnBadRequest converts s to a uint64 value.
func ParseUint64OrReturnBadRequest(w http.ResponseWriter, s string) (n uint64, ok bool) {
var err error
Expand Down Expand Up @@ -382,14 +368,3 @@ func ParseHTTPArgsWithLimit(r *http.Request, defaultLimit int) (tags []string, p
func ParseHTTPArgs(r *http.Request) (tags []string, page, limit int, err error) {
return ParseHTTPArgsWithLimit(r, DefaultLimit)
}

// ParseQueryParamBool parses the given param to a boolean. It returns false by
// default if the string is not parseable to bool.
func ParseQueryParamBool(r *http.Request, param string) bool {
valueStr := r.FormValue(param)
value := false
if ok, err := strconv.ParseBool(valueStr); err == nil {
value = ok
}
return value
}
164 changes: 161 additions & 3 deletions types/rest/rest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
package rest

import (
"errors"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"sort"
"strings"
"testing"

"github.com/stretchr/testify/require"
Expand All @@ -19,7 +21,24 @@ import (
"github.com/cosmos/cosmos-sdk/types"
)

func TestBaseReqValidateBasic(t *testing.T) {
func TestBaseReq_Sanitize(t *testing.T) {
t.Parallel()
sanitized := BaseReq{ChainID: " test",
Memo: "memo ",
From: " cosmos1cq0sxam6x4l0sv9yz3a2vlqhdhvt2k6jtgcse0 ",
Gas: " ",
GasAdjustment: " 0.3",
}.Sanitize()
require.Equal(t, BaseReq{ChainID: "test",
Memo: "memo",
From: "cosmos1cq0sxam6x4l0sv9yz3a2vlqhdhvt2k6jtgcse0",
Gas: "",
GasAdjustment: "0.3",
}, sanitized)
}

func TestBaseReq_ValidateBasic(t *testing.T) {
t.Parallel()
fromAddr := "cosmos1cq0sxam6x4l0sv9yz3a2vlqhdhvt2k6jtgcse0"
tenstakes, err := types.ParseCoins("10stake")
require.NoError(t, err)
Expand Down Expand Up @@ -63,6 +82,7 @@ func TestBaseReqValidateBasic(t *testing.T) {
}

func TestParseHTTPArgs(t *testing.T) {
t.Parallel()
req0 := mustNewRequest(t, "", "/", nil)
req1 := mustNewRequest(t, "", "/?limit=5", nil)
req2 := mustNewRequest(t, "", "/?page=5", nil)
Expand Down Expand Up @@ -114,6 +134,7 @@ func TestParseHTTPArgs(t *testing.T) {
}

func TestParseQueryHeight(t *testing.T) {
t.Parallel()
var emptyHeight int64
height := int64(1256756)

Expand Down Expand Up @@ -155,6 +176,7 @@ func TestProcessPostResponse(t *testing.T) {
// 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"`
Expand Down Expand Up @@ -205,6 +227,142 @@ func TestProcessPostResponse(t *testing.T) {
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 BaseReq

// test OK
ReadRESTReq(w, req, codec.New(), &br)
require.Equal(t, BaseReq{ChainID: "alessio", Memo: "text"}, br)
res := w.Result()
require.Equal(t, http.StatusOK, res.StatusCode)

// test non valid JSON
reqBody = ioutil.NopCloser(strings.NewReader(`MALFORMED`))
req = &http.Request{Body: reqBody}
br = BaseReq{}
w = httptest.NewRecorder()
ReadRESTReq(w, req, codec.New(), &br)
require.Equal(t, br, br)
res = w.Result()
require.Equal(t, http.StatusBadRequest, res.StatusCode)
}

func TestWriteSimulationResponse(t *testing.T) {
t.Parallel()
w := httptest.NewRecorder()
WriteSimulationResponse(w, codec.New(), 10)
res := w.Result()
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 := ParseUint64OrReturnBadRequest(w, "100")
require.True(t, ok)
require.Equal(t, http.StatusOK, w.Result().StatusCode)

w = httptest.NewRecorder()
_, ok = ParseUint64OrReturnBadRequest(w, "-100")
require.False(t, ok)
require.Equal(t, http.StatusBadRequest, w.Result().StatusCode)
}

func TestParseFloat64OrReturnBadRequest(t *testing.T) {
t.Parallel()
w := httptest.NewRecorder()
_, ok := ParseFloat64OrReturnBadRequest(w, "100", 0)
require.True(t, ok)
require.Equal(t, http.StatusOK, w.Result().StatusCode)

w = httptest.NewRecorder()
_, ok = ParseFloat64OrReturnBadRequest(w, "bad request", 0)
require.False(t, ok)
require.Equal(t, http.StatusBadRequest, w.Result().StatusCode)

w = httptest.NewRecorder()
ret, ok := ParseFloat64OrReturnBadRequest(w, "", 9.0)
require.Equal(t, float64(9), ret)
require.True(t, ok)
require.Equal(t, http.StatusOK, w.Result().StatusCode)
}

func TestPostProcessResponseBare(t *testing.T) {
t.Parallel()

// write bytes
ctx := context.CLIContext{}
w := httptest.NewRecorder()
bs := []byte("text string")
PostProcessResponseBare(w, ctx, bs)
res := w.Result()
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"}
PostProcessResponseBare(w, ctx, data)
res = w.Result()
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))

// 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"}
PostProcessResponseBare(w, ctx, data)
res = w.Result()
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{}
PostProcessResponseBare(w, ctx, data2)
res = w.Result()
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, "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.
Expand All @@ -218,7 +376,7 @@ func runPostProcessResponse(t *testing.T, ctx context.CLIContext, obj interface{
PostProcessResponse(w, ctx, obj)
require.Equal(t, http.StatusOK, w.Code, w.Body)
resp := w.Result()
defer resp.Body.Close()
t.Cleanup(func() { resp.Body.Close() })
body, err := ioutil.ReadAll(resp.Body)
require.Nil(t, err)
require.Equal(t, expectedBody, body)
Expand All @@ -236,7 +394,7 @@ func runPostProcessResponse(t *testing.T, ctx context.CLIContext, obj interface{
PostProcessResponse(w, ctx, marshalled)
require.Equal(t, http.StatusOK, w.Code, w.Body)
resp = w.Result()
defer resp.Body.Close()
t.Cleanup(func() { resp.Body.Close() })
body, err = ioutil.ReadAll(resp.Body)
require.Nil(t, err)
require.Equal(t, expectedBody, body)
Expand Down