-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtesting.go
68 lines (57 loc) · 1.61 KB
/
testing.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
package log
// test.go contains helpers for both internal and external testing
import (
"sync"
"time"
)
// entry is only used for test, we do not use it as contract for interface
type entry struct {
level Level
time time.Time
msg string
context Fields
fields Fields
source Caller
}
var _ Handler = (*TestHandler)(nil)
// TestHandler stores log as entry, its slice is protected by a RWMutex and safe for concurrent use
type TestHandler struct {
mu sync.RWMutex
entries []entry
}
// NewTestHandler returns a test handler, it should only be used in test,
// a concrete type instead of Handler interface is returned to reduce unnecessary type cast in test
func NewTestHandler() *TestHandler {
return &TestHandler{}
}
func (h *TestHandler) HandleLog(level Level, time time.Time, msg string, source Caller, context Fields, fields Fields) {
h.mu.Lock()
h.entries = append(h.entries, entry{level: level, time: time, msg: msg, source: source, context: copyFields(context), fields: copyFields(fields)})
h.mu.Unlock()
}
// Flush implements Handler interface
func (h *TestHandler) Flush() {
// nop
}
// HasLog checks if a log with specified level and message exists in slice
// TODO: support field, source etc.
func (h *TestHandler) HasLog(level Level, msg string) bool {
h.mu.RLock()
defer h.mu.RUnlock()
for _, e := range h.entries {
if e.level == level && e.msg == msg {
return true
}
}
return false
}
func (h *TestHandler) getLogByMessage(msg string) (entry, bool) {
h.mu.RLock()
defer h.mu.RUnlock()
for _, e := range h.entries {
if e.msg == msg {
return e, true
}
}
return entry{}, false
}