master
go 67 lines 1.59 KB
Raw
1 package logger
2
3 import (
4 "log/slog"
5 "sync/atomic"
6 "testing"
7
8 "github.com/stretchr/testify/assert"
9 )
10
11 type formatProbe struct {
12 hits *atomic.Int32
13 }
14
15 func (p formatProbe) String() string {
16 p.hits.Add(1)
17 return "probe"
18 }
19
20 func TestWhenElseLogsOnlyChosenBranch(t *testing.T) {
21 setTestLevel(t, slog.LevelDebug)
22
23 l, h := newTestLogger(slog.LevelDebug)
24
25 l.When(true).Warning("warn1").Else().Info("info1")
26 assert.Equal(t, 1, h.count())
27 assert.Equal(t, slog.LevelWarn, h.last().level)
28 assert.Equal(t, "warn1", h.last().msg)
29
30 l.When(false).Warning("warn2").Else().Info("info2")
31 assert.Equal(t, 2, h.count())
32 assert.Equal(t, slog.LevelInfo, h.last().level)
33 assert.Equal(t, "info2", h.last().msg)
34 }
35
36 func TestWhenElseSkipsFormattingOnSuppressedBranch(t *testing.T) {
37 setTestLevel(t, slog.LevelDebug)
38
39 l, h := newTestLogger(slog.LevelDebug)
40 var firstHits atomic.Int32
41 var secondHits atomic.Int32
42
43 l.When(true).Warningf("warn %s", formatProbe{hits: &firstHits}).Else().Infof("info %s", formatProbe{hits: &secondHits})
44
45 assert.Equal(t, int32(1), firstHits.Load())
46 assert.Equal(t, int32(0), secondHits.Load())
47 assert.Equal(t, 1, h.count())
48 assert.Equal(t, slog.LevelWarn, h.last().level)
49 }
50
51 func TestWhenWithoutElseDoesNotLogWhenConditionFalse(t *testing.T) {
52 setTestLevel(t, slog.LevelDebug)
53
54 l, h := newTestLogger(slog.LevelDebug)
55 l.When(false).Infof("suppressed %d", 1)
56
57 assert.Equal(t, 0, h.count())
58 }
59
60 func TestWhenNilLoggerDoesNotPanic(t *testing.T) {
61 setTestLevel(t, slog.LevelDebug)
62
63 var l *Logger
64 assert.NotPanics(t, func() {
65 l.When(true).Noticef("hello %s", "world").Else().Info("ignored")
66 })
67 }