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.

174 lines
4.4 KiB

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
  1. package server
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net"
  9. "net/http"
  10. "net/http/httptest"
  11. "sync"
  12. "sync/atomic"
  13. "testing"
  14. "time"
  15. "github.com/fortytw2/leaktest"
  16. "github.com/stretchr/testify/assert"
  17. "github.com/stretchr/testify/require"
  18. "github.com/tendermint/tendermint/libs/log"
  19. rpctypes "github.com/tendermint/tendermint/rpc/jsonrpc/types"
  20. )
  21. type sampleResult struct {
  22. Value string `json:"value"`
  23. }
  24. func TestMaxOpenConnections(t *testing.T) {
  25. const max = 5 // max simultaneous connections
  26. t.Cleanup(leaktest.Check(t))
  27. ctx, cancel := context.WithCancel(context.Background())
  28. defer cancel()
  29. logger := log.NewNopLogger()
  30. // Start the server.
  31. var open int32
  32. mux := http.NewServeMux()
  33. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  34. if n := atomic.AddInt32(&open, 1); n > int32(max) {
  35. t.Errorf("%d open connections, want <= %d", n, max)
  36. }
  37. defer atomic.AddInt32(&open, -1)
  38. time.Sleep(10 * time.Millisecond)
  39. fmt.Fprint(w, "some body")
  40. })
  41. config := DefaultConfig()
  42. l, err := Listen("tcp://127.0.0.1:0", max)
  43. require.NoError(t, err)
  44. defer l.Close()
  45. go Serve(ctx, l, mux, logger, config) //nolint:errcheck // ignore for tests
  46. // Make N GET calls to the server.
  47. attempts := max * 2
  48. var wg sync.WaitGroup
  49. var failed int32
  50. for i := 0; i < attempts; i++ {
  51. wg.Add(1)
  52. go func() {
  53. defer wg.Done()
  54. c := http.Client{Timeout: 3 * time.Second}
  55. r, err := c.Get("http://" + l.Addr().String())
  56. if err != nil {
  57. atomic.AddInt32(&failed, 1)
  58. return
  59. }
  60. defer r.Body.Close()
  61. }()
  62. }
  63. wg.Wait()
  64. // We expect some Gets to fail as the server's accept queue is filled,
  65. // but most should succeed.
  66. if int(failed) >= attempts/2 {
  67. t.Errorf("%d requests failed within %d attempts", failed, attempts)
  68. }
  69. }
  70. func TestServeTLS(t *testing.T) {
  71. t.Cleanup(leaktest.Check(t))
  72. ln, err := net.Listen("tcp", "localhost:0")
  73. require.NoError(t, err)
  74. defer ln.Close()
  75. mux := http.NewServeMux()
  76. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  77. fmt.Fprint(w, "some body")
  78. })
  79. ctx, cancel := context.WithCancel(context.Background())
  80. defer cancel()
  81. logger := log.NewNopLogger()
  82. chErr := make(chan error, 1)
  83. go func() {
  84. select {
  85. case chErr <- ServeTLS(ctx, ln, mux, "test.crt", "test.key", logger, DefaultConfig()):
  86. case <-ctx.Done():
  87. }
  88. }()
  89. select {
  90. case err := <-chErr:
  91. require.NoError(t, err)
  92. case <-time.After(100 * time.Millisecond):
  93. }
  94. tr := &http.Transport{
  95. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  96. }
  97. c := &http.Client{Transport: tr}
  98. res, err := c.Get("https://" + ln.Addr().String())
  99. require.NoError(t, err)
  100. defer res.Body.Close()
  101. assert.Equal(t, http.StatusOK, res.StatusCode)
  102. body, err := io.ReadAll(res.Body)
  103. require.NoError(t, err)
  104. assert.Equal(t, []byte("some body"), body)
  105. }
  106. func TestWriteRPCResponse(t *testing.T) {
  107. id := rpctypes.JSONRPCIntID(-1)
  108. // one argument
  109. w := httptest.NewRecorder()
  110. logger := log.NewNopLogger()
  111. writeRPCResponse(w, logger,
  112. rpctypes.NewRPCSuccessResponse(id, &sampleResult{"hello"}))
  113. resp := w.Result()
  114. body, err := io.ReadAll(resp.Body)
  115. _ = resp.Body.Close()
  116. require.NoError(t, err)
  117. assert.Equal(t, 200, resp.StatusCode)
  118. assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
  119. assert.Equal(t, "", resp.Header.Get("Cache-control"))
  120. assert.Equal(t, `{"jsonrpc":"2.0","id":-1,"result":{"value":"hello"}}`, string(body))
  121. // multiple arguments
  122. w = httptest.NewRecorder()
  123. writeRPCResponse(w, logger,
  124. rpctypes.NewRPCSuccessResponse(id, &sampleResult{"hello"}),
  125. rpctypes.NewRPCSuccessResponse(id, &sampleResult{"world"}),
  126. )
  127. resp = w.Result()
  128. body, err = io.ReadAll(resp.Body)
  129. _ = resp.Body.Close()
  130. require.NoError(t, err)
  131. assert.Equal(t, 200, resp.StatusCode)
  132. assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
  133. assert.Equal(t, `[{"jsonrpc":"2.0","id":-1,"result":{"value":"hello"}},`+
  134. `{"jsonrpc":"2.0","id":-1,"result":{"value":"world"}}]`, string(body))
  135. }
  136. func TestWriteHTTPResponse(t *testing.T) {
  137. w := httptest.NewRecorder()
  138. logger := log.NewNopLogger()
  139. writeHTTPResponse(w, logger,
  140. rpctypes.RPCInternalError(rpctypes.JSONRPCIntID(-1), errors.New("foo")))
  141. resp := w.Result()
  142. body, err := io.ReadAll(resp.Body)
  143. _ = resp.Body.Close()
  144. require.NoError(t, err)
  145. assert.Equal(t, http.StatusOK, resp.StatusCode)
  146. assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
  147. assert.Equal(t, `{"code":-32603,"message":"Internal error","data":"foo"}`, string(body))
  148. }