-
Notifications
You must be signed in to change notification settings - Fork 1
/
test_handler.go
59 lines (52 loc) · 1.63 KB
/
test_handler.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
package clog
// TestHandler redirects all the logs to the testing framework logger
type TestHandler struct {
t TestLogInterface
}
// TestLogInterface for use with testing.B or testing.T
type TestLogInterface interface {
Log(args ...interface{})
Logf(format string, args ...interface{})
}
// NewTestHandler instantiates a new logger redirecting to the test framework logger
// or any other implementation of TestLogInterface for that matter
func NewTestHandler(t TestLogInterface) *TestHandler {
return &TestHandler{
t: t,
}
}
// SetTestLog install a test logger as the default logger.
// A test logger redirects all logs sent through the package methods to the Log/Logf methods of your test
//
// IMPORTANT: don't forget to CloseTestLog() at the end of the test
//
// Example:
//
// func TestLog(t *testing.T) {
// SetTestLog(t)
// defer CloseTestLog()
// // These two calls are equivalent:
// clog.Debug("debug message")
// t.Log("debug message")
// }
func SetTestLog(t TestLogInterface) {
SetDefaultLogger(NewLogger(NewTestHandler(t)))
}
// CloseTestLog at the end of the test otherwise the logger will keep a reference on t.
// For a description on how to use it, see SetTestLog()
func CloseTestLog() {
SetDefaultLogger(NewLogger(NewDiscardHandler()))
}
// LogEntry sends a log entry with the specified level
func (h *TestHandler) LogEntry(logEntry LogEntry) error {
if logEntry.Format == "" {
h.t.Log(append([]interface{}{logEntry.Level.String()}, logEntry.Values...)...)
return nil
}
h.t.Logf(logEntry.Level.String()+" "+logEntry.Format, logEntry.Values...)
return nil
}
// Verify interface
var (
_ Handler = &TestHandler{}
)