1 package ldlogtest
2
3 import (
4 "bytes"
5 "testing"
6
7 "github.com/stretchr/testify/assert"
8
9 "github.com/launchdarkly/go-sdk-common/v3/ldlog"
10 )
11
12 type mockLogTestValues struct {
13 level ldlog.LogLevel
14 nextLevel ldlog.LogLevel
15 println func(ldlog.Loggers, ...interface{})
16 printf func(ldlog.Loggers, string, ...interface{})
17 }
18
19 var allTestValues = []mockLogTestValues{
20 {ldlog.Debug, ldlog.Info, ldlog.Loggers.Debug, ldlog.Loggers.Debugf},
21 {ldlog.Info, ldlog.Warn, ldlog.Loggers.Info, ldlog.Loggers.Infof},
22 {ldlog.Warn, ldlog.Error, ldlog.Loggers.Warn, ldlog.Loggers.Warnf},
23 {ldlog.Error, ldlog.None, ldlog.Loggers.Error, ldlog.Loggers.Errorf},
24 }
25
26 func TestMockLogCapturesMessagesForLevel(t *testing.T) {
27 for _, v := range allTestValues {
28 t.Run(v.level.String(), func(t *testing.T) {
29 m := NewMockLog()
30 m.Loggers.SetMinLevel(v.level)
31 v.println(m.Loggers, "hello")
32 v.printf(m.Loggers, "yes: %t", true)
33
34 m.Loggers.SetMinLevel(v.nextLevel)
35 v.println(m.Loggers, "shouldn't see this")
36
37 o1 := m.GetOutput(v.level)
38 assert.Equal(t, []string{"hello", "yes: true"}, o1)
39
40 o2 := m.GetAllOutput()
41 assert.Equal(t, []MockLogItem{
42 {v.level, "hello"},
43 {v.level, "yes: true"},
44 }, o2)
45 })
46 }
47 }
48
49 func TestMessageMatching(t *testing.T) {
50 m := NewMockLog()
51 m.Loggers.Info("first")
52 m.Loggers.Info("second")
53 m.Loggers.Warn("third")
54
55 testShouldFail := func(t *testing.T, action func(*testing.T)) {
56 var tt testing.T
57 action(&tt)
58 assert.True(t, tt.Failed(), "test should have failed")
59 }
60
61 shouldMatch := func(t *testing.T, level ldlog.LogLevel, pattern string) {
62 assert.True(t, m.HasMessageMatch(level, pattern))
63 m.AssertMessageMatch(t, true, level, pattern)
64 testShouldFail(t, func(tt *testing.T) { m.AssertMessageMatch(tt, false, level, pattern) })
65 }
66
67 shouldNotMatch := func(t *testing.T, level ldlog.LogLevel, pattern string) {
68 assert.False(t, m.HasMessageMatch(level, pattern))
69 m.AssertMessageMatch(t, false, level, pattern)
70 testShouldFail(t, func(tt *testing.T) { m.AssertMessageMatch(tt, true, level, pattern) })
71 }
72
73 shouldMatch(t, ldlog.Info, ".econd")
74 shouldMatch(t, ldlog.Warn, "t.*")
75 shouldNotMatch(t, ldlog.Info, "third")
76 shouldNotMatch(t, ldlog.Error, ".")
77 }
78
79 func TestDump(t *testing.T) {
80 buf := bytes.NewBuffer(nil)
81 m := NewMockLog()
82 m.Loggers.Info("first")
83 m.Loggers.Warn("second")
84 m.Dump(buf)
85 assert.Equal(t, "Info: first\nWarn: second\n", string(buf.Bytes()))
86 }
87
View as plain text