error-pages/internal/logger/logger_test.go

76 lines
2.0 KiB
Go
Raw Normal View History

2021-09-29 15:38:50 +00:00
package logger_test
import (
"regexp"
"strings"
"testing"
"time"
"github.com/kami-zh/go-capturer"
"github.com/stretchr/testify/assert"
2023-01-29 10:54:56 +00:00
"github.com/stretchr/testify/require"
2021-09-29 15:38:50 +00:00
"github.com/tarampampam/error-pages/internal/logger"
)
2023-01-29 10:54:56 +00:00
func TestNewDebugLevelConsoleFormat(t *testing.T) {
2021-09-29 15:38:50 +00:00
output := capturer.CaptureStderr(func() {
2023-01-29 10:54:56 +00:00
log, err := logger.New(logger.DebugLevel, logger.ConsoleFormat)
require.NoError(t, err)
2021-09-29 15:38:50 +00:00
log.Debug("dbg msg")
log.Info("inf msg")
log.Error("err msg")
})
assert.Contains(t, output, time.Now().Format("15:04:05"))
assert.Regexp(t, `\t.+info.+\tinf msg`, output)
2023-01-29 10:54:56 +00:00
assert.Regexp(t, `\t.+info.+\t.+logger_test\.go:\d+\tinf msg`, output)
2021-09-29 15:38:50 +00:00
assert.Contains(t, output, "dbg msg")
assert.Contains(t, output, "err msg")
}
2023-01-29 10:54:56 +00:00
func TestNewErrorLevelConsoleFormat(t *testing.T) {
2021-09-29 15:38:50 +00:00
output := capturer.CaptureStderr(func() {
2023-01-29 10:54:56 +00:00
log, err := logger.New(logger.ErrorLevel, logger.ConsoleFormat)
require.NoError(t, err)
2021-09-29 15:38:50 +00:00
log.Debug("dbg msg")
2023-01-29 10:54:56 +00:00
log.Info("inf msg")
2021-09-29 15:38:50 +00:00
log.Error("err msg")
})
2023-01-29 10:54:56 +00:00
assert.NotContains(t, output, "inf msg")
assert.NotContains(t, output, "dbg msg")
2021-09-29 15:38:50 +00:00
assert.Contains(t, output, "err msg")
}
2023-01-29 10:54:56 +00:00
func TestNewWarnLevelJSONFormat(t *testing.T) {
2021-09-29 15:38:50 +00:00
output := capturer.CaptureStderr(func() {
2023-01-29 10:54:56 +00:00
log, err := logger.New(logger.WarnLevel, logger.JSONFormat)
require.NoError(t, err)
2021-09-29 15:38:50 +00:00
log.Debug("dbg msg")
2023-01-29 10:54:56 +00:00
log.Info("inf msg")
log.Warn("warn msg")
2021-09-29 15:38:50 +00:00
log.Error("err msg")
})
// replace timestamp field with fixed value
fakeTimestamp := regexp.MustCompile(`"ts":\d+\.\d+,`)
output = fakeTimestamp.ReplaceAllString(output, `"ts":0.1,`)
lines := strings.Split(strings.Trim(output, "\n"), "\n")
2023-01-29 10:54:56 +00:00
assert.JSONEq(t, `{"level":"warn","ts":0.1,"msg":"warn msg"}`, lines[0])
2021-09-29 15:38:50 +00:00
assert.JSONEq(t, `{"level":"error","ts":0.1,"msg":"err msg"}`, lines[1])
}
2023-01-29 10:54:56 +00:00
func TestNewErrors(t *testing.T) {
_, err := logger.New(logger.Level(127), logger.ConsoleFormat)
require.EqualError(t, err, "unsupported logging level")
_, err = logger.New(logger.WarnLevel, logger.Format(255))
require.EqualError(t, err, "unsupported logging format")
}