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.

393 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
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. var (
  31. ctx = context.Background()
  32. )
  33. type ResultEcho struct {
  34. Value string `json:"value"`
  35. }
  36. type ResultEchoInt struct {
  37. Value int `json:"value"`
  38. }
  39. type ResultEchoBytes struct {
  40. Value []byte `json:"value"`
  41. }
  42. type ResultEchoDataBytes struct {
  43. Value tmbytes.HexBytes `json:"value"`
  44. }
  45. // Define some routes
  46. var Routes = map[string]*server.RPCFunc{
  47. "echo": server.NewRPCFunc(EchoResult, "arg", false),
  48. "echo_ws": server.NewWSRPCFunc(EchoWSResult, "arg"),
  49. "echo_bytes": server.NewRPCFunc(EchoBytesResult, "arg", false),
  50. "echo_data_bytes": server.NewRPCFunc(EchoDataBytesResult, "arg", false),
  51. "echo_int": server.NewRPCFunc(EchoIntResult, "arg", false),
  52. }
  53. func EchoResult(ctx *rpctypes.Context, v string) (*ResultEcho, error) {
  54. return &ResultEcho{v}, nil
  55. }
  56. func EchoWSResult(ctx *rpctypes.Context, v string) (*ResultEcho, error) {
  57. return &ResultEcho{v}, nil
  58. }
  59. func EchoIntResult(ctx *rpctypes.Context, v int) (*ResultEchoInt, error) {
  60. return &ResultEchoInt{v}, nil
  61. }
  62. func EchoBytesResult(ctx *rpctypes.Context, v []byte) (*ResultEchoBytes, error) {
  63. return &ResultEchoBytes{v}, nil
  64. }
  65. func EchoDataBytesResult(ctx *rpctypes.Context, v tmbytes.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. // launch unix and tcp servers
  74. func setup() {
  75. logger := log.MustNewDefaultLogger(log.LogFormatPlain, log.LogLevelInfo, false)
  76. cmd := exec.Command("rm", "-f", unixSocket)
  77. err := cmd.Start()
  78. if err != nil {
  79. panic(err)
  80. }
  81. if err = cmd.Wait(); err != nil {
  82. panic(err)
  83. }
  84. tcpLogger := logger.With("socket", "tcp")
  85. mux := http.NewServeMux()
  86. server.RegisterRPCFuncs(mux, Routes, tcpLogger)
  87. wm := server.NewWebsocketManager(Routes, server.ReadWait(5*time.Second), server.PingPeriod(1*time.Second))
  88. wm.SetLogger(tcpLogger)
  89. mux.HandleFunc(websocketEndpoint, wm.WebsocketHandler)
  90. config := server.DefaultConfig()
  91. listener1, err := server.Listen(tcpAddr, config.MaxOpenConnections)
  92. if err != nil {
  93. panic(err)
  94. }
  95. go func() {
  96. if err := server.Serve(listener1, mux, tcpLogger, config); err != nil {
  97. panic(err)
  98. }
  99. }()
  100. unixLogger := logger.With("socket", "unix")
  101. mux2 := http.NewServeMux()
  102. server.RegisterRPCFuncs(mux2, Routes, unixLogger)
  103. wm = server.NewWebsocketManager(Routes)
  104. wm.SetLogger(unixLogger)
  105. mux2.HandleFunc(websocketEndpoint, wm.WebsocketHandler)
  106. listener2, err := server.Listen(unixAddr, config.MaxOpenConnections)
  107. if err != nil {
  108. panic(err)
  109. }
  110. go func() {
  111. if err := server.Serve(listener2, mux2, unixLogger, config); err != nil {
  112. panic(err)
  113. }
  114. }()
  115. // wait for servers to start
  116. time.Sleep(time.Second * 2)
  117. }
  118. func echoViaHTTP(cl client.Caller, val string) (string, error) {
  119. params := map[string]interface{}{
  120. "arg": val,
  121. }
  122. result := new(ResultEcho)
  123. if _, err := cl.Call(ctx, "echo", params, result); err != nil {
  124. return "", err
  125. }
  126. return result.Value, nil
  127. }
  128. func echoIntViaHTTP(cl client.Caller, val int) (int, error) {
  129. params := map[string]interface{}{
  130. "arg": val,
  131. }
  132. result := new(ResultEchoInt)
  133. if _, err := cl.Call(ctx, "echo_int", params, result); err != nil {
  134. return 0, err
  135. }
  136. return result.Value, nil
  137. }
  138. func echoBytesViaHTTP(cl client.Caller, bytes []byte) ([]byte, error) {
  139. params := map[string]interface{}{
  140. "arg": bytes,
  141. }
  142. result := new(ResultEchoBytes)
  143. if _, err := cl.Call(ctx, "echo_bytes", params, result); err != nil {
  144. return []byte{}, err
  145. }
  146. return result.Value, nil
  147. }
  148. func echoDataBytesViaHTTP(cl client.Caller, bytes tmbytes.HexBytes) (tmbytes.HexBytes, error) {
  149. params := map[string]interface{}{
  150. "arg": bytes,
  151. }
  152. result := new(ResultEchoDataBytes)
  153. if _, err := cl.Call(ctx, "echo_data_bytes", params, result); err != nil {
  154. return []byte{}, err
  155. }
  156. return result.Value, nil
  157. }
  158. func testWithHTTPClient(t *testing.T, cl client.HTTPClient) {
  159. val := testVal
  160. got, err := echoViaHTTP(cl, val)
  161. require.Nil(t, err)
  162. assert.Equal(t, got, val)
  163. val2 := randBytes(t)
  164. got2, err := echoBytesViaHTTP(cl, val2)
  165. require.Nil(t, err)
  166. assert.Equal(t, got2, val2)
  167. val3 := tmbytes.HexBytes(randBytes(t))
  168. got3, err := echoDataBytesViaHTTP(cl, val3)
  169. require.Nil(t, err)
  170. assert.Equal(t, got3, val3)
  171. val4 := mrand.Intn(10000)
  172. got4, err := echoIntViaHTTP(cl, val4)
  173. require.Nil(t, err)
  174. assert.Equal(t, got4, val4)
  175. }
  176. func echoViaWS(cl *client.WSClient, val string) (string, error) {
  177. params := map[string]interface{}{
  178. "arg": val,
  179. }
  180. err := cl.Call(context.Background(), "echo", params)
  181. if err != nil {
  182. return "", err
  183. }
  184. msg := <-cl.ResponsesCh
  185. if msg.Error != nil {
  186. return "", err
  187. }
  188. result := new(ResultEcho)
  189. err = json.Unmarshal(msg.Result, result)
  190. if err != nil {
  191. return "", nil
  192. }
  193. return result.Value, nil
  194. }
  195. func echoBytesViaWS(cl *client.WSClient, bytes []byte) ([]byte, error) {
  196. params := map[string]interface{}{
  197. "arg": bytes,
  198. }
  199. err := cl.Call(context.Background(), "echo_bytes", params)
  200. if err != nil {
  201. return []byte{}, err
  202. }
  203. msg := <-cl.ResponsesCh
  204. if msg.Error != nil {
  205. return []byte{}, msg.Error
  206. }
  207. result := new(ResultEchoBytes)
  208. err = json.Unmarshal(msg.Result, result)
  209. if err != nil {
  210. return []byte{}, nil
  211. }
  212. return result.Value, nil
  213. }
  214. func testWithWSClient(t *testing.T, cl *client.WSClient) {
  215. val := testVal
  216. got, err := echoViaWS(cl, val)
  217. require.Nil(t, err)
  218. assert.Equal(t, got, val)
  219. val2 := randBytes(t)
  220. got2, err := echoBytesViaWS(cl, val2)
  221. require.Nil(t, err)
  222. assert.Equal(t, got2, val2)
  223. }
  224. //-------------
  225. func TestServersAndClientsBasic(t *testing.T) {
  226. serverAddrs := [...]string{tcpAddr, unixAddr}
  227. for _, addr := range serverAddrs {
  228. cl1, err := client.NewURI(addr)
  229. require.Nil(t, err)
  230. fmt.Printf("=== testing server on %s using URI client", addr)
  231. testWithHTTPClient(t, cl1)
  232. cl2, err := client.New(addr)
  233. require.Nil(t, err)
  234. fmt.Printf("=== testing server on %s using JSONRPC client", addr)
  235. testWithHTTPClient(t, cl2)
  236. cl3, err := client.NewWS(addr, websocketEndpoint)
  237. require.Nil(t, err)
  238. cl3.SetLogger(log.TestingLogger())
  239. err = cl3.Start()
  240. require.Nil(t, err)
  241. fmt.Printf("=== testing server on %s using WS client", addr)
  242. testWithWSClient(t, cl3)
  243. err = cl3.Stop()
  244. require.NoError(t, err)
  245. }
  246. }
  247. func TestHexStringArg(t *testing.T) {
  248. cl, err := client.NewURI(tcpAddr)
  249. require.Nil(t, err)
  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, err := client.NewURI(tcpAddr)
  258. require.Nil(t, err)
  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, err := client.NewWS(tcpAddr, websocketEndpoint)
  267. require.Nil(t, err)
  268. cl.SetLogger(log.TestingLogger())
  269. err = cl.Start()
  270. require.Nil(t, err)
  271. t.Cleanup(func() {
  272. if err := cl.Stop(); err != nil {
  273. t.Error(err)
  274. }
  275. })
  276. val := testVal
  277. params := map[string]interface{}{
  278. "arg": val,
  279. }
  280. err = cl.Call(context.Background(), "echo_ws", params)
  281. require.Nil(t, err)
  282. msg := <-cl.ResponsesCh
  283. if msg.Error != nil {
  284. t.Fatal(err)
  285. }
  286. result := new(ResultEcho)
  287. err = json.Unmarshal(msg.Result, result)
  288. require.Nil(t, err)
  289. got := result.Value
  290. assert.Equal(t, got, val)
  291. }
  292. func TestWSHandlesArrayParams(t *testing.T) {
  293. cl, err := client.NewWS(tcpAddr, websocketEndpoint)
  294. require.Nil(t, err)
  295. cl.SetLogger(log.TestingLogger())
  296. err = cl.Start()
  297. require.Nil(t, err)
  298. t.Cleanup(func() {
  299. if err := cl.Stop(); err != nil {
  300. t.Error(err)
  301. }
  302. })
  303. val := testVal
  304. params := []interface{}{val}
  305. err = cl.CallWithArrayParams(context.Background(), "echo_ws", params)
  306. require.Nil(t, err)
  307. msg := <-cl.ResponsesCh
  308. if msg.Error != nil {
  309. t.Fatalf("%+v", err)
  310. }
  311. result := new(ResultEcho)
  312. err = json.Unmarshal(msg.Result, result)
  313. require.Nil(t, err)
  314. got := result.Value
  315. assert.Equal(t, got, val)
  316. }
  317. // TestWSClientPingPong checks that a client & server exchange pings
  318. // & pongs so connection stays alive.
  319. func TestWSClientPingPong(t *testing.T) {
  320. cl, err := client.NewWS(tcpAddr, websocketEndpoint)
  321. require.Nil(t, err)
  322. cl.SetLogger(log.TestingLogger())
  323. err = cl.Start()
  324. require.Nil(t, err)
  325. t.Cleanup(func() {
  326. if err := cl.Stop(); err != nil {
  327. t.Error(err)
  328. }
  329. })
  330. time.Sleep(6 * time.Second)
  331. }
  332. func randBytes(t *testing.T) []byte {
  333. n := mrand.Intn(10) + 2
  334. buf := make([]byte, n)
  335. _, err := crand.Read(buf)
  336. require.Nil(t, err)
  337. return bytes.ReplaceAll(buf, []byte("="), []byte{100})
  338. }