...
1 package slogtest_test
2
3 import (
4 "context"
5 "testing"
6
7 "cdr.dev/slog/internal/assert"
8 "cdr.dev/slog/sloggers/slogtest"
9 )
10
11 func TestStateless(t *testing.T) {
12 t.Parallel()
13
14 tb := &fakeTB{}
15 slogtest.Debug(tb, "hello")
16 slogtest.Info(tb, "hello")
17
18 slogtest.Error(tb, "hello")
19 assert.Equal(t, "errors", 1, tb.errors)
20
21 defer func() {
22 recover()
23 assert.Equal(t, "fatals", 1, tb.fatals)
24 }()
25
26 slogtest.Fatal(tb, "hello")
27 }
28
29 func TestIgnoreErrors(t *testing.T) {
30 t.Parallel()
31
32 tb := &fakeTB{}
33 l := slogtest.Make(tb, &slogtest.Options{
34 IgnoreErrors: true,
35 })
36
37 l.Error(bg, "hello")
38 assert.Equal(t, "errors", 0, tb.errors)
39
40 defer func() {
41 recover()
42 assert.Equal(t, "fatals", 1, tb.fatals)
43 }()
44
45 l.Fatal(bg, "hello")
46 }
47
48 func TestCleanup(t *testing.T) {
49 t.Parallel()
50
51 tb := &fakeTB{}
52 l := slogtest.Make(tb, &slogtest.Options{})
53
54 for _, fn := range tb.cleanups {
55 fn()
56 }
57
58
59 l.Info(bg, "hello")
60 assert.Equal(t, "no logs", 0, tb.logs)
61 }
62
63 func TestSkipCleanup(t *testing.T) {
64 t.Parallel()
65
66 tb := &fakeTB{}
67 slogtest.Make(tb, &slogtest.Options{
68 SkipCleanup: true,
69 })
70
71 assert.Len(t, "no cleanups", 0, tb.cleanups)
72 }
73
74 var bg = context.Background()
75
76 type fakeTB struct {
77 testing.TB
78
79 logs int
80 errors int
81 fatals int
82 cleanups []func()
83 }
84
85 func (tb *fakeTB) Helper() {}
86
87 func (tb *fakeTB) Log(v ...interface{}) {
88 tb.logs++
89 }
90
91 func (tb *fakeTB) Error(v ...interface{}) {
92 tb.errors++
93 }
94
95 func (tb *fakeTB) Fatal(v ...interface{}) {
96 tb.fatals++
97 panic("")
98 }
99
100 func (tb *fakeTB) Cleanup(fn func()) {
101 tb.cleanups = append(tb.cleanups, fn)
102 }
103
View as plain text