loghandler_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. }))
  29. resp := httptest.NewRecorder()
  30. handler.ServeHTTP(resp, req)
  31. assert.Equal(t, http.StatusServiceUnavailable, resp.Code)
  32. assert.Equal(t, "test", resp.Header().Get("X-Test"))
  33. assert.Equal(t, "content", resp.Body.String())
  34. }
  35. }
  36. func TestLogHandlerSlow(t *testing.T) {
  37. handlers := []func(handler http.Handler) http.Handler{
  38. LogHandler,
  39. DetailedLogHandler,
  40. }
  41. for _, logHandler := range handlers {
  42. req := httptest.NewRequest(http.MethodGet, "http://localhost", nil)
  43. handler := logHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  44. time.Sleep(slowThreshold + time.Millisecond*50)
  45. }))
  46. resp := httptest.NewRecorder()
  47. handler.ServeHTTP(resp, req)
  48. assert.Equal(t, http.StatusOK, resp.Code)
  49. }
  50. }
  51. func BenchmarkLogHandler(b *testing.B) {
  52. b.ReportAllocs()
  53. req := httptest.NewRequest(http.MethodGet, "http://localhost", nil)
  54. handler := LogHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  55. w.WriteHeader(http.StatusOK)
  56. }))
  57. for i := 0; i < b.N; i++ {
  58. resp := httptest.NewRecorder()
  59. handler.ServeHTTP(resp, req)
  60. }
  61. }