feat: move MockLogger into a logtest sub-package (#5)
This commit was merged in pull request #5.
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
// Package logtest provides test helpers for the logging library. It is kept in
|
||||
// its own package so that importing the production logging package does not pull
|
||||
// in testify (a test-only dependency) — only consumers that import logtest do.
|
||||
package logtest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func NewMockLogger() *MockLogger {
|
||||
logged := &bytes.Buffer{}
|
||||
|
||||
return &MockLogger{
|
||||
logged: logged,
|
||||
logger: slog.New(slog.NewTextHandler(logged, &slog.HandlerOptions{
|
||||
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
|
||||
if a.Key == "time" {
|
||||
return slog.Attr{}
|
||||
}
|
||||
return a
|
||||
},
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
type MockLogger struct {
|
||||
logger *slog.Logger
|
||||
logged *bytes.Buffer
|
||||
}
|
||||
|
||||
func (m *MockLogger) Logger() *slog.Logger {
|
||||
return m.logger
|
||||
}
|
||||
|
||||
func (m *MockLogger) Check(t testing.TB, wantLogged []string) {
|
||||
var gotLogged []string
|
||||
if m.logged.String() != "" {
|
||||
gotLogged = strings.Split(m.logged.String(), "\n")
|
||||
gotLogged = gotLogged[:len(gotLogged)-1]
|
||||
}
|
||||
if len(wantLogged) == 0 {
|
||||
assert.Empty(t, gotLogged)
|
||||
return
|
||||
}
|
||||
assert.Equal(t, wantLogged, gotLogged)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package logtest
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestMockLogger(t *testing.T) {
|
||||
m := NewMockLogger()
|
||||
m.Logger().Info("hello", "k", "v")
|
||||
m.Check(t, []string{`level=INFO msg=hello k=v`})
|
||||
empty := NewMockLogger()
|
||||
empty.Check(t, nil)
|
||||
}
|
||||
Reference in New Issue
Block a user