-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtest.go
60 lines (53 loc) · 1.39 KB
/
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
package test
import (
"bufio"
"bytes"
"io"
"testing"
log "github.com/sirupsen/logrus"
)
// testingLogRedirector is inspired by https://github.com/sirupsen/logrus/issues/834
type testingLogRedirector struct {
lineBuffer bytes.Buffer
logger *log.Logger
originalOutput io.Writer
t *testing.T
}
// Dispose is documented in RedirectLogs.
func (t *testingLogRedirector) Dispose() {
rest := t.lineBuffer.Bytes()
if len(rest) > 0 {
t.t.Log(string(rest))
}
t.logger.SetOutput(t.originalOutput)
}
// Write implements the io.Writer interface.
func (t *testingLogRedirector) Write(p []byte) (n int, err error) {
n, _ = t.lineBuffer.Write(p)
for {
advance, token, _ := bufio.ScanLines(t.lineBuffer.Bytes(), false)
if advance == 0 {
return
}
t.t.Log(string(token))
t.lineBuffer.Next(advance)
}
}
// Disposable represents a resource that needs to be explicitly freed.
type Disposable interface {
Dispose()
}
// RedirectLogs redirects the output of logrus' standard logger to a testing.T and returns a Disposable that restores the standard logger's
// output to the output when RedirectLogs was called once Dispose is called.
func RedirectLogs(t *testing.T) Disposable {
logger := log.StandardLogger()
d := &testingLogRedirector{
logger: logger,
originalOutput: logger.Out,
t: t,
}
if !testing.Verbose() {
d.logger.SetOutput(d)
}
return d
}