log_test.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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/wuntsong-org/go-zero-plus/core/logx/logtest"
  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(WithLogCollector(req.Context(), 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. c := logtest.NewCollector(t)
  25. req := httptest.NewRequest(http.MethodGet, "http://localhost", http.NoBody)
  26. Error(req, "first")
  27. Errorf(req, "second %s", "third")
  28. val := c.String()
  29. assert.True(t, strings.Contains(val, "first"))
  30. assert.True(t, strings.Contains(val, "second"))
  31. assert.True(t, strings.Contains(val, "third"))
  32. }
  33. func TestLogCollectorContext(t *testing.T) {
  34. ctx := context.Background()
  35. assert.Nil(t, LogCollectorFromContext(ctx))
  36. collector := new(LogCollector)
  37. ctx = WithLogCollector(ctx, collector)
  38. assert.Equal(t, collector, LogCollectorFromContext(ctx))
  39. }