-
Notifications
You must be signed in to change notification settings - Fork 2
/
glager.go
348 lines (296 loc) · 9.23 KB
/
glager.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// Package glager provides Gomega matchers to verify lager logging.
//
// See https://github.com/onsi/gomega and https://code.cloudfoundry.org/lager
// for more information.
package glager
import (
"bytes"
"encoding/json"
"fmt"
"io"
"code.cloudfoundry.org/lager/v3"
"github.com/onsi/gomega/format"
"github.com/onsi/gomega/gbytes"
"github.com/onsi/gomega/types"
)
type logEntry lager.LogFormat
type logEntries []logEntry
type logEntryData lager.Data
type option func(*logEntry)
// TestLogger embedds an actual lager logger and implements gbytes.BufferProvider.
// This comes in handy when used with the HaveLogged matcher.
type TestLogger struct {
lager.Logger
buf *gbytes.Buffer
}
// NewLogger returns a new TestLogger that can be used with the HaveLogged matcher.
// The returned logger uses log level lager.DEBUG.
func NewLogger(component string) *TestLogger {
buf := gbytes.NewBuffer()
log := lager.NewLogger(component)
log.RegisterSink(lager.NewWriterSink(buf, lager.DEBUG))
return &TestLogger{log, buf}
}
// Buffer implements gbytes.BufferProvider.Buffer.
func (l *TestLogger) Buffer() *gbytes.Buffer {
return l.buf
}
type logMatcher struct {
actual logEntries
expected logEntries
}
// HaveLogged is an alias for ContainSequence. It checks if the specified entries
// appear inside the log in the right sequence. The entries do not have to be
// contiguous in the log, all that matters is the order and the properties of the
// entries.
//
// Log entries passed to this mtcher do not have to be complete, i.e. you do not
// have to specify all available properties but only the ones you are actually
// interested in. Unspecified properties are being ignored when matching the
// entries, i.e they can have arbitrary values.
//
// This matcher works best when used with a TestLogger.
//
// Example:
//
// // instantiate glager.TestLogger inside your test and
// logger := NewLogger("test")
//
// // pass it to your code and use it in there to log stuff
// myFunc(logger)
//
// // verify logging inside your test, using the logger
// // in this example we are interested in the log level, the message, and the
// // data of the log entries
// Expect(logger).To(HaveLogged(
// Info(
// Message("test.myFunc"),
// Data("event", "start"),
// ),
// Info(
// Message("test.myFunc"),
// Data("event", "done"),
// ),
// ))
func HaveLogged(expectedSequence ...logEntry) types.GomegaMatcher {
return ContainSequence(expectedSequence...)
}
// ContainSequence checks if the specified entries appear inside the log in the
// right order. The entries do not have to be contiguous inide the log, all that
// matters is their respective order.
//
// Log entries passed to this mtcher do not have to be complete, i.e. you do not
// have to specify all available properties but only the ones you are actually
// interested in. Unspecified properties are being ignored when matching the
// entries, i.e they can have arbitrary values.
//
// This matcher works best when used with a Buffer.
//
// Example:
//
// // instantiate regular lager logger and register buffer as sink
// log := gbytes.NewBuffer()
// logger := lager.NewLogger("test")
// logger.RegisterSink(lager.NewWriterSink(log, lager.DEBUG))
//
// // pass it to your code and use it in there to log stuff
// myFunc(logger)
//
// // verify logging inside your test, using the log buffer
// // in this example we are only interested in the data of the log entries
// Expect(log).To(ContainSequence(
// Info(
// Data("event", "start"),
// ),
// Info(
// Data("event", "done"),
// ),
// ))
func ContainSequence(expectedSequence ...logEntry) types.GomegaMatcher {
return &logMatcher{
expected: expectedSequence,
}
}
// Info returns a log entry of type lager.INFO that can be used with the
// HaveLogged and ContainSequence matchers.
func Info(options ...option) logEntry {
return LogEntry(lager.INFO, options...)
}
// Debug returns a log entry of type lager.DEBUG that can be used with the
// HaveLogged and ContainSequence matchers.
func Debug(options ...option) logEntry {
return LogEntry(lager.DEBUG, options...)
}
// AnyErr can be used to check of arbitrary errors when matching Error entries.
var AnyErr error = nil
// Error returns a log entry of type lager.ERROR that can be used with the
// HaveLogged and ContainSequence matchers.
func Error(err error, options ...option) logEntry {
if err != nil {
options = append(options, Data("error", err.Error()))
}
return LogEntry(lager.ERROR, options...)
}
// Fatal returns a log entry of type lager.FATAL that can be used with the
// HaveLogged and ContainSequence matchers.
func Fatal(err error, options ...option) logEntry {
if err != nil {
options = append(options, Data("error", err.Error()))
}
return LogEntry(lager.FATAL, options...)
}
// LogEntry returns a log entry for the specified log level that can be used with
// the HaveLogged and ContainSequence matchers.
func LogEntry(logLevel lager.LogLevel, options ...option) logEntry {
entry := logEntry(lager.LogFormat{
LogLevel: logLevel,
Data: lager.Data{},
})
for _, option := range options {
option(&entry)
}
return entry
}
// Message specifies a string that represent the message of a given log entry.
func Message(msg string) option {
return func(e *logEntry) {
e.Message = msg
}
}
// Action is an alias for Message, lager uses the term action is used
// alternatively to message.
func Action(action string) option {
return Message(action)
}
// Source specifies a string that indicates the log source. The source of a
// lager logger is usually specified at instantiation time. Source is sometimes
// also called component.
func Source(src string) option {
return func(e *logEntry) {
e.Source = src
}
}
// Data specifies the data logged by a given log entry. Arguments are specified
// as an alternating sequence of keys (string) and values (interface{}).
func Data(kv ...interface{}) option {
if len(kv)%2 == 1 {
kv = append(kv, "")
}
return func(e *logEntry) {
for i := 0; i < len(kv); i += 2 {
key, ok := kv[i].(string)
if !ok {
err := fmt.Errorf("Invalid type for data key. Want string. Got %T:%v.", kv[i], kv[i])
panic(err)
}
e.Data[key] = kv[i+1]
}
}
}
// ContentsProvider implements Contents function.
type ContentsProvider interface {
// Contents returns a slice of bytes.
Contents() []byte
}
// Match is doing the actual matching for a given log assertion.
func (lm *logMatcher) Match(actual interface{}) (success bool, err error) {
var reader io.Reader
switch x := actual.(type) {
case gbytes.BufferProvider:
reader = bytes.NewReader(x.Buffer().Contents())
case ContentsProvider:
reader = bytes.NewReader(x.Contents())
case io.Reader:
reader = x
default:
return false, fmt.Errorf("ContainSequence must be passed an io.Reader, glager.ContentsProvider, or gbytes.BufferProvider. Got:\n%s", format.Object(actual, 1))
}
decoder := json.NewDecoder(reader)
lm.actual = logEntries{}
for {
var entry logEntry
if err := decoder.Decode(&entry); err == io.EOF {
break
} else if err != nil {
return false, err
}
lm.actual = append(lm.actual, entry)
}
actualEntries := lm.actual
for _, expected := range lm.expected {
i, found, err := actualEntries.indexOf(expected)
if err != nil {
return false, err
}
if !found {
return false, nil
}
actualEntries = actualEntries[i+1:]
}
return true, nil
}
// FailureMessage constructs a message for failed assertions.
func (lm *logMatcher) FailureMessage(actual interface{}) (message string) {
return fmt.Sprintf(
"Expected\n\t%s\nto contain log sequence \n\t%s",
format.Object(lm.actual, 0),
format.Object(lm.expected, 0),
)
}
// NegatedFailureMessage constructs a message for failed negative assertions.
func (lm *logMatcher) NegatedFailureMessage(actual interface{}) (message string) {
return fmt.Sprintf(
"Expected\n\t%s\nnot to contain log sequence \n\t%s",
format.Object(lm.actual, 0),
format.Object(lm.expected, 0),
)
}
func (entry logEntry) logData() logEntryData {
return logEntryData(entry.Data)
}
func (actual logEntry) contains(expected logEntry) (bool, error) {
if expected.Source != "" && actual.Source != expected.Source {
return false, nil
}
if expected.Message != "" && actual.Message != expected.Message {
return false, nil
}
if actual.LogLevel != expected.LogLevel {
return false, nil
}
containsData, err := actual.logData().contains(expected.logData())
if err != nil {
return false, err
}
return containsData, nil
}
func (actual logEntryData) contains(expected logEntryData) (bool, error) {
for expectedKey, expectedVal := range expected {
actualVal, found := actual[expectedKey]
if !found {
return false, nil
}
// this has been marshalled and unmarshalled before, no need to check err
actualJSON, _ := json.Marshal(actualVal)
expectedJSON, err := json.Marshal(expectedVal)
if err != nil {
return false, err
}
if string(actualJSON) != string(expectedJSON) {
return false, nil
}
}
return true, nil
}
func (entries logEntries) indexOf(entry logEntry) (int, bool, error) {
for i, actual := range entries {
containsEntry, err := actual.contains(entry)
if err != nil {
return 0, false, err
}
if containsEntry {
return i, true, nil
}
}
return 0, false, nil
}