-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathbot_test.go
490 lines (402 loc) · 11.7 KB
/
bot_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
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
package joe_test
import (
"bytes"
"errors"
"io"
"testing"
"time"
"github.com/go-joe/joe"
"github.com/go-joe/joe/joetest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest"
"go.uber.org/zap/zaptest/observer"
)
func TestBot_New(t *testing.T) {
logger := zaptest.NewLogger(t)
b := joe.New("test", joe.WithLogger(logger))
require.NotNil(t, b)
require.Equal(t, "test", b.Name)
require.NotNil(t, b.Auth)
require.NotNil(t, b.Logger)
require.NotNil(t, b.Brain)
require.NotNil(t, b.Adapter)
}
func TestBot_Run(t *testing.T) {
b := joetest.NewBot(t)
initEvt := make(chan bool)
b.Brain.RegisterHandler(func(evt joe.InitEvent) {
initEvt <- true
})
shutdownEvt := make(chan bool)
b.Brain.RegisterHandler(func(evt joe.ShutdownEvent) {
shutdownEvt <- true
})
runExit := make(chan bool)
go func() {
assert.NoError(t, b.Run())
runExit <- true
}()
wait(t, initEvt)
go b.Stop()
wait(t, shutdownEvt)
wait(t, runExit)
}
func TestBot_Respond(t *testing.T) {
b := joetest.NewBot(t)
handledMessages := make(chan joe.Message)
b.Respond("Hello (.+), this is a (.+)", func(msg joe.Message) error {
handledMessages <- msg
return nil
})
b.Start()
defer b.Stop()
b.Brain.Emit(joe.ReceiveMessageEvent{
Text: "Hello world, this is a test",
Channel: "XXX",
})
select {
case msg := <-handledMessages:
assert.Equal(t, "Hello world, this is a test", msg.Text)
assert.Equal(t, "XXX", msg.Channel)
assert.Equal(t, []string{"world", "test"}, msg.Matches)
case <-time.After(time.Second):
t.Error("Timeout")
}
}
func TestBot_Respond_Data(t *testing.T) {
b := joetest.NewBot(t)
handledMessages := make(chan joe.Message)
b.Respond("Test message", func(msg joe.Message) error {
handledMessages <- msg
return nil
})
b.Start()
defer b.Stop()
type CustomData struct {
Foo string
}
// Test if extra data passed via the ReceiveMessageEvent is copied to the Message
data := &CustomData{Foo: "bar"}
b.Brain.Emit(joe.ReceiveMessageEvent{
Text: "Test message",
Data: data,
})
select {
case msg := <-handledMessages:
assert.Equal(t, data, msg.Data)
case <-time.After(time.Second):
t.Error("Timeout")
}
}
func TestBot_Respond_AuthorID(t *testing.T) {
b := joetest.NewBot(t)
handledMessages := make(chan joe.Message)
b.Respond("Test message", func(msg joe.Message) error {
handledMessages <- msg
return nil
})
b.Start()
defer b.Stop()
// Test if author ID passed via the ReceiveMessageEvent is copied to the Message
b.Brain.Emit(joe.ReceiveMessageEvent{
Text: "Test message",
AuthorID: "Friedrich",
})
select {
case msg := <-handledMessages:
assert.Equal(t, "Friedrich", msg.AuthorID)
case <-time.After(time.Second):
t.Error("Timeout")
}
}
func TestBot_Respond_Matches(t *testing.T) {
b := joetest.NewBot(t)
handledMessages := make(chan joe.Message)
b.Respond("Remember (.+) is (.+)", func(msg joe.Message) error {
handledMessages <- msg
return nil
})
b.Start()
defer b.Stop()
cases := map[string][]string{
"Remember foo is bar": {"foo", "bar"},
"remember a is b": {"a", "b"},
"remember FOO IS BAR": {"FOO", "BAR"},
}
for input, matches := range cases {
b.Brain.Emit(joe.ReceiveMessageEvent{Text: input})
select {
case msg := <-handledMessages:
assert.Equal(t, matches, msg.Matches)
case <-time.After(time.Second):
t.Error("timeout")
}
}
}
func TestBot_Respond_No_Matches(t *testing.T) {
b := joetest.NewBot(t)
b.Respond("Hello world, this is a test", func(msg joe.Message) error {
t.Errorf("Handler should not match but got %+v", msg)
return nil
})
nonMatches := []string{
"Foobar", // entirely different
"Hello world", // only the prefix
"this is a test", // only the suffix
"world", // only a substring
"Hello world this is a test", // missing comma
"TEST Hello world, this is a test", // additional prefix
"Hello world, this is a test TEST", // additional suffix
"TEST Hello world, this is a test TEST", // additional prefix and suffix
"Hello world, TEST this is a test", // additional word in the middle
}
b.Start()
defer b.Stop()
for _, txt := range nonMatches {
b.EmitSync(joe.ReceiveMessageEvent{Text: txt})
}
}
func TestBot_Respond_MultipleMatchingHandlers(t *testing.T) {
b := joetest.NewBot(t)
var firstHandlerExecuted bool
b.Respond("hello", func(msg joe.Message) error {
firstHandlerExecuted = true
return nil
})
var secondHandlerExecuted bool
b.Respond(".*", func(msg joe.Message) error {
secondHandlerExecuted = true
return nil
})
b.Start()
defer b.Stop()
firstHandlerExecuted, secondHandlerExecuted = false, false // reset
b.EmitSync(joe.ReceiveMessageEvent{Text: "Hello"})
assert.True(t, firstHandlerExecuted, "first handler should have been executed")
assert.False(t, secondHandlerExecuted, "second handler should not have been executed")
firstHandlerExecuted, secondHandlerExecuted = false, false // reset
b.EmitSync(joe.ReceiveMessageEvent{Text: "trigger default"})
assert.False(t, firstHandlerExecuted, "first handler should not have been executed")
assert.True(t, secondHandlerExecuted, "second handler should have been executed")
}
func TestBot_RespondRegex(t *testing.T) {
b := joetest.NewBot(t)
handledMessages := make(chan joe.Message, 1)
b.RespondRegex(`name is ([^\s]+)$`, func(msg joe.Message) error {
t.Logf("Received joe.Message %q", msg.Text)
handledMessages <- msg
return nil
})
b.Start()
defer b.Stop()
cases := map[string][]string{ // maps input to expected matches
"name is Joe": {"Joe"}, // simple case
"NAME IS Joe": {"Joe"}, // simple case, case insensitive
"Hello, my name is Joe": {"Joe"}, // match on substrings
"My name is Joe and what is yours?": nil, // respect end of input anchor
"": nil, // should not match but also not panic
}
for input, matches := range cases {
b.EmitSync(joe.ReceiveMessageEvent{Text: input})
if matches == nil {
select {
case msg := <-handledMessages:
t.Errorf("message handler should not have been called with %q", msg.Text)
continue
default:
// no joe.Message as expected, lets move on
continue
}
}
// Check joe.Message was handled as expected
select {
case msg := <-handledMessages:
assert.Equal(t, matches, msg.Matches)
case <-time.After(time.Second):
t.Errorf("timeout: %s", input)
}
}
}
func TestBot_RespondRegex_Empty(t *testing.T) {
b := joetest.NewBot(t)
b.RespondRegex("", func(msg joe.Message) error {
t.Error("should never match")
return nil
})
b.Start()
defer b.Stop()
cases := []string{
"",
" ",
"\n",
"\t",
"foobar",
"foo bar",
}
for _, input := range cases {
b.EmitSync(joe.ReceiveMessageEvent{Text: input})
}
}
func TestBot_RespondRegex_Invalid(t *testing.T) {
b := joetest.NewBot(t)
b.RespondRegex("this is not a [valid regular expression", func(msg joe.Message) error {
t.Error("should never match")
return nil
})
err := b.Run()
require.Error(t, err)
require.Regexp(t, `invalid event handlers: .+\.go:\d+: error parsing regexp: missing closing \]`, err.Error())
}
func TestBot_Auth(t *testing.T) {
b := joetest.NewBot(t)
b.Respond("auth test", func(msg joe.Message) error {
err := b.Auth.CheckPermission("test.foo", msg.AuthorID)
if err != nil {
return msg.RespondE("I'm sorry Dave, I'm afraid I can't do that")
}
return msg.RespondE("OK")
})
b.Start()
assert.Equal(t, "test > ", b.ReadOutput())
userID := "42"
b.EmitSync(joe.ReceiveMessageEvent{Text: "auth test", AuthorID: userID})
assert.Equal(t, "I'm sorry Dave, I'm afraid I can't do that\n", b.ReadOutput())
ok, err := b.Auth.Grant("test", userID)
require.NoError(t, err)
assert.True(t, ok)
b.EmitSync(joe.ReceiveMessageEvent{Text: "auth test", AuthorID: userID})
assert.Equal(t, "OK\n", b.ReadOutput())
b.Stop()
}
func TestBot_CloseAdapter(t *testing.T) {
input := &testCloser{Reader: new(bytes.Buffer)}
output := new(bytes.Buffer)
testAdapter := joe.ModuleFunc(func(conf *joe.Config) error {
a := joe.NewCLIAdapter("test", conf.Logger("adapter"))
a.Input = input
a.Output = output
conf.SetAdapter(a)
return nil
})
b := joetest.NewBot(t, testAdapter)
b.Start()
b.Stop()
assert.True(t, input.Closed)
}
func TestBot_ModuleErrors(t *testing.T) {
modA := joe.ModuleFunc(func(conf *joe.Config) error {
return errors.New("error in module A")
})
modB := joe.ModuleFunc(func(conf *joe.Config) error {
return errors.New("error in module B")
})
b := joetest.NewBot(t, modA, modB)
err := b.Run()
assert.EqualError(t, err, "failed to initialize bot: error in module A; error in module B")
}
func TestBot_RegistrationErrors(t *testing.T) {
b := joetest.NewBot(t)
b.Brain.RegisterHandler(42) // not a valid handler
b.Brain.RegisterHandler(func() {}) // not a valid handler
err := b.Run()
require.Error(t, err)
t.Log(err.Error())
assert.Regexp(t, "invalid event handlers: .+", err.Error())
assert.Regexp(t, "event handler is no function", err.Error())
assert.Regexp(t, "event handler needs one or two arguments", err.Error())
}
func TestBot_Say(t *testing.T) {
a := new(MockAdapter)
b := joetest.NewBot(t)
b.Adapter = a
a.On("Send", "Hello world", "foo").Return(nil)
b.Say("foo", "Hello world")
a.On("Send", "Hello world: the answer is 42", "bar").Return(nil)
b.Say("bar", "Hello %s: the answer is %d", "world", 42)
a.AssertExpectations(t)
}
func TestBot_Say_Error(t *testing.T) {
obs, logs := observer.New(zap.DebugLevel)
logger := zap.New(obs)
a := new(MockAdapter)
b := joetest.NewBot(t)
b.Adapter = a
b.Logger = logger
adapterErr := errors.New("watch your language")
a.On("Send", "damn it", "baz").Return(adapterErr)
b.Say("baz", "damn it")
assert.Equal(t, []observer.LoggedEntry{{
Entry: zapcore.Entry{Level: zap.ErrorLevel, Message: "Failed to send message"},
Context: []zapcore.Field{zap.Error(adapterErr)},
}}, logs.AllUntimed())
a.AssertExpectations(t)
}
// TestBot_HandlerEvents tests if event handler functions can safely (i.e. without
// deadlock or panic) emit new events.
func TestBot_HandlerEvents(t *testing.T) {
b := joetest.NewBot(t)
type TestEvent struct {
N int
}
var receivedEvents []TestEvent
b.Brain.RegisterHandler(func(evt TestEvent) {
receivedEvents = append(receivedEvents, evt)
})
msgEvents := 10
testEventsPerMsg := 10
b.Brain.RegisterHandler(func(joe.ReceiveMessageEvent) {
// This test checks that emitting events from within an event handler
// does not deadlock the Brain.
for i := 0; i < testEventsPerMsg; i++ {
// TODO: if we use a callback here, will it then deadlock?
b.Brain.Emit(TestEvent{N: i})
}
})
b.Start()
for i := 0; i < msgEvents; i++ {
b.EmitSync(joe.ReceiveMessageEvent{})
}
b.Stop() // should block until all events have been processed
require.Equal(t, msgEvents*testEventsPerMsg, len(receivedEvents), "did not receive enough events")
for i := 0; i < msgEvents; i++ {
for j := 0; j < testEventsPerMsg; j++ {
idx := i*testEventsPerMsg + j
n := receivedEvents[idx].N
require.Equal(t, j, n, "i=%d j=%d", i, j)
}
}
}
type testCloser struct {
Closed bool
io.Reader
}
func (c *testCloser) Close() error {
c.Closed = true
return nil
}
func wait(t *testing.T, c chan bool) {
select {
case <-c:
return
case <-time.After(time.Second):
t.Fatal("timeout")
}
}
type MockAdapter struct {
mock.Mock
}
func (a *MockAdapter) RegisterAt(b *joe.Brain) {
a.Called(b)
}
func (a *MockAdapter) Send(text, channel string) error {
args := a.Called(text, channel)
return args.Error(0)
}
func (a *MockAdapter) Close() error {
args := a.Called()
return args.Error(0)
}