-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtesting.go
More file actions
69 lines (56 loc) · 1.66 KB
/
testing.go
File metadata and controls
69 lines (56 loc) · 1.66 KB
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
package logging
import (
"bufio"
"bytes"
testing "github.com/mitchellh/go-testing-interface"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type TestLogger struct {
instance *zap.Logger
stdout *bytes.Buffer
}
// Instance returns the actual *zap.Logger you should pass to your dependency
// to accumulate log lines and inspect them later on.
func (l *TestLogger) Instance() *zap.Logger {
return l.instance
}
// RecordedLines returns all the logged line seen, each line being a full fledged JSON value
func (w *TestLogger) RecordedLines(t testing.T) (out []string) {
scanner := bufio.NewScanner(w.stdout)
for succeed, line := next(scanner); succeed && scanner.Err() == nil; succeed, line = next(scanner) {
out = append(out, line)
}
if scanner.Err() != nil {
t.Errorf("test logger scanning logged lines fail unexpectedly: %w", scanner.Err())
}
return
}
func next(scanner *bufio.Scanner) (succeed bool, line string) {
succeed = scanner.Scan()
line = scanner.Text()
return
}
type bufferSyncer bytes.Buffer
func (b *bufferSyncer) Write(p []byte) (n int, err error) {
return (*bytes.Buffer)(b).Write(p)
}
func (b *bufferSyncer) Sync() error {
return nil
}
func NewTestLogger(t testing.T) *TestLogger {
stdout := bytes.NewBuffer(nil)
encoderCfg := zapcore.EncoderConfig{
MessageKey: "msg",
LevelKey: "level",
NameKey: "logger",
EncodeLevel: zapcore.LowercaseLevelEncoder,
EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeDuration: zapcore.StringDurationEncoder,
}
core := zapcore.NewCore(zapcore.NewJSONEncoder(encoderCfg), (*bufferSyncer)(stdout), zap.DebugLevel)
return &TestLogger{
instance: zap.New(core),
stdout: stdout,
}
}