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