Last active
November 17, 2024 20:45
-
-
Save ivankatliarchuk/68fd97d239a2eaff0fb244277c70f417 to your computer and use it in GitHub Desktop.
how-to-test-slog
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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