This repository was archived by the owner on Oct 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 191
/
Copy pathrpc_test.go
94 lines (76 loc) · 1.79 KB
/
rpc_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package rpc
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"strings"
"testing"
"time"
"github.com/ethereum/go-ethereum/rpc"
"github.com/stretchr/testify/require"
)
type TestService struct{}
func (s *TestService) Foo(arg string) string {
return arg
}
func TestStartHTTPEndpointStartStop(t *testing.T) {
config := &Config{
RPCAddr: "127.0.0.1",
RPCPort: randomPort(),
}
ctx, cancel := context.WithCancel(context.Background())
_, err := StartHTTPEndpoint(
ctx, config, []rpc.API{
{
Namespace: "test",
Version: "1.0",
Service: &TestService{},
Public: true,
},
},
rpc.HTTPTimeouts{
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
IdleTimeout: 5 * time.Second,
},
)
require.Nil(t, err, "unexpected error")
res, err := rpcCall(config.RPCPort, "test_foo", []string{"baz"})
require.Nil(t, err, "unexpected error")
resStr := res.(string)
require.Equal(t, "baz", resStr)
cancel()
_, err = rpcCall(config.RPCPort, "test_foo", []string{"baz"})
require.NotNil(t, err)
}
func rpcCall(port int, method string, params []string) (interface{}, error) {
parsedParams, err := json.Marshal(params)
if err != nil {
return nil, err
}
fullBody := fmt.Sprintf(
`{ "id": 1, "jsonrpc": "2.0", "method": "%s", "params": %s }`,
method, string(parsedParams),
)
res, err := http.Post(fmt.Sprintf("http://127.0.0.1:%d", port), "application/json", strings.NewReader(fullBody))
if err != nil {
return nil, err
}
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var out map[string]interface{}
err = json.Unmarshal(data, &out)
if err != nil {
return nil, err
}
result := out["result"].(interface{})
return result, nil
}
func randomPort() int {
return rand.Intn(65535-1025) + 1025
}