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.

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