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