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.

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