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.

83 lines
2.0 KiB

  1. package rpcserver
  2. import (
  3. "fmt"
  4. "io"
  5. "io/ioutil"
  6. "net/http"
  7. "os"
  8. "sync"
  9. "sync/atomic"
  10. "testing"
  11. "time"
  12. "github.com/stretchr/testify/require"
  13. "github.com/tendermint/tendermint/libs/log"
  14. )
  15. func TestMaxOpenConnections(t *testing.T) {
  16. const max = 5 // max simultaneous connections
  17. // Start the server.
  18. var open int32
  19. mux := http.NewServeMux()
  20. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  21. if n := atomic.AddInt32(&open, 1); n > int32(max) {
  22. t.Errorf("%d open connections, want <= %d", n, max)
  23. }
  24. defer atomic.AddInt32(&open, -1)
  25. time.Sleep(10 * time.Millisecond)
  26. fmt.Fprint(w, "some body")
  27. })
  28. config := DefaultConfig()
  29. config.MaxOpenConnections = max
  30. l, err := Listen("tcp://127.0.0.1:0", config)
  31. require.NoError(t, err)
  32. defer l.Close()
  33. go StartHTTPServer(l, mux, log.TestingLogger(), config)
  34. // Make N GET calls to the server.
  35. attempts := max * 2
  36. var wg sync.WaitGroup
  37. var failed int32
  38. for i := 0; i < attempts; i++ {
  39. wg.Add(1)
  40. go func() {
  41. defer wg.Done()
  42. c := http.Client{Timeout: 3 * time.Second}
  43. r, err := c.Get("http://" + l.Addr().String())
  44. if err != nil {
  45. t.Log(err)
  46. atomic.AddInt32(&failed, 1)
  47. return
  48. }
  49. defer r.Body.Close()
  50. io.Copy(ioutil.Discard, r.Body)
  51. }()
  52. }
  53. wg.Wait()
  54. // We expect some Gets to fail as the server's accept queue is filled,
  55. // but most should succeed.
  56. if int(failed) >= attempts/2 {
  57. t.Errorf("%d requests failed within %d attempts", failed, attempts)
  58. }
  59. }
  60. func TestStartHTTPAndTLSServer(t *testing.T) {
  61. config := DefaultConfig()
  62. config.MaxOpenConnections = 1
  63. // set up fixtures
  64. listenerAddr := "tcp://0.0.0.0:0"
  65. listener, err := Listen(listenerAddr, config)
  66. require.NoError(t, err)
  67. mux := http.NewServeMux()
  68. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {})
  69. // test failure
  70. err = StartHTTPAndTLSServer(listener, mux, "", "", log.TestingLogger(), config)
  71. require.IsType(t, (*os.PathError)(nil), err)
  72. // TODO: test that starting the server can actually work
  73. }