예제 #1
0
파일: jsonrpc_test.go 프로젝트: chrjen/btcd
// TestMiscErrors tests a few error conditions not covered elsewhere.
func TestMiscErrors(t *testing.T) {
	t.Parallel()

	// Force an error in NewRequest by giving it a parameter type that is
	// not supported.
	_, err := btcjson.NewRequest(nil, "test", []interface{}{make(chan int)})
	if err == nil {
		t.Error("NewRequest: did not receive error")
		return
	}

	// Force an error in MarshalResponse by giving it an id type that is not
	// supported.
	wantErr := btcjson.Error{ErrorCode: btcjson.ErrInvalidType}
	_, err = btcjson.MarshalResponse(make(chan int), nil, nil)
	if jerr, ok := err.(btcjson.Error); !ok || jerr.ErrorCode != wantErr.ErrorCode {
		t.Errorf("MarshalResult: did not receive expected error - got "+
			"%v (%[1]T), want %v (%[2]T)", err, wantErr)
		return
	}

	// Force an error in MarshalResponse by giving it a result type that
	// can't be marshalled.
	_, err = btcjson.MarshalResponse(1, make(chan int), nil)
	if _, ok := err.(*json.UnsupportedTypeError); !ok {
		wantErr := &json.UnsupportedTypeError{}
		t.Errorf("MarshalResult: did not receive expected error - got "+
			"%v (%[1]T), want %T", err, wantErr)
		return
	}
}
예제 #2
0
파일: example_test.go 프로젝트: chrjen/btcd
// This example demonstrates how to marshal a JSON-RPC response.
func ExampleMarshalResponse() {
	// Marshal a new JSON-RPC response.  For example, this is a response
	// to a getblockheight request.
	marshalledBytes, err := btcjson.MarshalResponse(1, 350001, nil)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Display the marshalled response.  Ordinarily this would be sent
	// across the wire to the RPC client, but for this example, just display
	// it.
	fmt.Printf("%s\n", marshalledBytes)

	// Output:
	// {"result":350001,"error":null,"id":1}
}
예제 #3
0
파일: jsonrpc_test.go 프로젝트: chrjen/btcd
// TestMarshalResponse ensures the MarshalResponse function works as expected.
func TestMarshalResponse(t *testing.T) {
	t.Parallel()

	testID := 1
	tests := []struct {
		name     string
		result   interface{}
		jsonErr  *btcjson.RPCError
		expected []byte
	}{
		{
			name:     "ordinary bool result with no error",
			result:   true,
			jsonErr:  nil,
			expected: []byte(`{"result":true,"error":null,"id":1}`),
		},
		{
			name:   "result with error",
			result: nil,
			jsonErr: func() *btcjson.RPCError {
				return btcjson.NewRPCError(btcjson.ErrRPCBlockNotFound, "123 not found")
			}(),
			expected: []byte(`{"result":null,"error":{"code":-5,"message":"123 not found"},"id":1}`),
		},
	}

	t.Logf("Running %d tests", len(tests))
	for i, test := range tests {
		_, _ = i, test
		marshalled, err := btcjson.MarshalResponse(testID, test.result, test.jsonErr)
		if err != nil {
			t.Errorf("Test #%d (%s) unexpected error: %v", i,
				test.name, err)
			continue
		}

		if !reflect.DeepEqual(marshalled, test.expected) {
			t.Errorf("Test #%d (%s) mismatched result - got %s, "+
				"want %s", i, test.name, marshalled,
				test.expected)
		}
	}
}