log_test.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package internal
  2. import (
  3. "context"
  4. "net/http"
  5. "net/http/httptest"
  6. "strings"
  7. "testing"
  8. "github.com/stretchr/testify/assert"
  9. "github.com/zeromicro/go-zero/core/logx"
  10. )
  11. func TestInfo(t *testing.T) {
  12. collector := new(LogCollector)
  13. req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody)
  14. req = req.WithContext(context.WithValue(req.Context(), LogContext, collector))
  15. Info(req, "first")
  16. Infof(req, "second %s", "third")
  17. val := collector.Flush()
  18. assert.True(t, strings.Contains(val, "first"))
  19. assert.True(t, strings.Contains(val, "second"))
  20. assert.True(t, strings.Contains(val, "third"))
  21. assert.True(t, strings.Contains(val, "\n"))
  22. }
  23. func TestError(t *testing.T) {
  24. var buf strings.Builder
  25. w := logx.NewWriter(&buf)
  26. o := logx.Reset()
  27. logx.SetWriter(w)
  28. defer func() {
  29. logx.Reset()
  30. logx.SetWriter(o)
  31. }()
  32. req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody)
  33. Error(req, "first")
  34. Errorf(req, "second %s", "third")
  35. val := buf.String()
  36. assert.True(t, strings.Contains(val, "first"))
  37. assert.True(t, strings.Contains(val, "second"))
  38. assert.True(t, strings.Contains(val, "third"))
  39. }
  40. func TestContextKey_String(t *testing.T) {
  41. val := contextKey("foo")
  42. assert.True(t, strings.Contains(val.String(), "foo"))
  43. }