log/logging_test.go
2025-02-23 09:56:16 -06:00

98 lines
2.0 KiB
Go

package log
import (
"bytes"
"log/slog"
"testing"
"github.com/stretchr/testify/assert"
)
func slogToBuffer() (*bytes.Buffer, *slog.Logger) {
buf := new(bytes.Buffer)
return buf, slog.New(
slog.NewTextHandler(
buf,
&slog.HandlerOptions{
Level: LevelTrace,
},
),
)
}
func TestSetLogLevel(t *testing.T) {
Init("text")
for _, i := range []int{0, 21, 41, 61, 81, 101} {
SetNumericLevel(i)
switch i {
case 0:
assert.Equal(t, LevelFatal, L.SLogLevel.Level())
case 21:
assert.Equal(t, slog.LevelError, L.SLogLevel.Level())
case 41:
assert.Equal(t, slog.LevelWarn, L.SLogLevel.Level())
case 61:
assert.Equal(t, slog.LevelInfo, L.SLogLevel.Level())
case 81:
assert.Equal(t, slog.LevelDebug, L.SLogLevel.Level())
case 101:
assert.Equal(t, LevelTrace, L.SLogLevel.Level())
}
}
}
func TestFatal(t *testing.T) {
buf, log := slogToBuffer()
L.Log = log
Fatal("TEST Message")
assert.Contains(t, buf.String(), "TEST Message")
assert.Contains(t, buf.String(), "level=ERROR+4")
}
func TestError(t *testing.T) {
buf, log := slogToBuffer()
L.Log = log
Error("TEST Message")
assert.Contains(t, buf.String(), "TEST Message")
assert.Contains(t, buf.String(), "level=ERROR")
}
func TestWarn(t *testing.T) {
buf, log := slogToBuffer()
L.Log = log
Warn("TEST Message")
assert.Contains(t, buf.String(), "TEST Message")
assert.Contains(t, buf.String(), "level=WARN")
}
func TestInfo(t *testing.T) {
buf, log := slogToBuffer()
L.Log = log
Info("TEST Message")
assert.Contains(t, buf.String(), "TEST Message")
assert.Contains(t, buf.String(), "level=INFO")
}
func TestDebug(t *testing.T) {
buf, log := slogToBuffer()
L.Log = log
Debug("TEST Message")
assert.Contains(t, buf.String(), "TEST Message")
assert.Contains(t, buf.String(), "level=DEBUG")
}
func TestTrace(t *testing.T) {
buf, log := slogToBuffer()
L.Log = log
Trace("TEST Message")
assert.Contains(t, buf.String(), "TEST Message")
assert.Contains(t, buf.String(), "level=DEBUG-4")
}