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.

385 lines
9.1 KiB

7 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package jsonrpc
  2. import (
  3. "bytes"
  4. "context"
  5. crand "crypto/rand"
  6. "encoding/json"
  7. "fmt"
  8. mrand "math/rand"
  9. "net/http"
  10. "os"
  11. "os/exec"
  12. "testing"
  13. "time"
  14. "github.com/stretchr/testify/assert"
  15. "github.com/stretchr/testify/require"
  16. tmbytes "github.com/tendermint/tendermint/libs/bytes"
  17. "github.com/tendermint/tendermint/libs/log"
  18. "github.com/tendermint/tendermint/rpc/jsonrpc/client"
  19. "github.com/tendermint/tendermint/rpc/jsonrpc/server"
  20. rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
  21. )
  22. // Client and Server should work over tcp or unix sockets
  23. const (
  24. tcpAddr = "tcp://127.0.0.1:47768"
  25. unixSocket = "/tmp/rpc_test.sock"
  26. unixAddr = "unix://" + unixSocket
  27. websocketEndpoint = "/websocket/endpoint"
  28. testVal = "acbd"
  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 tmbytes.HexBytes `json:"value"`
  41. }
  42. // Define some routes
  43. var Routes = map[string]*server.RPCFunc{
  44. "echo": server.NewRPCFunc(EchoResult, "arg", false),
  45. "echo_ws": server.NewWSRPCFunc(EchoWSResult, "arg"),
  46. "echo_bytes": server.NewRPCFunc(EchoBytesResult, "arg", false),
  47. "echo_data_bytes": server.NewRPCFunc(EchoDataBytesResult, "arg", false),
  48. "echo_int": server.NewRPCFunc(EchoIntResult, "arg", false),
  49. }
  50. func EchoResult(ctx *rpctypes.Context, v string) (*ResultEcho, error) {
  51. return &ResultEcho{v}, nil
  52. }
  53. func EchoWSResult(ctx *rpctypes.Context, v string) (*ResultEcho, error) {
  54. return &ResultEcho{v}, nil
  55. }
  56. func EchoIntResult(ctx *rpctypes.Context, v int) (*ResultEchoInt, error) {
  57. return &ResultEchoInt{v}, nil
  58. }
  59. func EchoBytesResult(ctx *rpctypes.Context, v []byte) (*ResultEchoBytes, error) {
  60. return &ResultEchoBytes{v}, nil
  61. }
  62. func EchoDataBytesResult(ctx *rpctypes.Context, v tmbytes.HexBytes) (*ResultEchoDataBytes, error) {
  63. return &ResultEchoDataBytes{v}, nil
  64. }
  65. func TestMain(m *testing.M) {
  66. ctx, cancel := context.WithCancel(context.Background())
  67. defer cancel()
  68. setup(ctx)
  69. code := m.Run()
  70. os.Exit(code)
  71. }
  72. // launch unix and tcp servers
  73. func setup(ctx context.Context) {
  74. logger := log.MustNewDefaultLogger(log.LogFormatPlain, log.LogLevelInfo, false)
  75. cmd := exec.Command("rm", "-f", unixSocket)
  76. err := cmd.Start()
  77. if err != nil {
  78. panic(err)
  79. }
  80. if err = cmd.Wait(); err != nil {
  81. panic(err)
  82. }
  83. tcpLogger := logger.With("socket", "tcp")
  84. mux := http.NewServeMux()
  85. server.RegisterRPCFuncs(mux, Routes, tcpLogger)
  86. wm := server.NewWebsocketManager(Routes, server.ReadWait(5*time.Second), server.PingPeriod(1*time.Second))
  87. wm.SetLogger(tcpLogger)
  88. mux.HandleFunc(websocketEndpoint, wm.WebsocketHandler)
  89. config := server.DefaultConfig()
  90. listener1, err := server.Listen(tcpAddr, config.MaxOpenConnections)
  91. if err != nil {
  92. panic(err)
  93. }
  94. go func() {
  95. if err := server.Serve(ctx, listener1, mux, tcpLogger, config); err != nil {
  96. panic(err)
  97. }
  98. }()
  99. unixLogger := logger.With("socket", "unix")
  100. mux2 := http.NewServeMux()
  101. server.RegisterRPCFuncs(mux2, Routes, unixLogger)
  102. wm = server.NewWebsocketManager(Routes)
  103. wm.SetLogger(unixLogger)
  104. mux2.HandleFunc(websocketEndpoint, wm.WebsocketHandler)
  105. listener2, err := server.Listen(unixAddr, config.MaxOpenConnections)
  106. if err != nil {
  107. panic(err)
  108. }
  109. go func() {
  110. if err := server.Serve(ctx, listener2, mux2, unixLogger, config); err != nil {
  111. panic(err)
  112. }
  113. }()
  114. // wait for servers to start
  115. time.Sleep(time.Second * 2)
  116. }
  117. func echoViaHTTP(ctx context.Context, cl client.Caller, val string) (string, error) {
  118. params := map[string]interface{}{
  119. "arg": val,
  120. }
  121. result := new(ResultEcho)
  122. if _, err := cl.Call(ctx, "echo", params, result); err != nil {
  123. return "", err
  124. }
  125. return result.Value, nil
  126. }
  127. func echoIntViaHTTP(ctx context.Context, cl client.Caller, val int) (int, error) {
  128. params := map[string]interface{}{
  129. "arg": val,
  130. }
  131. result := new(ResultEchoInt)
  132. if _, err := cl.Call(ctx, "echo_int", params, result); err != nil {
  133. return 0, err
  134. }
  135. return result.Value, nil
  136. }
  137. func echoBytesViaHTTP(ctx context.Context, cl client.Caller, bytes []byte) ([]byte, error) {
  138. params := map[string]interface{}{
  139. "arg": bytes,
  140. }
  141. result := new(ResultEchoBytes)
  142. if _, err := cl.Call(ctx, "echo_bytes", params, result); err != nil {
  143. return []byte{}, err
  144. }
  145. return result.Value, nil
  146. }
  147. func echoDataBytesViaHTTP(ctx context.Context, cl client.Caller, bytes tmbytes.HexBytes) (tmbytes.HexBytes, error) {
  148. params := map[string]interface{}{
  149. "arg": bytes,
  150. }
  151. result := new(ResultEchoDataBytes)
  152. if _, err := cl.Call(ctx, "echo_data_bytes", params, result); err != nil {
  153. return []byte{}, err
  154. }
  155. return result.Value, nil
  156. }
  157. func testWithHTTPClient(ctx context.Context, t *testing.T, cl client.HTTPClient) {
  158. val := testVal
  159. got, err := echoViaHTTP(ctx, cl, val)
  160. require.Nil(t, err)
  161. assert.Equal(t, got, val)
  162. val2 := randBytes(t)
  163. got2, err := echoBytesViaHTTP(ctx, cl, val2)
  164. require.Nil(t, err)
  165. assert.Equal(t, got2, val2)
  166. val3 := tmbytes.HexBytes(randBytes(t))
  167. got3, err := echoDataBytesViaHTTP(ctx, cl, val3)
  168. require.Nil(t, err)
  169. assert.Equal(t, got3, val3)
  170. val4 := mrand.Intn(10000)
  171. got4, err := echoIntViaHTTP(ctx, cl, val4)
  172. require.Nil(t, err)
  173. assert.Equal(t, got4, val4)
  174. }
  175. func echoViaWS(cl *client.WSClient, val string) (string, error) {
  176. params := map[string]interface{}{
  177. "arg": val,
  178. }
  179. err := cl.Call(context.Background(), "echo", params)
  180. if err != nil {
  181. return "", err
  182. }
  183. msg := <-cl.ResponsesCh
  184. if msg.Error != nil {
  185. return "", err
  186. }
  187. result := new(ResultEcho)
  188. err = json.Unmarshal(msg.Result, result)
  189. if err != nil {
  190. return "", nil
  191. }
  192. return result.Value, nil
  193. }
  194. func echoBytesViaWS(cl *client.WSClient, bytes []byte) ([]byte, error) {
  195. params := map[string]interface{}{
  196. "arg": bytes,
  197. }
  198. err := cl.Call(context.Background(), "echo_bytes", params)
  199. if err != nil {
  200. return []byte{}, err
  201. }
  202. msg := <-cl.ResponsesCh
  203. if msg.Error != nil {
  204. return []byte{}, msg.Error
  205. }
  206. result := new(ResultEchoBytes)
  207. err = json.Unmarshal(msg.Result, result)
  208. if err != nil {
  209. return []byte{}, nil
  210. }
  211. return result.Value, nil
  212. }
  213. func testWithWSClient(t *testing.T, cl *client.WSClient) {
  214. val := testVal
  215. got, err := echoViaWS(cl, val)
  216. require.Nil(t, err)
  217. assert.Equal(t, got, val)
  218. val2 := randBytes(t)
  219. got2, err := echoBytesViaWS(cl, val2)
  220. require.Nil(t, err)
  221. assert.Equal(t, got2, val2)
  222. }
  223. //-------------
  224. func TestServersAndClientsBasic(t *testing.T) {
  225. bctx, cancel := context.WithCancel(context.Background())
  226. defer cancel()
  227. serverAddrs := [...]string{tcpAddr, unixAddr}
  228. for _, addr := range serverAddrs {
  229. t.Run(addr, func(t *testing.T) {
  230. ctx, cancel := context.WithCancel(bctx)
  231. defer cancel()
  232. logger := log.NewTestingLogger(t)
  233. cl2, err := client.New(addr)
  234. require.Nil(t, err)
  235. fmt.Printf("=== testing server on %s using JSONRPC client", addr)
  236. testWithHTTPClient(ctx, t, cl2)
  237. cl3, err := client.NewWS(addr, websocketEndpoint)
  238. require.Nil(t, err)
  239. cl3.Logger = logger
  240. err = cl3.Start(ctx)
  241. require.Nil(t, err)
  242. fmt.Printf("=== testing server on %s using WS client", addr)
  243. testWithWSClient(t, cl3)
  244. cancel()
  245. })
  246. }
  247. }
  248. func TestWSNewWSRPCFunc(t *testing.T) {
  249. ctx, cancel := context.WithCancel(context.Background())
  250. defer cancel()
  251. cl, err := client.NewWS(tcpAddr, websocketEndpoint)
  252. require.Nil(t, err)
  253. cl.Logger = log.NewTestingLogger(t)
  254. err = cl.Start(ctx)
  255. require.Nil(t, err)
  256. t.Cleanup(func() {
  257. if err := cl.Stop(); err != nil {
  258. t.Error(err)
  259. }
  260. })
  261. val := testVal
  262. params := map[string]interface{}{
  263. "arg": val,
  264. }
  265. err = cl.Call(context.Background(), "echo_ws", params)
  266. require.Nil(t, err)
  267. msg := <-cl.ResponsesCh
  268. if msg.Error != nil {
  269. t.Fatal(err)
  270. }
  271. result := new(ResultEcho)
  272. err = json.Unmarshal(msg.Result, result)
  273. require.Nil(t, err)
  274. got := result.Value
  275. assert.Equal(t, got, val)
  276. }
  277. func TestWSHandlesArrayParams(t *testing.T) {
  278. ctx, cancel := context.WithCancel(context.Background())
  279. defer cancel()
  280. cl, err := client.NewWS(tcpAddr, websocketEndpoint)
  281. require.Nil(t, err)
  282. cl.Logger = log.NewTestingLogger(t)
  283. require.Nil(t, cl.Start(ctx))
  284. t.Cleanup(func() {
  285. if err := cl.Stop(); err != nil {
  286. t.Error(err)
  287. }
  288. })
  289. val := testVal
  290. params := []interface{}{val}
  291. err = cl.CallWithArrayParams(context.Background(), "echo_ws", params)
  292. require.Nil(t, err)
  293. msg := <-cl.ResponsesCh
  294. if msg.Error != nil {
  295. t.Fatalf("%+v", err)
  296. }
  297. result := new(ResultEcho)
  298. err = json.Unmarshal(msg.Result, result)
  299. require.Nil(t, err)
  300. got := result.Value
  301. assert.Equal(t, got, val)
  302. }
  303. // TestWSClientPingPong checks that a client & server exchange pings
  304. // & pongs so connection stays alive.
  305. func TestWSClientPingPong(t *testing.T) {
  306. ctx, cancel := context.WithCancel(context.Background())
  307. defer cancel()
  308. cl, err := client.NewWS(tcpAddr, websocketEndpoint)
  309. require.Nil(t, err)
  310. cl.Logger = log.NewTestingLogger(t)
  311. err = cl.Start(ctx)
  312. require.Nil(t, err)
  313. t.Cleanup(func() {
  314. if err := cl.Stop(); err != nil {
  315. t.Error(err)
  316. }
  317. })
  318. time.Sleep(6 * time.Second)
  319. }
  320. func randBytes(t *testing.T) []byte {
  321. n := mrand.Intn(10) + 2
  322. buf := make([]byte, n)
  323. _, err := crand.Read(buf)
  324. require.Nil(t, err)
  325. return bytes.ReplaceAll(buf, []byte("="), []byte{100})
  326. }