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