Skip to content

Instantly share code, notes, and snippets.

@ivankatliarchuk
Last active November 17, 2024 20:45
Show Gist options
  • Save ivankatliarchuk/68fd97d239a2eaff0fb244277c70f417 to your computer and use it in GitHub Desktop.
Save ivankatliarchuk/68fd97d239a2eaff0fb244277c70f417 to your computer and use it in GitHub Desktop.
how-to-test-slog
package rds
import (
log "log/slog"
)
func Process(input string) string {
log.Info("process")
return input
}
---
package rds_test
import (
"bytes"
"fmt"
"log/slog"
"testing"
"github.com/stretchr/testify/assert"
)
func TestProcessLogging(t *testing.T) {
var buf bytes.Buffer
th := slog.NewTextHandler(&buf, nil)
slog.SetDefault(slog.New(th))
_ = Process("hello")
assert.Contains(t, buf.String(), "level=INFO msg=process")
}
func TestProcessLoggingMocking(t *testing.T) {
wr := WriterC{}
th := slog.NewTextHandler(&wr, nil)
slog.SetDefault(slog.New(th))
_ = Process("hello")
assert.Equal(t, wr.CountInfo, 1)
}
type WriterC struct {
CountInfo int
}
// Write overrides behaviour of Writer interface
func (w *WriterC) Write(p []byte) (n int, err error) {
if strings.Contains(strings.ToLower(string(p)), "info") {
w.CountInfo += 1
}
return len(p), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment