You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

378 lines
8.8 KiB

8 years ago
7 years ago
7 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package rpc
  2. import (
  3. "bytes"
  4. "context"
  5. crand "crypto/rand"
  6. "encoding/json"
  7. "fmt"
  8. "math/rand"
  9. "net/http"
  10. "os"
  11. "os/exec"
  12. "testing"
  13. "time"
  14. "github.com/go-kit/kit/log/term"
  15. "github.com/stretchr/testify/assert"
  16. "github.com/stretchr/testify/require"
  17. amino "github.com/tendermint/go-amino"
  18. cmn "github.com/tendermint/tendermint/libs/common"
  19. "github.com/tendermint/tendermint/libs/log"
  20. client "github.com/tendermint/tendermint/rpc/lib/client"
  21. server "github.com/tendermint/tendermint/rpc/lib/server"
  22. types "github.com/tendermint/tendermint/rpc/lib/types"
  23. )
  24. // Client and Server should work over tcp or unix sockets
  25. const (
  26. tcpAddr = "tcp://0.0.0.0:47768"
  27. unixSocket = "/tmp/rpc_test.sock"
  28. unixAddr = "unix://" + unixSocket
  29. websocketEndpoint = "/websocket/endpoint"
  30. )
  31. type ResultEcho struct {
  32. Value string `json:"value"`
  33. }
  34. type ResultEchoInt struct {
  35. Value int `json:"value"`
  36. }
  37. type ResultEchoBytes struct {
  38. Value []byte `json:"value"`
  39. }
  40. type ResultEchoDataBytes struct {
  41. Value cmn.HexBytes `json:"value"`
  42. }
  43. // Define some routes
  44. var Routes = map[string]*server.RPCFunc{
  45. "echo": server.NewRPCFunc(EchoResult, "arg"),
  46. "echo_ws": server.NewWSRPCFunc(EchoWSResult, "arg"),
  47. "echo_bytes": server.NewRPCFunc(EchoBytesResult, "arg"),
  48. "echo_data_bytes": server.NewRPCFunc(EchoDataBytesResult, "arg"),
  49. "echo_int": server.NewRPCFunc(EchoIntResult, "arg"),
  50. }
  51. // Amino codec required to encode/decode everything above.
  52. var RoutesCdc = amino.NewCodec()
  53. func EchoResult(v string) (*ResultEcho, error) {
  54. return &ResultEcho{v}, nil
  55. }
  56. func EchoWSResult(wsCtx types.WSRPCContext, v string) (*ResultEcho, error) {
  57. return &ResultEcho{v}, nil
  58. }
  59. func EchoIntResult(v int) (*ResultEchoInt, error) {
  60. return &ResultEchoInt{v}, nil
  61. }
  62. func EchoBytesResult(v []byte) (*ResultEchoBytes, error) {
  63. return &ResultEchoBytes{v}, nil
  64. }
  65. func EchoDataBytesResult(v cmn.HexBytes) (*ResultEchoDataBytes, error) {
  66. return &ResultEchoDataBytes{v}, nil
  67. }
  68. func TestMain(m *testing.M) {
  69. setup()
  70. code := m.Run()
  71. os.Exit(code)
  72. }
  73. var colorFn = func(keyvals ...interface{}) term.FgBgColor {
  74. for i := 0; i < len(keyvals)-1; i += 2 {
  75. if keyvals[i] == "socket" {
  76. if keyvals[i+1] == "tcp" {
  77. return term.FgBgColor{Fg: term.DarkBlue}
  78. } else if keyvals[i+1] == "unix" {
  79. return term.FgBgColor{Fg: term.DarkCyan}
  80. }
  81. }
  82. }
  83. return term.FgBgColor{}
  84. }
  85. // launch unix and tcp servers
  86. func setup() {
  87. logger := log.NewTMLoggerWithColorFn(log.NewSyncWriter(os.Stdout), colorFn)
  88. cmd := exec.Command("rm", "-f", unixSocket)
  89. err := cmd.Start()
  90. if err != nil {
  91. panic(err)
  92. }
  93. if err = cmd.Wait(); err != nil {
  94. panic(err)
  95. }
  96. tcpLogger := logger.With("socket", "tcp")
  97. mux := http.NewServeMux()
  98. server.RegisterRPCFuncs(mux, Routes, RoutesCdc, tcpLogger)
  99. wm := server.NewWebsocketManager(Routes, RoutesCdc, server.ReadWait(5*time.Second), server.PingPeriod(1*time.Second))
  100. wm.SetLogger(tcpLogger)
  101. mux.HandleFunc(websocketEndpoint, wm.WebsocketHandler)
  102. go func() {
  103. _, err := server.StartHTTPServer(tcpAddr, mux, tcpLogger, server.Config{})
  104. if err != nil {
  105. panic(err)
  106. }
  107. }()
  108. unixLogger := logger.With("socket", "unix")
  109. mux2 := http.NewServeMux()
  110. server.RegisterRPCFuncs(mux2, Routes, RoutesCdc, unixLogger)
  111. wm = server.NewWebsocketManager(Routes, RoutesCdc)
  112. wm.SetLogger(unixLogger)
  113. mux2.HandleFunc(websocketEndpoint, wm.WebsocketHandler)
  114. go func() {
  115. _, err := server.StartHTTPServer(unixAddr, mux2, unixLogger, server.Config{})
  116. if err != nil {
  117. panic(err)
  118. }
  119. }()
  120. // wait for servers to start
  121. time.Sleep(time.Second * 2)
  122. }
  123. func echoViaHTTP(cl client.HTTPClient, val string) (string, error) {
  124. params := map[string]interface{}{
  125. "arg": val,
  126. }
  127. result := new(ResultEcho)
  128. if _, err := cl.Call("echo", params, result); err != nil {
  129. return "", err
  130. }
  131. return result.Value, nil
  132. }
  133. func echoIntViaHTTP(cl client.HTTPClient, val int) (int, error) {
  134. params := map[string]interface{}{
  135. "arg": val,
  136. }
  137. result := new(ResultEchoInt)
  138. if _, err := cl.Call("echo_int", params, result); err != nil {
  139. return 0, err
  140. }
  141. return result.Value, nil
  142. }
  143. func echoBytesViaHTTP(cl client.HTTPClient, bytes []byte) ([]byte, error) {
  144. params := map[string]interface{}{
  145. "arg": bytes,
  146. }
  147. result := new(ResultEchoBytes)
  148. if _, err := cl.Call("echo_bytes", params, result); err != nil {
  149. return []byte{}, err
  150. }
  151. return result.Value, nil
  152. }
  153. func echoDataBytesViaHTTP(cl client.HTTPClient, bytes cmn.HexBytes) (cmn.HexBytes, error) {
  154. params := map[string]interface{}{
  155. "arg": bytes,
  156. }
  157. result := new(ResultEchoDataBytes)
  158. if _, err := cl.Call("echo_data_bytes", params, result); err != nil {
  159. return []byte{}, err
  160. }
  161. return result.Value, nil
  162. }
  163. func testWithHTTPClient(t *testing.T, cl client.HTTPClient) {
  164. val := "acbd"
  165. got, err := echoViaHTTP(cl, val)
  166. require.Nil(t, err)
  167. assert.Equal(t, got, val)
  168. val2 := randBytes(t)
  169. got2, err := echoBytesViaHTTP(cl, val2)
  170. require.Nil(t, err)
  171. assert.Equal(t, got2, val2)
  172. val3 := cmn.HexBytes(randBytes(t))
  173. got3, err := echoDataBytesViaHTTP(cl, val3)
  174. require.Nil(t, err)
  175. assert.Equal(t, got3, val3)
  176. val4 := rand.Intn(10000)
  177. got4, err := echoIntViaHTTP(cl, val4)
  178. require.Nil(t, err)
  179. assert.Equal(t, got4, val4)
  180. }
  181. func echoViaWS(cl *client.WSClient, val string) (string, error) {
  182. params := map[string]interface{}{
  183. "arg": val,
  184. }
  185. err := cl.Call(context.Background(), "echo", params)
  186. if err != nil {
  187. return "", err
  188. }
  189. msg := <-cl.ResponsesCh
  190. if msg.Error != nil {
  191. return "", err
  192. }
  193. result := new(ResultEcho)
  194. err = json.Unmarshal(msg.Result, result)
  195. if err != nil {
  196. return "", nil
  197. }
  198. return result.Value, nil
  199. }
  200. func echoBytesViaWS(cl *client.WSClient, bytes []byte) ([]byte, error) {
  201. params := map[string]interface{}{
  202. "arg": bytes,
  203. }
  204. err := cl.Call(context.Background(), "echo_bytes", params)
  205. if err != nil {
  206. return []byte{}, err
  207. }
  208. msg := <-cl.ResponsesCh
  209. if msg.Error != nil {
  210. return []byte{}, msg.Error
  211. }
  212. result := new(ResultEchoBytes)
  213. err = json.Unmarshal(msg.Result, result)
  214. if err != nil {
  215. return []byte{}, nil
  216. }
  217. return result.Value, nil
  218. }
  219. func testWithWSClient(t *testing.T, cl *client.WSClient) {
  220. val := "acbd"
  221. got, err := echoViaWS(cl, val)
  222. require.Nil(t, err)
  223. assert.Equal(t, got, val)
  224. val2 := randBytes(t)
  225. got2, err := echoBytesViaWS(cl, val2)
  226. require.Nil(t, err)
  227. assert.Equal(t, got2, val2)
  228. }
  229. //-------------
  230. func TestServersAndClientsBasic(t *testing.T) {
  231. serverAddrs := [...]string{tcpAddr, unixAddr}
  232. for _, addr := range serverAddrs {
  233. cl1 := client.NewURIClient(addr)
  234. fmt.Printf("=== testing server on %s using URI client", addr)
  235. testWithHTTPClient(t, cl1)
  236. cl2 := client.NewJSONRPCClient(addr)
  237. fmt.Printf("=== testing server on %s using JSONRPC client", addr)
  238. testWithHTTPClient(t, cl2)
  239. cl3 := client.NewWSClient(addr, websocketEndpoint)
  240. cl3.SetLogger(log.TestingLogger())
  241. err := cl3.Start()
  242. require.Nil(t, err)
  243. fmt.Printf("=== testing server on %s using WS client", addr)
  244. testWithWSClient(t, cl3)
  245. cl3.Stop()
  246. }
  247. }
  248. func TestHexStringArg(t *testing.T) {
  249. cl := client.NewURIClient(tcpAddr)
  250. // should NOT be handled as hex
  251. val := "0xabc"
  252. got, err := echoViaHTTP(cl, val)
  253. require.Nil(t, err)
  254. assert.Equal(t, got, val)
  255. }
  256. func TestQuotedStringArg(t *testing.T) {
  257. cl := client.NewURIClient(tcpAddr)
  258. // should NOT be unquoted
  259. val := "\"abc\""
  260. got, err := echoViaHTTP(cl, val)
  261. require.Nil(t, err)
  262. assert.Equal(t, got, val)
  263. }
  264. func TestWSNewWSRPCFunc(t *testing.T) {
  265. cl := client.NewWSClient(tcpAddr, websocketEndpoint)
  266. cl.SetLogger(log.TestingLogger())
  267. err := cl.Start()
  268. require.Nil(t, err)
  269. defer cl.Stop()
  270. val := "acbd"
  271. params := map[string]interface{}{
  272. "arg": val,
  273. }
  274. err = cl.Call(context.Background(), "echo_ws", params)
  275. require.Nil(t, err)
  276. msg := <-cl.ResponsesCh
  277. if msg.Error != nil {
  278. t.Fatal(err)
  279. }
  280. result := new(ResultEcho)
  281. err = json.Unmarshal(msg.Result, result)
  282. require.Nil(t, err)
  283. got := result.Value
  284. assert.Equal(t, got, val)
  285. }
  286. func TestWSHandlesArrayParams(t *testing.T) {
  287. cl := client.NewWSClient(tcpAddr, websocketEndpoint)
  288. cl.SetLogger(log.TestingLogger())
  289. err := cl.Start()
  290. require.Nil(t, err)
  291. defer cl.Stop()
  292. val := "acbd"
  293. params := []interface{}{val}
  294. err = cl.CallWithArrayParams(context.Background(), "echo_ws", params)
  295. require.Nil(t, err)
  296. msg := <-cl.ResponsesCh
  297. if msg.Error != nil {
  298. t.Fatalf("%+v", err)
  299. }
  300. result := new(ResultEcho)
  301. err = json.Unmarshal(msg.Result, result)
  302. require.Nil(t, err)
  303. got := result.Value
  304. assert.Equal(t, got, val)
  305. }
  306. // TestWSClientPingPong checks that a client & server exchange pings
  307. // & pongs so connection stays alive.
  308. func TestWSClientPingPong(t *testing.T) {
  309. cl := client.NewWSClient(tcpAddr, websocketEndpoint)
  310. cl.SetLogger(log.TestingLogger())
  311. err := cl.Start()
  312. require.Nil(t, err)
  313. defer cl.Stop()
  314. time.Sleep(6 * time.Second)
  315. }
  316. func randBytes(t *testing.T) []byte {
  317. n := rand.Intn(10) + 2
  318. buf := make([]byte, n)
  319. _, err := crand.Read(buf)
  320. require.Nil(t, err)
  321. return bytes.Replace(buf, []byte("="), []byte{100}, -1)
  322. }