From f1b20a67a23b5128597ea45b9c44966f11d492ff Mon Sep 17 00:00:00 2001 From: Antonio Pitasi Date: Thu, 3 Mar 2022 11:05:40 +0100 Subject: [PATCH] test: add AddCorrelationIDToLogger unit tests --- logging/correlation_test.go | 55 +++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 logging/correlation_test.go diff --git a/logging/correlation_test.go b/logging/correlation_test.go new file mode 100644 index 0000000..6f61e0c --- /dev/null +++ b/logging/correlation_test.go @@ -0,0 +1,55 @@ +package logging + +import ( + "context" + "go.uber.org/zap/zaptest/observer" + "net/http" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + "go.uber.org/zap" +) + +func makeTestContext() *gin.Context { + c, _ := gin.CreateTestContext(nil) + ctx := context.WithValue(context.Background(), IntCorrelationIDName, "anything") + request, _ := http.NewRequestWithContext(ctx, http.MethodPost, "http://something", nil) + c.Request = request + return c +} + +func Test_AddCorrelationIDToLogger_Nil_Context(t *testing.T) { + assert := assert.New(t) + + base := zap.NewExample().Sugar() + + assert.NotPanics(func() { + logger := AddCorrelationIDToLogger(nil, base) + assert.Equal(base, logger) + }) +} + +func Test_AddCorrelationIDToLogger_Nil_Logger(t *testing.T) { + assert := assert.New(t) + + c := makeTestContext() + + assert.Panics(func() { + AddCorrelationIDToLogger(c, nil) + }) +} + +func Test_AddCorrelationIDToLogger(t *testing.T) { + assert := assert.New(t) + + c := makeTestContext() + + observedZapCore, observedLogs := observer.New(zap.InfoLevel) + observedLogger := zap.New(observedZapCore) + + logger := AddCorrelationIDToLogger(c, observedLogger.Sugar()) + logger.Info("test") + + assert.Equal("anything", observedLogs.All()[0].ContextMap()[string(IntCorrelationIDName)]) +}