loghandler_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. "github.com/tal-tech/go-zero/rest/internal"
  11. )
  12. func init() {
  13. log.SetOutput(ioutil.Discard)
  14. }
  15. func TestLogHandler(t *testing.T) {
  16. handlers := []func(handler http.Handler) http.Handler{
  17. LogHandler,
  18. DetailedLogHandler,
  19. }
  20. for _, logHandler := range handlers {
  21. req := httptest.NewRequest(http.MethodGet, "http://localhost", nil)
  22. handler := logHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  23. r.Context().Value(internal.LogContext).(*internal.LogCollector).Append("anything")
  24. w.Header().Set("X-Test", "test")
  25. w.WriteHeader(http.StatusServiceUnavailable)
  26. _, err := w.Write([]byte("content"))
  27. assert.Nil(t, err)
  28. flusher, ok := w.(http.Flusher)
  29. assert.True(t, ok)
  30. flusher.Flush()
  31. }))
  32. resp := httptest.NewRecorder()
  33. handler.ServeHTTP(resp, req)
  34. assert.Equal(t, http.StatusServiceUnavailable, resp.Code)
  35. assert.Equal(t, "test", resp.Header().Get("X-Test"))
  36. assert.Equal(t, "content", resp.Body.String())
  37. }
  38. }
  39. func TestLogHandlerSlow(t *testing.T) {
  40. handlers := []func(handler http.Handler) http.Handler{
  41. LogHandler,
  42. DetailedLogHandler,
  43. }
  44. for _, logHandler := range handlers {
  45. req := httptest.NewRequest(http.MethodGet, "http://localhost", nil)
  46. handler := logHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  47. time.Sleep(slowThreshold + time.Millisecond*50)
  48. }))
  49. resp := httptest.NewRecorder()
  50. handler.ServeHTTP(resp, req)
  51. assert.Equal(t, http.StatusOK, resp.Code)
  52. }
  53. }
  54. func BenchmarkLogHandler(b *testing.B) {
  55. b.ReportAllocs()
  56. req := httptest.NewRequest(http.MethodGet, "http://localhost", nil)
  57. handler := LogHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  58. w.WriteHeader(http.StatusOK)
  59. }))
  60. for i := 0; i < b.N; i++ {
  61. resp := httptest.NewRecorder()
  62. handler.ServeHTTP(resp, req)
  63. }
  64. }