github.com/franono/tendermint@v0.32.2-0.20200527150959-749313264ce9/rpc/jsonrpc/types/types_test.go (about) 1 package types 2 3 import ( 4 "encoding/json" 5 "errors" 6 "fmt" 7 "testing" 8 9 "github.com/stretchr/testify/assert" 10 amino "github.com/tendermint/go-amino" 11 ) 12 13 type SampleResult struct { 14 Value string 15 } 16 17 type responseTest struct { 18 id jsonrpcid 19 expected string 20 } 21 22 var responseTests = []responseTest{ 23 {JSONRPCStringID("1"), `"1"`}, 24 {JSONRPCStringID("alphabet"), `"alphabet"`}, 25 {JSONRPCStringID(""), `""`}, 26 {JSONRPCStringID("àáâ"), `"àáâ"`}, 27 {JSONRPCIntID(-1), "-1"}, 28 {JSONRPCIntID(0), "0"}, 29 {JSONRPCIntID(1), "1"}, 30 {JSONRPCIntID(100), "100"}, 31 } 32 33 func TestResponses(t *testing.T) { 34 assert := assert.New(t) 35 cdc := amino.NewCodec() 36 for _, tt := range responseTests { 37 jsonid := tt.id 38 a := NewRPCSuccessResponse(cdc, jsonid, &SampleResult{"hello"}) 39 b, _ := json.Marshal(a) 40 s := fmt.Sprintf(`{"jsonrpc":"2.0","id":%v,"result":{"Value":"hello"}}`, tt.expected) 41 assert.Equal(s, string(b)) 42 43 d := RPCParseError(errors.New("hello world")) 44 e, _ := json.Marshal(d) 45 f := `{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error. Invalid JSON","data":"hello world"}}` 46 assert.Equal(f, string(e)) 47 48 g := RPCMethodNotFoundError(jsonid) 49 h, _ := json.Marshal(g) 50 i := fmt.Sprintf(`{"jsonrpc":"2.0","id":%v,"error":{"code":-32601,"message":"Method not found"}}`, tt.expected) 51 assert.Equal(string(h), i) 52 } 53 } 54 55 func TestUnmarshallResponses(t *testing.T) { 56 assert := assert.New(t) 57 cdc := amino.NewCodec() 58 for _, tt := range responseTests { 59 response := &RPCResponse{} 60 err := json.Unmarshal( 61 []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":%v,"result":{"Value":"hello"}}`, tt.expected)), 62 response, 63 ) 64 assert.Nil(err) 65 a := NewRPCSuccessResponse(cdc, tt.id, &SampleResult{"hello"}) 66 assert.Equal(*response, a) 67 } 68 response := &RPCResponse{} 69 err := json.Unmarshal([]byte(`{"jsonrpc":"2.0","id":true,"result":{"Value":"hello"}}`), response) 70 assert.NotNil(err) 71 } 72 73 func TestRPCError(t *testing.T) { 74 assert.Equal(t, "RPC error 12 - Badness: One worse than a code 11", 75 fmt.Sprintf("%v", &RPCError{ 76 Code: 12, 77 Message: "Badness", 78 Data: "One worse than a code 11", 79 })) 80 81 assert.Equal(t, "RPC error 12 - Badness", 82 fmt.Sprintf("%v", &RPCError{ 83 Code: 12, 84 Message: "Badness", 85 })) 86 }