mediocre-go-lib/mlog/mlog_test.go
Brian Picciano 9567a98606 Move massert into internal, and simplify it a lot
The previous massert isn't that useful compared to testify, but it's
nice to have some assertion helpers in the repo which don't require a
sub-dependency.
2023-12-26 16:27:41 +01:00

62 lines
1.8 KiB
Go

package mlog
import (
"bytes"
"context"
"errors"
"fmt"
"strings"
"testing"
. "testing"
"time"
"github.com/mediocregopher/mediocre-go-lib/v2/internal/massert"
"github.com/mediocregopher/mediocre-go-lib/v2/mctx"
)
func TestTruncate(t *T) {
massert.Equal(t, "abc", Truncate("abc", 4))
massert.Equal(t, "abc", Truncate("abc", 3))
massert.Equal(t, "ab...", Truncate("abc", 2))
}
func TestJSONLogger(t *T) {
buf := new(bytes.Buffer)
now := time.Now().UTC()
td, ts := now.Format(msgTimeFormat), fmt.Sprint(now.UnixNano())
l := NewLogger(&LoggerOpts{
MessageHandler: NewJSONMessageHandler(buf),
Now: func() time.Time { return now },
})
assertOut := func(t *testing.T, expected string) {
expected = strings.ReplaceAll(expected, "<TD>", td)
expected = strings.ReplaceAll(expected, "<TS>", ts)
out, err := buf.ReadString('\n')
massert.Equal(t, nil, err)
massert.Equal(t, expected, strings.TrimSpace(out))
}
ctx := context.Background()
// Default max level should be INFO
l.Debug(ctx, "foo")
l.Info(ctx, "bar")
l.Warn(ctx, "baz", errors.New("ERR"))
l.Error(ctx, "buz", errors.New("ERR"))
assertOut(t, `{"td":"<TD>","ts":<TS>,"level":"INFO","descr":"bar","level_int":30}`)
assertOut(t, `{"td":"<TD>","ts":<TS>,"level":"WARN","descr":"baz","level_int":20,"annotations":{"errMsg":"ERR"}}`)
assertOut(t, `{"td":"<TD>","ts":<TS>,"level":"ERROR","descr":"buz","level_int":10,"annotations":{"errMsg":"ERR"}}`)
// annotate context
ctx = mctx.Annotate(ctx, "foo", "bar")
l.Info(ctx, "bar")
assertOut(t, `{"td":"<TD>","ts":<TS>,"level":"INFO","descr":"bar","level_int":30,"annotations":{"foo":"bar"}}`)
// add namespace
l = l.WithNamespace("ns")
l.Info(ctx, "bar")
assertOut(t, `{"td":"<TD>","ts":<TS>,"level":"INFO","ns":["ns"],"descr":"bar","level_int":30,"annotations":{"foo":"bar"}}`)
}