package fog import ( "bytes" "net/http" "net/url" "testing" "time" "github.com/go-logr/logr" "github.com/stretchr/testify/assert" ) type testLogSink struct { fnInit func(ri logr.RuntimeInfo) fnEnabled func(lvl int) bool fnInfo func(lvl int, msg string, kv ...interface{}) fnError func(err error, msg string, kv ...interface{}) fnWithValues func(kv ...interface{}) fnWithName func(name string) } var _ logr.LogSink = &testLogSink{} func (l *testLogSink) Init(ri logr.RuntimeInfo) { if l.fnInit != nil { l.fnInit(ri) } } func (l *testLogSink) Enabled(lvl int) bool { if l.fnEnabled != nil { return l.fnEnabled(lvl) } return false } func (l *testLogSink) Info(lvl int, msg string, kv ...interface{}) { if l.fnInfo != nil { l.fnInfo(lvl, msg, kv...) } } func (l *testLogSink) Error(err error, msg string, kv ...interface{}) { if l.fnError != nil { l.fnError(err, msg, kv...) } } func (l *testLogSink) WithValues(kv ...interface{}) logr.LogSink { if l.fnWithValues != nil { l.fnWithValues(kv...) } out := *l return &out } func (l *testLogSink) WithName(name string) logr.LogSink { if l.fnWithName != nil { l.fnWithName(name) } out := *l return &out } func TestMiddlewareLoggerError(t *testing.T) { calledError := 0 errInput := "Bad Gateway" msgInput := "POST / 502 Bad Gateway" sink := &testLogSink{} sink.fnError = func(err error, msg string, _ ...interface{}) { calledError++ if err.Error() != errInput { t.Errorf("unexpected err input, got %v", err) } if msg != msgInput { t.Errorf("unexpected msg input, got %q", msg) } } logger := logr.New(sink) MiddlewareLogger(logger, &MiddlewareContext{ Request: &http.Request{ Method: http.MethodPost, URL: &url.URL{ Scheme: "http", Host: "ncr.com", Path: "/", }, }, Status: http.StatusBadGateway, Size: 120, Body: bytes.NewBufferString("hello test"), Time: 5 * time.Second, }) if calledError != 1 { t.Errorf("expected Error() to be called once, got %d", calledError) } } func TestMiddlewareLoggerWithValues(t *testing.T) { calledWithValues := 0 printSink := make(map[string]bool) sink := &testLogSink{} sink.fnWithValues = func(kv ...interface{}) { calledWithValues++ for _, res := range kv { val, ok := res.(string) if ok { printSink[val] = true } } } logger := logr.New(sink) MiddlewareLogger(logger, &MiddlewareContext{ Request: &http.Request{ Method: http.MethodPost, URL: &url.URL{ Scheme: "http", Host: "ncr.com", Path: "/", }, }, Status: http.StatusUnauthorized, Size: 120, Body: bytes.NewBufferString("hello test"), Time: 5 * time.Second, }) _, exists := printSink["httpRequest"] assert.True(t, exists) _, exists = printSink["httpResponse"] assert.True(t, exists) if calledWithValues != 2 { t.Errorf("expected WithValues() to be called twice, got %d", calledWithValues) } }