-
Notifications
You must be signed in to change notification settings - Fork 1
/
stdlog_handler_test.go
97 lines (86 loc) · 2.27 KB
/
stdlog_handler_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package clog
import (
"bytes"
"os"
"path/filepath"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestPrefix(t *testing.T) {
buffer := &bytes.Buffer{}
handler := NewStandardLogHandler(buffer, "prefix", 0)
err := handler.LogEntry(LogEntry{
Level: LevelDebug,
Values: []interface{}{"message"},
})
assert.NoError(t, err)
assert.Equal(t, "prefixDEBUG message\n", buffer.String())
}
func TestSetPrefix(t *testing.T) {
buffer := &bytes.Buffer{}
handler := NewStandardLogHandler(buffer, "no prefix", 0)
handler.SetPrefix("prefix")
err := handler.LogEntry(LogEntry{
Level: LevelDebug,
Values: []interface{}{"message"},
})
assert.NoError(t, err)
assert.Equal(t, "prefixDEBUG message\n", buffer.String())
}
func TestStandardLogHandlerConcurrency(t *testing.T) {
iterations := 1000
buffer := &bytes.Buffer{}
handler := NewStandardLogHandler(buffer, "", 0)
logger := NewLogger(handler)
wg := sync.WaitGroup{}
wg.Add(iterations)
for i := 0; i < iterations; i++ {
go func(num int) {
logger.Infof("log %03d", num)
wg.Done()
}(i)
}
wg.Wait()
for line, err := buffer.ReadString('\n'); err == nil; line, err = buffer.ReadString('\n') {
assert.Len(t, line, 14)
}
}
func TestCannotClose(t *testing.T) {
buffer := &bytes.Buffer{}
handler := NewStandardLogHandler(buffer, "", 0)
err := handler.Close()
assert.Error(t, err)
}
func TestCanClose(t *testing.T) {
file, err := os.CreateTemp(t.TempDir(), "TestCanClose")
require.NoError(t, err)
handler := NewStandardLogHandler(file, "", 0)
err = handler.Close()
assert.NoError(t, err)
}
func TestChangeOutput(t *testing.T) {
buffer := &bytes.Buffer{}
handler := NewStandardLogHandler(os.Stdout, "", 0)
handler.SetOutput(buffer)
err := handler.LogEntry(LogEntry{
Level: LevelDebug,
Values: []interface{}{"message"},
})
assert.NoError(t, err)
assert.Equal(t, "DEBUG message\n", buffer.String())
}
func TestLogOnClosedOutput(t *testing.T) {
logFile := filepath.Join(t.TempDir(), "file.log")
file, err := os.Create(logFile)
require.NoError(t, err)
handler := NewStandardLogHandler(file, "", 0)
err = handler.Close()
assert.NoError(t, err)
err = handler.LogEntry(LogEntry{
Level: LevelDebug,
Values: []interface{}{"message"},
})
assert.Error(t, err)
}