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.

383 lines
9.0 KiB

8 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
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 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. cl2, err := client.New(addr)
  233. require.Nil(t, err)
  234. fmt.Printf("=== testing server on %s using JSONRPC client", addr)
  235. testWithHTTPClient(ctx, t, cl2)
  236. cl3, err := client.NewWS(addr, websocketEndpoint)
  237. require.Nil(t, err)
  238. cl3.Logger = log.TestingLogger()
  239. err = cl3.Start(ctx)
  240. require.Nil(t, err)
  241. fmt.Printf("=== testing server on %s using WS client", addr)
  242. testWithWSClient(t, cl3)
  243. cancel()
  244. })
  245. }
  246. }
  247. func TestWSNewWSRPCFunc(t *testing.T) {
  248. ctx, cancel := context.WithCancel(context.Background())
  249. defer cancel()
  250. cl, err := client.NewWS(tcpAddr, websocketEndpoint)
  251. require.Nil(t, err)
  252. cl.Logger = log.TestingLogger()
  253. err = cl.Start(ctx)
  254. require.Nil(t, err)
  255. t.Cleanup(func() {
  256. if err := cl.Stop(); err != nil {
  257. t.Error(err)
  258. }
  259. })
  260. val := testVal
  261. params := map[string]interface{}{
  262. "arg": val,
  263. }
  264. err = cl.Call(context.Background(), "echo_ws", params)
  265. require.Nil(t, err)
  266. msg := <-cl.ResponsesCh
  267. if msg.Error != nil {
  268. t.Fatal(err)
  269. }
  270. result := new(ResultEcho)
  271. err = json.Unmarshal(msg.Result, result)
  272. require.Nil(t, err)
  273. got := result.Value
  274. assert.Equal(t, got, val)
  275. }
  276. func TestWSHandlesArrayParams(t *testing.T) {
  277. ctx, cancel := context.WithCancel(context.Background())
  278. defer cancel()
  279. cl, err := client.NewWS(tcpAddr, websocketEndpoint)
  280. require.Nil(t, err)
  281. cl.Logger = log.TestingLogger()
  282. require.Nil(t, cl.Start(ctx))
  283. t.Cleanup(func() {
  284. if err := cl.Stop(); err != nil {
  285. t.Error(err)
  286. }
  287. })
  288. val := testVal
  289. params := []interface{}{val}
  290. err = cl.CallWithArrayParams(context.Background(), "echo_ws", params)
  291. require.Nil(t, err)
  292. msg := <-cl.ResponsesCh
  293. if msg.Error != nil {
  294. t.Fatalf("%+v", err)
  295. }
  296. result := new(ResultEcho)
  297. err = json.Unmarshal(msg.Result, result)
  298. require.Nil(t, err)
  299. got := result.Value
  300. assert.Equal(t, got, val)
  301. }
  302. // TestWSClientPingPong checks that a client & server exchange pings
  303. // & pongs so connection stays alive.
  304. func TestWSClientPingPong(t *testing.T) {
  305. ctx, cancel := context.WithCancel(context.Background())
  306. defer cancel()
  307. cl, err := client.NewWS(tcpAddr, websocketEndpoint)
  308. require.Nil(t, err)
  309. cl.Logger = log.TestingLogger()
  310. err = cl.Start(ctx)
  311. require.Nil(t, err)
  312. t.Cleanup(func() {
  313. if err := cl.Stop(); err != nil {
  314. t.Error(err)
  315. }
  316. })
  317. time.Sleep(6 * time.Second)
  318. }
  319. func randBytes(t *testing.T) []byte {
  320. n := mrand.Intn(10) + 2
  321. buf := make([]byte, n)
  322. _, err := crand.Read(buf)
  323. require.Nil(t, err)
  324. return bytes.ReplaceAll(buf, []byte("="), []byte{100})
  325. }