Skip to content

Commit

Permalink
test: add AddCorrelationIDToLogger unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Pitasi committed Mar 3, 2022
1 parent 306f863 commit f1b20a6
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions logging/correlation_test.go
Original file line number Diff line number Diff line change
@@ -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)])
}

0 comments on commit f1b20a6

Please sign in to comment.