-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathrunner_test.go
1155 lines (1007 loc) · 25.7 KB
/
runner_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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package sarah
import (
"context"
"errors"
"fmt"
"github.com/oklahomer/go-kasumi/logger"
"io"
"log"
"os"
"reflect"
"regexp"
"strconv"
"sync"
"testing"
"time"
)
func TestMain(m *testing.M) {
oldLogger := logger.GetLogger()
defer logger.SetLogger(oldLogger)
// Suppress log output in test by default
l := log.New(io.Discard, "dummyLog", 0)
logger.SetLogger(logger.NewWithStandardLogger(l))
code := m.Run()
os.Exit(code)
}
func SetupAndRun(fnc func()) {
// Initialize package variables
runnerStatus = &status{}
options = &optionHolder{}
fnc()
}
type DummyConfigWatcher struct {
ReadFunc func(context.Context, BotType, string, interface{}) error
WatchFunc func(context.Context, BotType, string, func()) error
UnwatchFunc func(BotType) error
}
func (w *DummyConfigWatcher) Read(botCtx context.Context, botType BotType, id string, configPtr interface{}) error {
return w.ReadFunc(botCtx, botType, id, configPtr)
}
func (w *DummyConfigWatcher) Watch(ctx context.Context, botType BotType, id string, callback func()) error {
return w.WatchFunc(ctx, botType, id, callback)
}
func (w *DummyConfigWatcher) Unwatch(botType BotType) error {
return w.UnwatchFunc(botType)
}
type DummyWorker struct {
EnqueueFunc func(func()) error
}
func (w *DummyWorker) Enqueue(fnc func()) error {
return w.EnqueueFunc(fnc)
}
func TestNewConfig(t *testing.T) {
config := NewConfig()
if config == nil {
t.Fatal("Expected *Config is not returned.")
}
}
func Test_optionHolder_register(t *testing.T) {
opt := func(_ *runner) {}
holder := &optionHolder{}
holder.register(opt)
if len(holder.stashed) != 1 {
t.Fatalf("Expected number of options are not stashed: %d.", len(holder.stashed))
}
if reflect.ValueOf(holder.stashed[0]).Pointer() != reflect.ValueOf(opt).Pointer() {
t.Error("Given option is not stashed.")
}
}
func Test_optionHandler_apply(t *testing.T) {
called := 0
holder := &optionHolder{}
holder.stashed = []func(*runner){
func(_ *runner) {
called++
},
func(_ *runner) {
called++
},
}
r := &runner{}
holder.apply(r)
if called != 2 {
t.Errorf("Unexpected number of options are applied: %d.", called)
}
}
func TestRegisterAlerter(t *testing.T) {
SetupAndRun(func() {
alerter := &DummyAlerter{}
RegisterAlerter(alerter)
r := &runner{
alerters: &alerters{},
}
for _, v := range options.stashed {
v(r)
}
if len(*r.alerters) != 1 {
t.Fatalf("Expected number of alerter is not registered: %d.", len(*r.alerters))
}
if (*r.alerters)[0] != alerter {
t.Error("Given alerter is not registered.")
}
})
}
func TestRegisterBot(t *testing.T) {
SetupAndRun(func() {
bot := &DummyBot{}
RegisterBot(bot)
r := &runner{
alerters: &alerters{},
}
for _, v := range options.stashed {
v(r)
}
if len(r.bots) != 1 {
t.Fatalf("Expected number of bot is not registered: %d.", len(r.bots))
}
if r.bots[0] != bot {
t.Error("Given bot is not registered.")
}
})
}
func TestRegisterCommand(t *testing.T) {
SetupAndRun(func() {
var botType BotType = "dummy"
command := &DummyCommand{}
RegisterCommand(botType, command)
r := &runner{
commands: map[BotType][]Command{},
}
for _, v := range options.stashed {
v(r)
}
if len(r.commands[botType]) != 1 {
t.Fatalf("Expected number of Command is not registered: %d.", len(r.commandProps[botType]))
}
if r.commands[botType][0] != command {
t.Error("Given Command is not registered.")
}
})
}
func TestRegisterCommandProps(t *testing.T) {
SetupAndRun(func() {
var botType BotType = "dummy"
props := &CommandProps{
botType: botType,
}
RegisterCommandProps(props)
r := &runner{
commandProps: map[BotType][]*CommandProps{},
}
for _, v := range options.stashed {
v(r)
}
if len(r.commandProps[botType]) != 1 {
t.Fatalf("Expected number of CommandProps is not registered: %d.", len(r.commandProps[botType]))
}
if r.commandProps[botType][0] != props {
t.Error("Given CommandProps is not registered.")
}
})
}
func TestRegisterScheduledTask(t *testing.T) {
SetupAndRun(func() {
var botType BotType = "dummy"
task := &DummyScheduledTask{}
RegisterScheduledTask(botType, task)
r := &runner{
scheduledTasks: map[BotType][]ScheduledTask{},
}
for _, v := range options.stashed {
v(r)
}
if len(r.scheduledTasks[botType]) != 1 {
t.Fatalf("Expected number of ScheduledTask is not registered: %d.", len(r.scheduledTasks[botType]))
}
if r.scheduledTasks[botType][0] != task {
t.Error("Given ScheduledTask is not registered.")
}
})
}
func TestRegisterScheduledTaskProps(t *testing.T) {
SetupAndRun(func() {
var botType BotType = "dummy"
props := &ScheduledTaskProps{
botType: botType,
}
RegisterScheduledTaskProps(props)
r := &runner{
scheduledTaskProps: map[BotType][]*ScheduledTaskProps{},
}
for _, v := range options.stashed {
v(r)
}
if len(r.scheduledTaskProps[botType]) != 1 {
t.Fatalf("Expected number of ScheduledTaskProps is not registered: %d.", len(r.scheduledTaskProps[botType]))
}
if r.scheduledTaskProps[botType][0] != props {
t.Error("Given ScheduledTaskProps is not registered.")
}
})
}
func TestRegisterConfigWatcher(t *testing.T) {
SetupAndRun(func() {
watcher := &DummyConfigWatcher{}
RegisterConfigWatcher(watcher)
r := &runner{}
for _, v := range options.stashed {
v(r)
}
if r.configWatcher == nil {
t.Fatal("ConfigWatcher is not set")
}
if r.configWatcher != watcher {
t.Error("Given ConfigWatcher is not set.")
}
})
}
func TestRegisterWorker(t *testing.T) {
SetupAndRun(func() {
worker := &DummyWorker{}
RegisterWorker(worker)
r := &runner{}
for _, v := range options.stashed {
v(r)
}
if r.worker == nil {
t.Fatal("Worker is not set")
}
if r.worker != worker {
t.Error("Given Worker is not set.")
}
})
}
func TestRegisterBotErrorSupervisor(t *testing.T) {
SetupAndRun(func() {
supervisor := func(_ BotType, _ error) *SupervisionDirective {
return nil
}
RegisterBotErrorSupervisor(supervisor)
r := &runner{}
for _, v := range options.stashed {
v(r)
}
if r.superviseError == nil {
t.Fatal("superviseError is not set.")
}
if reflect.ValueOf(r.superviseError).Pointer() != reflect.ValueOf(supervisor).Pointer() {
t.Error("Passed function is not set.")
}
})
}
func TestRun(t *testing.T) {
SetupAndRun(func() {
config := &Config{
TimeZone: time.UTC.String(),
}
// Initial call with valid setting should work.
err := Run(context.Background(), config)
if err != nil {
t.Fatalf("Unexpected error is returned: %s.", err.Error())
}
err = Run(context.Background(), config)
if err == nil {
t.Fatal("Expected error is not returned.")
}
})
}
func TestRun_WithInvalidConfig(t *testing.T) {
SetupAndRun(func() {
config := &Config{
TimeZone: "INVALID",
}
err := Run(context.Background(), config)
if err == nil {
t.Error("Expected error is not returned.")
}
})
}
func Test_newRunner(t *testing.T) {
SetupAndRun(func() {
config := &Config{
TimeZone: time.UTC.String(),
}
r, e := newRunner(context.Background(), config)
if e != nil {
t.Fatalf("Unexpected error is returned: %s.", e.Error())
}
if r == nil {
t.Fatal("runner instance is not returned.")
}
if r.configWatcher == nil {
t.Error("Default ConfigWatcher should be set when PluginConfigRoot is not empty.")
}
if r.scheduler == nil {
t.Error("Scheduler must run at this point.")
}
if r.worker == nil {
t.Error("Default Worker should be set.")
}
})
}
func Test_newRunner_WithTimeZoneError(t *testing.T) {
SetupAndRun(func() {
config := &Config{
TimeZone: "DUMMY",
}
_, e := newRunner(context.Background(), config)
if e == nil {
t.Fatal("Expected error is not returned.")
}
})
}
func Test_runner_run(t *testing.T) {
SetupAndRun(func() {
var botType BotType = "myBot"
bot := &DummyBot{
BotTypeValue: botType,
RunFunc: func(ctx context.Context, _ func(Input) error, _ func(error)) {
<-ctx.Done()
},
}
config := &Config{
TimeZone: time.Now().Location().String(),
}
r := &runner{
config: config,
bots: []Bot{
bot,
},
}
rootCtx := context.Background()
ctx, cancel := context.WithCancel(rootCtx)
go r.run(ctx)
time.Sleep(1 * time.Second)
status := CurrentStatus()
if len(status.Bots) != 1 {
t.Fatalf("Expected number of Bot is not registered.")
}
if status.Bots[0].Type != botType {
t.Errorf("Unexpected BotStatus.Type is returned: %s.", status.Bots[0].Type)
}
if !status.Bots[0].Running {
t.Error("BotStatus.Running should be true at this point.")
}
cancel()
time.Sleep(1 * time.Second)
if CurrentStatus().Bots[0].Running {
t.Error("BotStatus.Running should not be true at this point.")
}
})
}
func Test_runner_runBot(t *testing.T) {
SetupAndRun(func() {
var botType BotType = "myBot"
// Prepare Bot to be run
passedCommand := make(chan Command, 1)
bot := &DummyBot{
BotTypeValue: botType,
AppendCommandFunc: func(cmd Command) {
passedCommand <- cmd
},
RunFunc: func(_ context.Context, _ func(Input) error, _ func(error)) {},
}
// Prepare command to be configured on the fly
commandProps := &CommandProps{
botType: botType,
identifier: "dummy",
matchFunc: func(input Input) bool {
return regexp.MustCompile(`^\.echo`).MatchString(input.Message())
},
commandFunc: func(_ context.Context, _ Input, _ ...CommandConfig) (*CommandResponse, error) {
return nil, nil
},
instructionFunc: func(_ *HelpInput) string {
return ".echo foo"
},
}
// Prepare scheduled task to be configured on the fly
dummySchedule := "@hourly"
dummyTaskConfig := &DummyScheduledTaskConfig{ScheduleValue: dummySchedule}
scheduledTaskProps := &ScheduledTaskProps{
botType: botType,
identifier: "dummyTask",
taskFunc: func(_ context.Context, _ ...TaskConfig) ([]*ScheduledTaskResult, error) {
return nil, nil
},
schedule: dummySchedule,
config: dummyTaskConfig,
defaultDestination: "",
}
// Configure runner
config := &Config{
TimeZone: time.Now().Location().String(),
}
alerted := make(chan struct{}, 1)
r := &runner{
config: config,
bots: []Bot{bot},
commandProps: map[BotType][]*CommandProps{
bot.BotType(): {
commandProps,
},
},
scheduledTaskProps: map[BotType][]*ScheduledTaskProps{
bot.BotType(): {
scheduledTaskProps,
},
},
scheduledTasks: map[BotType][]ScheduledTask{
bot.BotType(): {
&DummyScheduledTask{},
&DummyScheduledTask{ScheduleValue: "@every 1m"},
},
},
configWatcher: &DummyConfigWatcher{
ReadFunc: func(_ context.Context, _ BotType, _ string, _ interface{}) error {
return nil
},
WatchFunc: func(_ context.Context, _ BotType, _ string, _ func()) error {
return nil
},
UnwatchFunc: func(_ BotType) error {
return nil
},
},
worker: &DummyWorker{
EnqueueFunc: func(fnc func()) error {
return nil
},
},
scheduler: &DummyScheduler{
UpdateFunc: func(_ BotType, _ ScheduledTask, _ func()) error {
return nil
},
RemoveFunc: func(_ BotType, _ string) {},
},
alerters: &alerters{
&DummyAlerter{
AlertFunc: func(_ context.Context, _ BotType, err error) error {
alerted <- struct{}{}
return nil
},
},
},
}
// Let it run
rootCtx := context.Background()
runnerCtx, cancelRunner := context.WithCancel(rootCtx)
finished := make(chan bool)
go func() {
r.runBot(runnerCtx, bot)
finished <- true
}()
time.Sleep(1 * time.Second)
cancelRunner()
select {
case cmd := <-passedCommand:
if cmd == nil || cmd.Identifier() != commandProps.identifier {
t.Errorf("Stashed CommandPropsBuilder was not properly configured: %#v.", passedCommand)
}
case <-time.NewTimer(10 * time.Second).C:
t.Fatal("CommandPropsBuilder was not properly built.")
}
select {
case <-finished:
// O.K.
case <-time.NewTimer(10 * time.Second).C:
t.Error("Runner is not finished.")
}
if CurrentStatus().Running {
t.Error("Status.Running should be false at this point.")
}
select {
case <-alerted:
// O.K.
case <-time.NewTimer(10 * time.Second).C:
t.Error("Alert should be sent no matter how runner is canceled.")
}
})
}
func Test_runner_runBot_WithPanic(t *testing.T) {
SetupAndRun(func() {
var botType BotType = "myBot"
// Prepare Bot to be run
bot := &DummyBot{
BotTypeValue: botType,
AppendCommandFunc: func(cmd Command) {
},
RunFunc: func(_ context.Context, _ func(Input) error, _ func(error)) {
panic("panic on runner.Run")
},
}
// Configure runner
config := &Config{
TimeZone: time.Now().Location().String(),
}
alerted := make(chan struct{}, 1)
r := &runner{
config: config,
bots: []Bot{bot},
alerters: &alerters{
&DummyAlerter{
AlertFunc: func(_ context.Context, _ BotType, err error) error {
alerted <- struct{}{}
return nil
},
},
},
}
if CurrentStatus().Running {
t.Error("Status.Running should be false at this point.")
}
// Let it run
rootCtx := context.Background()
runnerCtx, cancel := context.WithCancel(rootCtx)
defer cancel()
finished := make(chan bool)
go func() {
r.runBot(runnerCtx, bot)
finished <- true
}()
time.Sleep(1 * time.Second)
select {
case <-finished:
// O.K.
case <-time.NewTimer(10 * time.Second).C:
t.Error("Runner is not finished.")
}
if CurrentStatus().Running {
t.Error("Status.Running should be false at this point.")
}
select {
case <-alerted:
// O.K.
case <-time.NewTimer(10 * time.Second).C:
t.Error("Alert should be sent no matter how runner is canceled.")
}
})
}
func Test_runner_superviseBot(t *testing.T) {
tests := []struct {
escalated error
directive *SupervisionDirective
shutdown bool
}{
{
escalated: NewBotNonContinuableError("this should stop Bot"),
shutdown: true,
},
{
escalated: errors.New("plain error"),
directive: nil,
shutdown: false,
},
{
escalated: errors.New("plain error"),
directive: &SupervisionDirective{
AlertingErr: errors.New("this is sent via alerter"),
StopBot: true,
},
shutdown: true,
},
{
escalated: errors.New("plain error"),
directive: &SupervisionDirective{
AlertingErr: nil,
StopBot: true,
},
shutdown: true,
},
{
escalated: errors.New("plain error"),
directive: &SupervisionDirective{
AlertingErr: errors.New("this is sent via alerter"),
StopBot: false,
},
shutdown: false,
},
{
escalated: errors.New("plain error"),
directive: &SupervisionDirective{
AlertingErr: nil,
StopBot: false,
},
shutdown: false,
},
}
alerted := make(chan error, 1)
for i, tt := range tests {
t.Run(strconv.Itoa(i+1), func(t *testing.T) {
r := &runner{
alerters: &alerters{
&DummyAlerter{
AlertFunc: func(_ context.Context, _ BotType, err error) error {
panic("Panic should not affect other alerters' behavior.")
},
},
&DummyAlerter{
AlertFunc: func(_ context.Context, _ BotType, err error) error {
alerted <- err
return nil
},
},
},
superviseError: func(_ BotType, _ error) *SupervisionDirective {
return tt.directive
},
}
rootCxt := context.Background()
botCtx, errSupervisor := r.superviseBot(rootCxt, "DummyBotType")
// Make sure the Bot state is currently active
select {
case <-botCtx.Done():
t.Error("Bot context should not be canceled at this point.")
default:
// O.K.
}
// Escalate an error
errSupervisor(tt.escalated)
if tt.shutdown {
// Bot should be canceled
select {
case <-botCtx.Done():
// O.K.
case <-time.NewTimer(1 * time.Second).C:
t.Error("Bot context should be canceled at this point.")
}
if e := botCtx.Err(); e != context.Canceled {
t.Errorf("botCtx.Err() must return context.Canceled, but was %#v", e)
}
}
if _, ok := tt.escalated.(*BotNonContinuableError); ok {
// When Bot escalate an non-continuable error, then alerter should be called.
select {
case e := <-alerted:
if e != tt.escalated {
t.Errorf("Unexpected error value is passed: %#v", e)
}
case <-time.NewTimer(1 * time.Second).C:
t.Error("Alerter is not called.")
}
} else if tt.directive != nil && tt.directive.AlertingErr != nil {
select {
case e := <-alerted:
if e != tt.directive.AlertingErr {
t.Errorf("Unexpected error value is passed: %#v", e)
}
case <-time.NewTimer(1 * time.Second).C:
t.Error("Alerter is not called.")
}
}
// See if a succeeding call block
nonBlocking := make(chan bool)
go func() {
errSupervisor(errors.New("succeeding calls should never block"))
nonBlocking <- true
}()
select {
case <-nonBlocking:
// O.K.
case <-time.NewTimer(10 * time.Second).C:
t.Error("Succeeding error escalation blocks.")
}
})
}
}
func Test_executeScheduledTask(t *testing.T) {
SetupAndRun(func() {
dummyContent := "dummy content"
dummyDestination := "#dummyDestination"
defaultDestination := "#defaultDestination"
type returnVal struct {
results []*ScheduledTaskResult
error error
}
testSets := []struct {
returnVal *returnVal
defaultDestination OutputDestination
}{
{returnVal: &returnVal{nil, nil}},
{returnVal: &returnVal{nil, errors.New("dummy")}},
// Destination is given by neither task result nor configuration, which ends up with early return
{returnVal: &returnVal{[]*ScheduledTaskResult{{Content: dummyContent}}, nil}},
// Destination is given by configuration
{returnVal: &returnVal{[]*ScheduledTaskResult{{Content: dummyContent}}, nil}, defaultDestination: defaultDestination},
// Destination is given by task result
{returnVal: &returnVal{[]*ScheduledTaskResult{{Content: dummyContent, Destination: dummyDestination}}, nil}},
}
var sendingOutput []Output
dummyBot := &DummyBot{SendMessageFunc: func(_ context.Context, output Output) {
sendingOutput = append(sendingOutput, output)
}}
for _, testSet := range testSets {
task := &scheduledTask{
identifier: "dummy",
taskFunc: func(_ context.Context, _ ...TaskConfig) ([]*ScheduledTaskResult, error) {
val := testSet.returnVal
return val.results, val.error
},
defaultDestination: testSet.defaultDestination,
configWrapper: &taskConfigWrapper{
value: &DummyScheduledTaskConfig{},
mutex: &sync.RWMutex{},
},
}
executeScheduledTask(context.TODO(), dummyBot, task)
}
if len(sendingOutput) != 2 {
t.Fatalf("Expecting sending method to be called twice, but was called %d time(s).", len(sendingOutput))
}
if sendingOutput[0].Content() != dummyContent || sendingOutput[0].Destination() != defaultDestination {
t.Errorf("Sending output differs from expecting one: %#v.", sendingOutput)
}
if sendingOutput[1].Content() != dummyContent || sendingOutput[1].Destination() != dummyDestination {
t.Errorf("Sending output differs from expecting one: %#v.", sendingOutput)
}
})
}
func Test_setupInputReceiver(t *testing.T) {
SetupAndRun(func() {
responded := make(chan bool, 1)
worker := &DummyWorker{
EnqueueFunc: func(fnc func()) error {
fnc()
return nil
},
}
bot := &DummyBot{
BotTypeValue: "DUMMY",
RespondFunc: func(_ context.Context, input Input) error {
responded <- true
return errors.New("error is returned, but still doesn't block")
},
}
receiveInput := setupInputReceiver(context.TODO(), bot, worker)
if err := receiveInput(&DummyInput{}); err != nil {
t.Errorf("Error should not be returned at this point: %s.", err.Error())
}
select {
case <-responded:
// O.K.
case <-time.NewTimer(10 * time.Second).C:
t.Error("Received input was not processed.")
}
})
}
func Test_setupInputReceiver_BlockedInputError(t *testing.T) {
SetupAndRun(func() {
bot := &DummyBot{}
worker := &DummyWorker{
EnqueueFunc: func(fnc func()) error {
return errors.New("any error should result in BlockedInputError")
},
}
receiveInput := setupInputReceiver(context.TODO(), bot, worker)
err := receiveInput(&DummyInput{})
if err == nil {
t.Fatal("Expected error is not returned.")
}
if _, ok := err.(*BlockedInputError); !ok {
t.Fatalf("Expected error type is not returned: %T.", err)
}
})
}
func Test_registerCommands(t *testing.T) {
SetupAndRun(func() {
tests := []struct {
configWatcher ConfigWatcher
props []*CommandProps
commands []Command
callback bool
regNum int
}{
{
configWatcher: &DummyConfigWatcher{
WatchFunc: func(_ context.Context, _ BotType, _ string, _ func()) error {
return nil
},
},
props: []*CommandProps{
{},
},
callback: false,
regNum: 1,
},
{
configWatcher: &DummyConfigWatcher{
ReadFunc: func(_ context.Context, _ BotType, _ string, _ interface{}) error {
return errors.New("configuration error")
},
WatchFunc: func(_ context.Context, _ BotType, _ string, _ func()) error {
return errors.New("subscription error")
},
},
props: []*CommandProps{
{
config: struct{}{},
},
},
callback: false,
regNum: 0,
},
{
configWatcher: &DummyConfigWatcher{
ReadFunc: func(_ context.Context, _ BotType, _ string, _ interface{}) error {
return nil
},
WatchFunc: func(_ context.Context, _ BotType, id string, callback func()) error {
callback()
return nil
},
},
props: []*CommandProps{
{
config: struct{}{},
},
},
callback: false,
regNum: 2,
},
{
configWatcher: &DummyConfigWatcher{
ReadFunc: func(_ context.Context, _ BotType, _ string, _ interface{}) error {
t.Error("ConfigWatcher should not be called when pre-built Command is given.")
return nil
},
WatchFunc: func(_ context.Context, _ BotType, _ string, _ func()) error {
t.Error("ConfigWatcher should not be called when pre-built Command is given.")
return nil
},
},
commands: []Command{
&DummyCommand{},
},
regNum: 1,
},
}
for i, tt := range tests {
t.Run(strconv.Itoa(i), func(t *testing.T) {
regNum := 0
botType := BotType(fmt.Sprintf("bot%d", i))
bot := &DummyBot{
BotTypeValue: botType,
AppendCommandFunc: func(command Command) {
regNum++
},
}
r := &runner{
configWatcher: tt.configWatcher,
commands: map[BotType][]Command{
botType: tt.commands,
},
commandProps: map[BotType][]*CommandProps{
botType: tt.props,
},
}
r.registerCommands(context.TODO(), bot)