timeouthandler_test.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package handler
  2. import (
  3. "io/ioutil"
  4. "log"
  5. "net/http"
  6. "net/http/httptest"
  7. "testing"
  8. "time"
  9. "github.com/stretchr/testify/assert"
  10. )
  11. func init() {
  12. log.SetOutput(ioutil.Discard)
  13. }
  14. func TestTimeout(t *testing.T) {
  15. timeoutHandler := TimeoutHandler(time.Millisecond)
  16. handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  17. time.Sleep(time.Minute)
  18. }))
  19. req := httptest.NewRequest(http.MethodGet, "http://localhost", nil)
  20. resp := httptest.NewRecorder()
  21. handler.ServeHTTP(resp, req)
  22. assert.Equal(t, http.StatusServiceUnavailable, resp.Code)
  23. }
  24. func TestWithinTimeout(t *testing.T) {
  25. timeoutHandler := TimeoutHandler(time.Second)
  26. handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  27. time.Sleep(time.Millisecond)
  28. }))
  29. req := httptest.NewRequest(http.MethodGet, "http://localhost", nil)
  30. resp := httptest.NewRecorder()
  31. handler.ServeHTTP(resp, req)
  32. assert.Equal(t, http.StatusOK, resp.Code)
  33. }
  34. func TestWithoutTimeout(t *testing.T) {
  35. timeoutHandler := TimeoutHandler(0)
  36. handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  37. time.Sleep(100 * time.Millisecond)
  38. }))
  39. req := httptest.NewRequest(http.MethodGet, "http://localhost", nil)
  40. resp := httptest.NewRecorder()
  41. handler.ServeHTTP(resp, req)
  42. assert.Equal(t, http.StatusOK, resp.Code)
  43. }