Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: add tests to improve code coverage for logging #244

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 19 additions & 11 deletions pkg/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ type Interface interface {

// Logger -.
type Logger struct {
logger *zerolog.Logger
logger *zerolog.Logger
localLevel zerolog.Level
}

var _ Interface = (*Logger)(nil)
Expand All @@ -41,38 +42,45 @@ func New(level string) *Logger {
l = zerolog.InfoLevel
}

zerolog.SetGlobalLevel(l)

skipFrameCount := 3
logger := zerolog.New(os.Stdout).With().Timestamp().CallerWithSkipFrameCount(zerolog.CallerSkipFrameCount + skipFrameCount).Logger()

return &Logger{
logger: &logger,
logger: &logger,
localLevel: l,
}
}

// Debug -.
func (l *Logger) Debug(message interface{}, args ...interface{}) {
l.msg("debug", message, args...)
if l.localLevel <= zerolog.DebugLevel {
l.msg("debug", message, args...)
}
}

// Info -.
func (l *Logger) Info(message string, args ...interface{}) {
l.log(message, args...)
if l.localLevel <= zerolog.InfoLevel {
l.log(message, args...)
}
}

// Warn -.
func (l *Logger) Warn(message string, args ...interface{}) {
l.log(message, args...)
if l.localLevel <= zerolog.WarnLevel {
l.log(message, args...)
}
}

// Error -.
func (l *Logger) Error(message interface{}, args ...interface{}) {
if l.logger.GetLevel() == zerolog.DebugLevel {
l.Debug(message, args...)
}
if l.localLevel <= zerolog.ErrorLevel {
if l.localLevel == zerolog.DebugLevel {
l.Debug(message, args...)
}

l.msg("error", message, args...)
l.msg("error", message, args...)
}
}

// Fatal -.
Expand Down
130 changes: 130 additions & 0 deletions pkg/logger/logger_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package logger

import (
"bytes"
"errors"
"fmt"
"os"
"os/exec"
"sync"
"testing"

"github.com/rs/zerolog"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

var mu sync.Mutex

type loggerTest struct {
name string
logLevel string
testFunction func(t *testing.T, log *Logger, buf *bytes.Buffer)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hey @emeeker2002 typically you'd want to have an expected result in your test struct. and then in each test case, you'd set the expected result. That way all assets can be handled in the for loop at the end.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would explain why the linter was wanting t.Helper in each function which was a bit odd to me.

}

func TestLogger(t *testing.T) {
t.Parallel()

tests := []loggerTest{
{
name: "Debug level logging",
logLevel: "debug",
testFunction: func(t *testing.T, log *Logger, buf *bytes.Buffer) {
t.Helper()
log.Debug("debug message")
assert.Contains(t, buf.String(), "debug message")
},
},
{
name: "Info level logging",
logLevel: "info",
testFunction: func(t *testing.T, log *Logger, buf *bytes.Buffer) {
t.Helper()
log.Info("info message")
assert.Contains(t, buf.String(), "info message")
},
},
{
name: "Warn level logging",
logLevel: "warn",
testFunction: func(t *testing.T, log *Logger, buf *bytes.Buffer) {
t.Helper()
log.Warn("warn message")
assert.Contains(t, buf.String(), "warn message")
},
},
{
name: "Error level logging",
logLevel: "error",
testFunction: func(t *testing.T, log *Logger, buf *bytes.Buffer) {
t.Helper()
log.Error("error message")
assert.Contains(t, buf.String(), "error message")
},
},
{
name: "Fatal level logging",
logLevel: "fatal",
testFunction: func(t *testing.T, log *Logger, _ *bytes.Buffer) {
t.Helper()
if os.Getenv("BE_CRASHER") == "1" {
log.Fatal("fatal message")

return
}
cmd := exec.Command(os.Args[0], "-test.run=TestLogger") // #nosec
cmd.Env = append(os.Environ(), "BE_CRASHER=1")
err := cmd.Run()
var exitError *exec.ExitError
if errors.As(err, &exitError) && !exitError.Success() {
return
}
t.Fatalf("process ran with err %v, want exit status 1", err)
},
},
}

for _, tc := range tests {
tc := tc // capture range variable

t.Run(tc.name, func(t *testing.T) {
t.Parallel()

var buf bytes.Buffer
logger := zerolog.New(&buf).With().Timestamp().Logger()
log := &Logger{logger: &logger}

tc.testFunction(t, log, &buf)
})
}
}

func TestNewLogger(t *testing.T) {
t.Parallel()

tests := []struct {
level string
expectedLevel zerolog.Level
}{
{"debug", zerolog.DebugLevel},
{"info", zerolog.InfoLevel},
{"warn", zerolog.WarnLevel},
{"error", zerolog.ErrorLevel},
{"invalid", zerolog.InfoLevel},
}

for _, tc := range tests {
tc := tc

t.Run(fmt.Sprintf("LogLevel_%s", tc.level), func(t *testing.T) {
t.Parallel()

mu.Lock()
defer mu.Unlock()

log := New(tc.level)
require.NotNil(t, log)
assert.Equal(t, tc.expectedLevel, log.localLevel)
})
}
}
Loading