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.

188 lines
4.5 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
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/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. ctx, cancel := context.WithCancel(context.Background())
  26. defer cancel()
  27. // Start the server.
  28. var open int32
  29. mux := http.NewServeMux()
  30. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  31. if n := atomic.AddInt32(&open, 1); n > int32(max) {
  32. t.Errorf("%d open connections, want <= %d", n, max)
  33. }
  34. defer atomic.AddInt32(&open, -1)
  35. time.Sleep(10 * time.Millisecond)
  36. fmt.Fprint(w, "some body")
  37. })
  38. config := DefaultConfig()
  39. l, err := Listen("tcp://127.0.0.1:0", max)
  40. require.NoError(t, err)
  41. defer l.Close()
  42. go Serve(ctx, l, mux, log.TestingLogger(), config) //nolint:errcheck // ignore for tests
  43. // Make N GET calls to the server.
  44. attempts := max * 2
  45. var wg sync.WaitGroup
  46. var failed int32
  47. for i := 0; i < attempts; i++ {
  48. wg.Add(1)
  49. go func() {
  50. defer wg.Done()
  51. c := http.Client{Timeout: 3 * time.Second}
  52. r, err := c.Get("http://" + l.Addr().String())
  53. if err != nil {
  54. atomic.AddInt32(&failed, 1)
  55. return
  56. }
  57. defer r.Body.Close()
  58. }()
  59. }
  60. wg.Wait()
  61. // We expect some Gets to fail as the server's accept queue is filled,
  62. // but most should succeed.
  63. if int(failed) >= attempts/2 {
  64. t.Errorf("%d requests failed within %d attempts", failed, attempts)
  65. }
  66. }
  67. func TestServeTLS(t *testing.T) {
  68. ln, err := net.Listen("tcp", "localhost:0")
  69. require.NoError(t, err)
  70. defer ln.Close()
  71. mux := http.NewServeMux()
  72. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  73. fmt.Fprint(w, "some body")
  74. })
  75. ctx, cancel := context.WithCancel(context.Background())
  76. defer cancel()
  77. chErr := make(chan error, 1)
  78. go func() {
  79. chErr <- ServeTLS(ctx, ln, mux, "test.crt", "test.key", log.TestingLogger(), DefaultConfig())
  80. }()
  81. select {
  82. case err := <-chErr:
  83. require.NoError(t, err)
  84. case <-time.After(100 * time.Millisecond):
  85. }
  86. tr := &http.Transport{
  87. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  88. }
  89. c := &http.Client{Transport: tr}
  90. res, err := c.Get("https://" + ln.Addr().String())
  91. require.NoError(t, err)
  92. defer res.Body.Close()
  93. assert.Equal(t, http.StatusOK, res.StatusCode)
  94. body, err := io.ReadAll(res.Body)
  95. require.NoError(t, err)
  96. assert.Equal(t, []byte("some body"), body)
  97. }
  98. func TestWriteRPCResponseHTTP(t *testing.T) {
  99. id := rpctypes.JSONRPCIntID(-1)
  100. // one argument
  101. w := httptest.NewRecorder()
  102. err := WriteRPCResponseHTTP(w, true, rpctypes.NewRPCSuccessResponse(id, &sampleResult{"hello"}))
  103. require.NoError(t, err)
  104. resp := w.Result()
  105. body, err := io.ReadAll(resp.Body)
  106. _ = resp.Body.Close()
  107. require.NoError(t, err)
  108. assert.Equal(t, 200, resp.StatusCode)
  109. assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
  110. assert.Equal(t, "max-age=31536000", resp.Header.Get("Cache-control"))
  111. assert.Equal(t, `{
  112. "jsonrpc": "2.0",
  113. "id": -1,
  114. "result": {
  115. "value": "hello"
  116. }
  117. }`, string(body))
  118. // multiple arguments
  119. w = httptest.NewRecorder()
  120. err = WriteRPCResponseHTTP(w,
  121. false,
  122. rpctypes.NewRPCSuccessResponse(id, &sampleResult{"hello"}),
  123. rpctypes.NewRPCSuccessResponse(id, &sampleResult{"world"}))
  124. require.NoError(t, err)
  125. resp = w.Result()
  126. body, err = io.ReadAll(resp.Body)
  127. _ = 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, `[
  132. {
  133. "jsonrpc": "2.0",
  134. "id": -1,
  135. "result": {
  136. "value": "hello"
  137. }
  138. },
  139. {
  140. "jsonrpc": "2.0",
  141. "id": -1,
  142. "result": {
  143. "value": "world"
  144. }
  145. }
  146. ]`, string(body))
  147. }
  148. func TestWriteRPCResponseHTTPError(t *testing.T) {
  149. w := httptest.NewRecorder()
  150. err := WriteRPCResponseHTTPError(w, rpctypes.RPCInternalError(rpctypes.JSONRPCIntID(-1), errors.New("foo")))
  151. require.NoError(t, err)
  152. resp := w.Result()
  153. body, err := io.ReadAll(resp.Body)
  154. _ = resp.Body.Close()
  155. require.NoError(t, err)
  156. assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
  157. assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
  158. assert.Equal(t, `{
  159. "jsonrpc": "2.0",
  160. "id": -1,
  161. "error": {
  162. "code": -32603,
  163. "message": "Internal error",
  164. "data": "foo"
  165. }
  166. }`, string(body))
  167. }