github.com/hyperledger/burrow@v0.34.5-0.20220512172541-77f09336001d/rpc/lib/types/types_test.go (about)

     1  package types
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"testing"
     7  
     8  	"github.com/stretchr/testify/require"
     9  
    10  	"github.com/pkg/errors"
    11  	"github.com/stretchr/testify/assert"
    12  )
    13  
    14  type SampleResult struct {
    15  	Value string
    16  }
    17  
    18  func TestResponses(t *testing.T) {
    19  	assert := assert.New(t)
    20  
    21  	a := NewRPCSuccessResponse("1", &SampleResult{"hello"})
    22  	b, _ := json.Marshal(a)
    23  	s := `{"jsonrpc":"2.0","id":"1","result":{"Value":"hello"}}`
    24  	assert.Equal(string(s), string(b))
    25  
    26  	d := RPCParseError("1", errors.New("Hello world"))
    27  	e, _ := json.Marshal(d)
    28  	f := `{"jsonrpc":"2.0","id":"1","error":{"code":-32700,"message":"Parse Error","data":"Hello world"}}`
    29  	assert.Equal(string(f), string(e))
    30  
    31  	g := RPCMethodNotFoundError("2")
    32  	h, _ := json.Marshal(g)
    33  	i := `{"jsonrpc":"2.0","id":"2","error":{"code":-32601,"message":"Method Not Found"}}`
    34  	assert.Equal(i, string(h))
    35  }
    36  
    37  func TestRequests(t *testing.T) {
    38  	// Make sure empty params omitted
    39  	req := NewRPCRequest("foo", "NoParamsMethod", nil)
    40  	bs, err := json.Marshal(req)
    41  	require.NoError(t, err)
    42  	require.Equal(t, `{"jsonrpc":"2.0","id":"foo","method":"NoParamsMethod"}`, string(bs))
    43  }
    44  
    45  func TestRPCError(t *testing.T) {
    46  	assert.Equal(t, `Unknown Error 12 - Badness: "One worse than a code 11"`,
    47  		fmt.Sprintf("%v", &RPCError{
    48  			Code:    12,
    49  			Message: "Badness",
    50  			Data:    raw("One worse than a code 11"),
    51  		}))
    52  
    53  	assert.Equal(t, "Unknown Error 12 - Badness",
    54  		fmt.Sprintf("%v", &RPCError{
    55  			Code:    12,
    56  			Message: "Badness",
    57  		}))
    58  }
    59  
    60  func raw(v interface{}) json.RawMessage {
    61  	bs, err := json.MarshalIndent(v, "", "\t")
    62  	if err != nil {
    63  		panic(err)
    64  	}
    65  	return bs
    66  }