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.

182 lines
4.4 KiB

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