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.

381 lines
8.7 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 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. "github.com/tendermint/go-wire/data"
  18. client "github.com/tendermint/tendermint/rpc/lib/client"
  19. server "github.com/tendermint/tendermint/rpc/lib/server"
  20. types "github.com/tendermint/tendermint/rpc/lib/types"
  21. "github.com/tendermint/tmlibs/log"
  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 data.Bytes `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. func EchoResult(v string) (*ResultEcho, error) {
  51. return &ResultEcho{v}, nil
  52. }
  53. func EchoWSResult(wsCtx types.WSRPCContext, v string) (*ResultEcho, error) {
  54. return &ResultEcho{v}, nil
  55. }
  56. func EchoIntResult(v int) (*ResultEchoInt, error) {
  57. return &ResultEchoInt{v}, nil
  58. }
  59. func EchoBytesResult(v []byte) (*ResultEchoBytes, error) {
  60. return &ResultEchoBytes{v}, nil
  61. }
  62. func EchoDataBytesResult(v data.Bytes) (*ResultEchoDataBytes, error) {
  63. return &ResultEchoDataBytes{v}, nil
  64. }
  65. func TestMain(m *testing.M) {
  66. setup()
  67. code := m.Run()
  68. os.Exit(code)
  69. }
  70. var colorFn = func(keyvals ...interface{}) term.FgBgColor {
  71. for i := 0; i < len(keyvals)-1; i += 2 {
  72. if keyvals[i] == "socket" {
  73. if keyvals[i+1] == "tcp" {
  74. return term.FgBgColor{Fg: term.DarkBlue}
  75. } else if keyvals[i+1] == "unix" {
  76. return term.FgBgColor{Fg: term.DarkCyan}
  77. }
  78. }
  79. }
  80. return term.FgBgColor{}
  81. }
  82. // launch unix and tcp servers
  83. func setup() {
  84. logger := log.NewTMLoggerWithColorFn(log.NewSyncWriter(os.Stdout), colorFn)
  85. cmd := exec.Command("rm", "-f", unixSocket)
  86. err := cmd.Start()
  87. if err != nil {
  88. panic(err)
  89. }
  90. if err = cmd.Wait(); err != nil {
  91. panic(err)
  92. }
  93. tcpLogger := logger.With("socket", "tcp")
  94. mux := http.NewServeMux()
  95. server.RegisterRPCFuncs(mux, Routes, tcpLogger)
  96. wm := server.NewWebsocketManager(Routes, nil, server.ReadWait(5*time.Second), server.PingPeriod(1*time.Second))
  97. wm.SetLogger(tcpLogger)
  98. mux.HandleFunc(websocketEndpoint, wm.WebsocketHandler)
  99. go func() {
  100. _, err := server.StartHTTPServer(tcpAddr, mux, tcpLogger)
  101. if err != nil {
  102. panic(err)
  103. }
  104. }()
  105. unixLogger := logger.With("socket", "unix")
  106. mux2 := http.NewServeMux()
  107. server.RegisterRPCFuncs(mux2, Routes, unixLogger)
  108. wm = server.NewWebsocketManager(Routes, nil)
  109. wm.SetLogger(unixLogger)
  110. mux2.HandleFunc(websocketEndpoint, wm.WebsocketHandler)
  111. go func() {
  112. _, err := server.StartHTTPServer(unixAddr, mux2, unixLogger)
  113. if err != nil {
  114. panic(err)
  115. }
  116. }()
  117. // wait for servers to start
  118. time.Sleep(time.Second * 2)
  119. }
  120. func echoViaHTTP(cl client.HTTPClient, val string) (string, error) {
  121. params := map[string]interface{}{
  122. "arg": val,
  123. }
  124. result := new(ResultEcho)
  125. if _, err := cl.Call("echo", params, result); err != nil {
  126. return "", err
  127. }
  128. return result.Value, nil
  129. }
  130. func echoIntViaHTTP(cl client.HTTPClient, val int) (int, error) {
  131. params := map[string]interface{}{
  132. "arg": val,
  133. }
  134. result := new(ResultEchoInt)
  135. if _, err := cl.Call("echo_int", params, result); err != nil {
  136. return 0, err
  137. }
  138. return result.Value, nil
  139. }
  140. func echoBytesViaHTTP(cl client.HTTPClient, bytes []byte) ([]byte, error) {
  141. params := map[string]interface{}{
  142. "arg": bytes,
  143. }
  144. result := new(ResultEchoBytes)
  145. if _, err := cl.Call("echo_bytes", params, result); err != nil {
  146. return []byte{}, err
  147. }
  148. return result.Value, nil
  149. }
  150. func echoDataBytesViaHTTP(cl client.HTTPClient, bytes data.Bytes) (data.Bytes, error) {
  151. params := map[string]interface{}{
  152. "arg": bytes,
  153. }
  154. result := new(ResultEchoDataBytes)
  155. if _, err := cl.Call("echo_data_bytes", params, result); err != nil {
  156. return []byte{}, err
  157. }
  158. return result.Value, nil
  159. }
  160. func testWithHTTPClient(t *testing.T, cl client.HTTPClient) {
  161. val := "acbd"
  162. got, err := echoViaHTTP(cl, val)
  163. require.Nil(t, err)
  164. assert.Equal(t, got, val)
  165. val2 := randBytes(t)
  166. got2, err := echoBytesViaHTTP(cl, val2)
  167. require.Nil(t, err)
  168. assert.Equal(t, got2, val2)
  169. val3 := data.Bytes(randBytes(t))
  170. got3, err := echoDataBytesViaHTTP(cl, val3)
  171. require.Nil(t, err)
  172. assert.Equal(t, got3, val3)
  173. val4 := rand.Intn(10000)
  174. got4, err := echoIntViaHTTP(cl, val4)
  175. require.Nil(t, err)
  176. assert.Equal(t, got4, val4)
  177. }
  178. func echoViaWS(cl *client.WSClient, val string) (string, error) {
  179. params := map[string]interface{}{
  180. "arg": val,
  181. }
  182. err := cl.Call(context.Background(), "echo", params)
  183. if err != nil {
  184. return "", err
  185. }
  186. select {
  187. case msg := <-cl.ResponsesCh:
  188. if msg.Error != nil {
  189. return "", err
  190. }
  191. result := new(ResultEcho)
  192. err = json.Unmarshal(*msg.Result, result)
  193. if err != nil {
  194. return "", nil
  195. }
  196. return result.Value, nil
  197. }
  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. select {
  208. case 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. }
  220. func testWithWSClient(t *testing.T, cl *client.WSClient) {
  221. val := "acbd"
  222. got, err := echoViaWS(cl, val)
  223. require.Nil(t, err)
  224. assert.Equal(t, got, val)
  225. val2 := randBytes(t)
  226. got2, err := echoBytesViaWS(cl, val2)
  227. require.Nil(t, err)
  228. assert.Equal(t, got2, val2)
  229. }
  230. //-------------
  231. func TestServersAndClientsBasic(t *testing.T) {
  232. serverAddrs := [...]string{tcpAddr, unixAddr}
  233. for _, addr := range serverAddrs {
  234. cl1 := client.NewURIClient(addr)
  235. fmt.Printf("=== testing server on %s using %v client", addr, cl1)
  236. testWithHTTPClient(t, cl1)
  237. cl2 := client.NewJSONRPCClient(addr)
  238. fmt.Printf("=== testing server on %s using %v client", addr, cl2)
  239. testWithHTTPClient(t, cl2)
  240. cl3 := client.NewWSClient(addr, websocketEndpoint)
  241. cl3.SetLogger(log.TestingLogger())
  242. _, err := cl3.Start()
  243. require.Nil(t, err)
  244. fmt.Printf("=== testing server on %s using %v client", addr, cl3)
  245. testWithWSClient(t, cl3)
  246. cl3.Stop()
  247. }
  248. }
  249. func TestHexStringArg(t *testing.T) {
  250. cl := client.NewURIClient(tcpAddr)
  251. // should NOT be handled as hex
  252. val := "0xabc"
  253. got, err := echoViaHTTP(cl, val)
  254. require.Nil(t, err)
  255. assert.Equal(t, got, val)
  256. }
  257. func TestQuotedStringArg(t *testing.T) {
  258. cl := client.NewURIClient(tcpAddr)
  259. // should NOT be unquoted
  260. val := "\"abc\""
  261. got, err := echoViaHTTP(cl, val)
  262. require.Nil(t, err)
  263. assert.Equal(t, got, val)
  264. }
  265. func TestWSNewWSRPCFunc(t *testing.T) {
  266. cl := client.NewWSClient(tcpAddr, websocketEndpoint)
  267. cl.SetLogger(log.TestingLogger())
  268. _, err := cl.Start()
  269. require.Nil(t, err)
  270. defer cl.Stop()
  271. val := "acbd"
  272. params := map[string]interface{}{
  273. "arg": val,
  274. }
  275. err = cl.Call(context.Background(), "echo_ws", params)
  276. require.Nil(t, err)
  277. select {
  278. case msg := <-cl.ResponsesCh:
  279. if msg.Error != nil {
  280. t.Fatal(err)
  281. }
  282. result := new(ResultEcho)
  283. err = json.Unmarshal(*msg.Result, result)
  284. require.Nil(t, err)
  285. got := result.Value
  286. assert.Equal(t, got, val)
  287. }
  288. }
  289. func TestWSHandlesArrayParams(t *testing.T) {
  290. cl := client.NewWSClient(tcpAddr, websocketEndpoint)
  291. cl.SetLogger(log.TestingLogger())
  292. _, err := cl.Start()
  293. require.Nil(t, err)
  294. defer cl.Stop()
  295. val := "acbd"
  296. params := []interface{}{val}
  297. err = cl.CallWithArrayParams(context.Background(), "echo_ws", params)
  298. require.Nil(t, err)
  299. select {
  300. case msg := <-cl.ResponsesCh:
  301. if msg.Error != nil {
  302. t.Fatalf("%+v", err)
  303. }
  304. result := new(ResultEcho)
  305. err = json.Unmarshal(*msg.Result, result)
  306. require.Nil(t, err)
  307. got := result.Value
  308. assert.Equal(t, got, val)
  309. }
  310. }
  311. // TestWSClientPingPong checks that a client & server exchange pings
  312. // & pongs so connection stays alive.
  313. func TestWSClientPingPong(t *testing.T) {
  314. cl := client.NewWSClient(tcpAddr, websocketEndpoint)
  315. cl.SetLogger(log.TestingLogger())
  316. _, err := cl.Start()
  317. require.Nil(t, err)
  318. defer cl.Stop()
  319. time.Sleep(6 * time.Second)
  320. }
  321. func randBytes(t *testing.T) []byte {
  322. n := rand.Intn(10) + 2
  323. buf := make([]byte, n)
  324. _, err := crand.Read(buf)
  325. require.Nil(t, err)
  326. return bytes.Replace(buf, []byte("="), []byte{100}, -1)
  327. }