From a27b879accb191b6a6c6e76a6251ed751967f73a Mon Sep 17 00:00:00 2001 From: tjpcc Date: Thu, 26 Jan 2023 16:22:58 -0700 Subject: test coverage and resulting bugfixes --- logging/middleware.go | 1 + logging/middleware_test.go | 47 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 logging/middleware_test.go (limited to 'logging') diff --git a/logging/middleware.go b/logging/middleware.go index 01278e1..5527ce7 100644 --- a/logging/middleware.go +++ b/logging/middleware.go @@ -48,6 +48,7 @@ func (lr *loggedResponseBody) log() { func (lr *loggedResponseBody) Read(b []byte) (int, error) { if lr.body == nil { + lr.log() return 0, io.EOF } diff --git a/logging/middleware_test.go b/logging/middleware_test.go new file mode 100644 index 0000000..288c960 --- /dev/null +++ b/logging/middleware_test.go @@ -0,0 +1,47 @@ +package logging_test + +import ( + "context" + "io" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "tildegit.org/tjp/gus" + "tildegit.org/tjp/gus/logging" +) + +func TestLogRequests(t *testing.T) { + logger := logRecorder{} + handler := logging.LogRequests(&logger)(func(_ context.Context, _ *gus.Request) *gus.Response { + return &gus.Response{} + }) + + response := handler(context.Background(), &gus.Request{}) + _, err := io.ReadAll(response.Body) + assert.Nil(t, err) + + require.Equal(t, 1, len(logger)) + + keyvals := map[string]any{} + for i := 0; i < len(logger[0])-1; i += 2 { + keyvals[logger[0][i].(string)] = logger[0][i+1] + } + + if assert.Contains(t, keyvals, "msg") { + assert.Equal(t, keyvals["msg"], "request") + } + assert.Contains(t, keyvals, "ts") + assert.Contains(t, keyvals, "dur") + assert.Contains(t, keyvals, "url") + assert.Contains(t, keyvals, "status") + assert.Contains(t, keyvals, "bodylen") +} + +type logRecorder [][]any + +func (lr *logRecorder) Log(keyvals ...any) error { + *lr = append(*lr, keyvals) + return nil +} -- cgit v1.2.3