-
Notifications
You must be signed in to change notification settings - Fork 16
/
command_test.go
648 lines (571 loc) · 16.6 KB
/
command_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
package sarah
import (
"context"
"errors"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"testing"
)
type DummyCommand struct {
IdentifierValue string
ExecuteFunc func(context.Context, Input) (*CommandResponse, error)
InstructionFunc func(*HelpInput) string
MatchFunc func(Input) bool
}
var _ Command = (*DummyCommand)(nil)
func (command *DummyCommand) Identifier() string {
return command.IdentifierValue
}
func (command *DummyCommand) Execute(ctx context.Context, input Input) (*CommandResponse, error) {
return command.ExecuteFunc(ctx, input)
}
func (command *DummyCommand) Instruction(input *HelpInput) string {
return command.InstructionFunc(input)
}
func (command *DummyCommand) Match(input Input) bool {
return command.MatchFunc(input)
}
func TestNewCommandPropsBuilder(t *testing.T) {
builder := NewCommandPropsBuilder()
if builder == nil {
t.Fatal("NewCommandPropsBuilder returned nil.")
}
}
func TestCommandPropsBuilder_ConfigurableFunc(t *testing.T) {
wrappedFncCalled := false
config := &struct{}{}
fnc := func(_ context.Context, _ Input, passedConfig CommandConfig) (*CommandResponse, error) {
wrappedFncCalled = true
if passedConfig != config {
t.Errorf("Passed config is not the expected one: %#v", passedConfig)
}
return nil, nil
}
builder := &CommandPropsBuilder{props: &CommandProps{}}
builder.ConfigurableFunc(config, fnc)
if builder.props.config != config {
t.Error("Passed config struct is not set.")
}
_, _ = builder.props.commandFunc(context.TODO(), &DummyInput{}, config)
if wrappedFncCalled == false {
t.Error("Provided func was not properly wrapped in builder.")
}
}
func TestCommandPropsBuilder_BotType(t *testing.T) {
var botType BotType = "dummy"
builder := &CommandPropsBuilder{props: &CommandProps{}}
builder.BotType(botType)
if builder.props.botType != botType {
t.Error("Provided BotType was not set.")
}
}
func TestCommandPropsBuilder_Func(t *testing.T) {
wrappedFncCalled := false
builder := &CommandPropsBuilder{props: &CommandProps{}}
fnc := func(_ context.Context, _ Input) (*CommandResponse, error) {
wrappedFncCalled = true
return nil, nil
}
builder.Func(fnc)
_, _ = builder.props.commandFunc(context.TODO(), &DummyInput{})
if wrappedFncCalled == false {
t.Error("Provided func was not properly wrapped in builder.")
}
}
func TestCommandPropsBuilder_Identifier(t *testing.T) {
builder := &CommandPropsBuilder{props: &CommandProps{}}
id := "FOO"
builder.Identifier(id)
if builder.props.identifier != id {
t.Error("Provided identifier is not set.")
}
}
func TestCommandPropsBuilder_Instruction(t *testing.T) {
builder := &CommandPropsBuilder{props: &CommandProps{}}
example := ".echo foo"
builder.Instruction(example)
instruction := builder.props.instructionFunc(&HelpInput{})
if instruction != example {
t.Error("Provided instruction is not returned.")
}
}
func TestCommandPropsBuilder_InstructionFunc(t *testing.T) {
builder := &CommandPropsBuilder{props: &CommandProps{}}
fnc := func(_ *HelpInput) string {
return "dummy"
}
builder.InstructionFunc(fnc)
if reflect.ValueOf(builder.props.instructionFunc).Pointer() != reflect.ValueOf(fnc).Pointer() {
t.Error("Passed function is not set.")
}
}
func TestCommandPropsBuilder_MatchPattern(t *testing.T) {
builder := &CommandPropsBuilder{props: &CommandProps{}}
builder.MatchPattern(regexp.MustCompile(`^\.echo`))
if !builder.props.matchFunc(&DummyInput{MessageValue: ".echo"}) {
t.Error("Expected true to return, but did not.")
}
}
func TestCommandPropsBuilder_MatchFunc(t *testing.T) {
builder := &CommandPropsBuilder{props: &CommandProps{}}
builder.MatchFunc(func(input Input) bool {
return regexp.MustCompile(`^\.echo`).MatchString(input.Message())
})
if !builder.props.matchFunc(&DummyInput{MessageValue: ".echo"}) {
t.Error("Expected true to return, but did not.")
}
}
func TestCommandPropsBuilder_Build(t *testing.T) {
builder := &CommandPropsBuilder{props: &CommandProps{}}
if _, err := builder.Build(); err == nil {
t.Error("expected error not given.")
} else if err != ErrCommandInsufficientArgument {
t.Errorf("expected error not given. %#v", err)
}
var botType BotType = "dummy"
matchPattern := regexp.MustCompile(`^\.echo`)
identifier := "dummy"
example := ".echo knock knock"
config := &struct {
Token string
}{
Token: "dummy",
}
fnc := func(_ context.Context, input Input, passedConfig CommandConfig) (*CommandResponse, error) {
return nil, nil
}
builder.BotType(botType).
Identifier(identifier).
MatchPattern(matchPattern).
Instruction(example).
ConfigurableFunc(config, fnc)
props, err := builder.Build()
if err != nil {
t.Errorf("something is wrong with command construction. %#v", err)
}
if props == nil {
t.Fatal("Built command is not returned.")
}
if props.botType != botType {
t.Errorf("Expected BotType is not set: %s.", props.botType)
}
if props.identifier != identifier {
t.Errorf("Expected identifier is not set: %s.", props.identifier)
}
if !props.matchFunc(&DummyInput{MessageValue: ".echo foo"}) {
t.Error("Expected match result is not given.")
}
instruction := props.instructionFunc(&HelpInput{})
if instruction != example {
t.Errorf("Expected example is not returned: %s.", instruction)
}
if props.config != config {
t.Errorf("Expected config struct is not set: %#v.", config)
}
}
func TestCommandPropsBuilder_MustBuild(t *testing.T) {
builder := &CommandPropsBuilder{props: &CommandProps{}}
builder.BotType("dummyBot").
Identifier("dummy").
MatchPattern(regexp.MustCompile(`^\.echo`)).
Instruction(".echo knock knock")
func() {
defer func() {
if r := recover(); r == nil {
t.Error("Expected panic did not occur.")
}
}()
builder.MustBuild()
}()
builder.Func(func(_ context.Context, input Input) (*CommandResponse, error) {
return nil, nil
})
props := builder.MustBuild()
if props.identifier != builder.props.identifier {
t.Error("Provided identifier is not set.")
}
}
func TestNewCommands(t *testing.T) {
commands := NewCommands()
if commands == nil {
t.Error("Not properly initialized.")
}
}
func TestCommands_FindFirstMatched(t *testing.T) {
commands := &Commands{}
matchedCommand := commands.FindFirstMatched(&DummyInput{MessageValue: "echo"})
if matchedCommand != nil {
t.Fatalf("Something is returned while nothing other than nil may returned: %#v.", matchedCommand)
}
irrelevantCommand := &DummyCommand{}
irrelevantCommand.MatchFunc = func(_ Input) bool {
return false
}
echoCommand := &DummyCommand{}
echoCommand.MatchFunc = func(input Input) bool {
return strings.HasPrefix(input.Message(), "echo")
}
echoCommand.ExecuteFunc = func(_ context.Context, _ Input) (*CommandResponse, error) {
return &CommandResponse{Content: ""}, nil
}
irrelevantCommand2 := &DummyCommand{}
irrelevantCommand2.MatchFunc = func(_ Input) bool {
return false
}
commands = &Commands{collection: []Command{irrelevantCommand, echoCommand, irrelevantCommand2}}
matchedCommand = commands.FindFirstMatched(&DummyInput{MessageValue: "echo"})
if matchedCommand == nil {
t.Fatal("Expected command is not found.")
}
if matchedCommand != echoCommand {
t.Fatalf("Expected command instance not returned: %#v.", matchedCommand)
}
}
func TestCommands_ExecuteFirstMatched(t *testing.T) {
commands := &Commands{}
input := &DummyInput{}
input.MessageValue = "echo foo"
response, err := commands.ExecuteFirstMatched(context.TODO(), input)
if err != nil {
t.Error("Error is returned on non matching case.")
}
if response != nil {
t.Error("Response should be nil on non matching case.")
}
echoCommand := &DummyCommand{}
echoCommand.MatchFunc = func(input Input) bool {
return strings.HasPrefix(input.Message(), "echo")
}
echoCommand.ExecuteFunc = func(_ context.Context, _ Input) (*CommandResponse, error) {
return &CommandResponse{Content: ""}, nil
}
commands = &Commands{collection: []Command{echoCommand}}
response, err = commands.ExecuteFirstMatched(context.TODO(), input)
if err != nil {
t.Errorf("Unexpected error on command execution: %#v.", err)
return
}
if response == nil {
t.Error("Response expected, but was not returned.")
return
}
switch v := response.Content.(type) {
case string:
//OK
default:
t.Errorf("Expected string, but was %#v.", v)
}
}
func TestCommands_Append(t *testing.T) {
commands := &Commands{}
command := &DummyCommand{
IdentifierValue: "first",
}
// First operation
commands.Append(command)
if len(commands.collection) == 0 {
t.Fatal("Provided command was not appended.")
}
if (commands.collection)[0] != command {
t.Fatalf("Appended command is not the one provided: %#v", commands.collection[0])
}
// Second operation with same command, but with a different value
newCommand := &DummyCommand{
IdentifierValue: "first",
}
commands.Append(newCommand)
if len(commands.collection) != 1 {
t.Fatalf("Expected only one command to stay, but was: %d.", len(commands.collection))
}
if commands.collection[0] != newCommand {
t.Fatal("The old command was not replaced with the new one with the same ID.")
}
// Third operation with different command
anotherCommand := &DummyCommand{
IdentifierValue: "second",
}
commands.Append(anotherCommand)
if len(commands.collection) != 2 {
t.Fatalf("Expected 2 commands to stay, but was: %d.", len(commands.collection))
}
// Third operation with same command, but with a different value
yetNewCommand := &DummyCommand{
IdentifierValue: "first",
}
commands.Append(yetNewCommand)
if len(commands.collection) != 2 {
t.Fatalf("Expected two one command to stay, but was: %d.", len(commands.collection))
}
if commands.collection[0] != yetNewCommand {
t.Fatal("The old command was not replaced with the new one with the same ID.")
}
}
func TestCommands_Helps(t *testing.T) {
cmd1 := &DummyCommand{
IdentifierValue: "id",
InstructionFunc: func(_ *HelpInput) string {
return "example"
},
}
cmd2 := &DummyCommand{
IdentifierValue: "hiddenCommand",
InstructionFunc: func(_ *HelpInput) string {
return ""
},
}
commands := &Commands{collection: []Command{cmd1, cmd2}}
helps := commands.Helps(&HelpInput{})
if len(*helps) != 1 {
t.Fatalf("Expectnig one help to be given, but was %d.", len(*helps))
}
if (*helps)[0].Identifier != cmd1.IdentifierValue {
t.Errorf("Expected ID was not returned: %s.", (*helps)[0].Identifier)
}
if (*helps)[0].Instruction != cmd1.InstructionFunc(&HelpInput{}) {
t.Errorf("Expected instruction was not returned: %s.", (*helps)[0].Instruction)
}
}
func TestSimpleCommand_Identifier(t *testing.T) {
id := "bar"
command := defaultCommand{identifier: id}
if command.Identifier() != id {
t.Errorf("Stored identifier is not returned: %s.", command.Identifier())
}
}
func TestSimpleCommand_Instruction(t *testing.T) {
instruction := "example foo"
command := defaultCommand{
instructionFunc: func(_ *HelpInput) string {
return instruction
},
}
if command.Instruction(&HelpInput{}) != instruction {
t.Errorf("Stored example is not returned: %s.", command.Identifier())
}
}
func TestSimpleCommand_Match(t *testing.T) {
command := defaultCommand{matchFunc: func(input Input) bool {
return regexp.MustCompile(`^\.echo`).MatchString(input.Message())
}}
if command.Match(&DummyInput{MessageValue: ".echo foo"}) == false {
t.Error("Expected match result is not returned.")
}
}
func TestSimpleCommand_Execute(t *testing.T) {
wrappedFncCalled := false
command := defaultCommand{
configWrapper: &commandConfigWrapper{
value: &struct{}{},
mutex: &sync.RWMutex{},
},
commandFunc: func(ctx context.Context, input Input, cfg ...CommandConfig) (*CommandResponse, error) {
wrappedFncCalled = true
return nil, nil
},
}
input := &DummyInput{}
_, err := command.Execute(context.TODO(), input)
if err != nil {
t.Errorf("Error is returned: %s", err.Error())
}
if wrappedFncCalled == false {
t.Error("Wrapped function is not called.")
}
}
func TestStripMessage(t *testing.T) {
pattern := regexp.MustCompile(`^\.echo`)
stripped := StripMessage(pattern, ".echo foo bar")
if stripped != "foo bar" {
t.Errorf("Unexpected return value: %s.", stripped)
}
}
func Test_buildCommand(t *testing.T) {
type config struct {
text string
}
tests := []struct {
props *CommandProps
watcher ConfigWatcher
validateConfig func(cfg interface{}) error
hasErr bool
}{
{
// No config
props: &CommandProps{
botType: "botType",
identifier: "fileNotFound",
config: nil,
commandFunc: func(_ context.Context, _ Input, _ ...CommandConfig) (*CommandResponse, error) {
return nil, nil
},
matchFunc: func(_ Input) bool {
return true
},
instructionFunc: func(_ *HelpInput) string {
return ""
},
},
watcher: nil,
hasErr: false,
},
{
props: &CommandProps{
botType: "botType",
identifier: "fileNotFound",
config: &config{},
commandFunc: func(_ context.Context, _ Input, _ ...CommandConfig) (*CommandResponse, error) {
return nil, nil
},
matchFunc: func(_ Input) bool {
return true
},
instructionFunc: func(_ *HelpInput) string {
return ""
},
},
watcher: &DummyConfigWatcher{
ReadFunc: func(_ context.Context, _ BotType, _ string, cfg interface{}) error {
config, ok := cfg.(*config)
if !ok {
t.Errorf("Unexpected type is passed: %T.", cfg)
return nil
}
config.text = "texts"
return nil
},
},
validateConfig: func(cfg interface{}) error {
config, ok := cfg.(*config)
if !ok {
return fmt.Errorf("unexpected type is passed: %T", cfg)
}
if config.text != "texts" {
return fmt.Errorf("nexpected value is set: %s", config.text)
}
return nil
},
hasErr: false,
},
{
props: &CommandProps{
botType: "botType",
identifier: "fileNotFound",
// Not a pointer to the config value, but is well handled
config: config{},
commandFunc: func(_ context.Context, _ Input, _ ...CommandConfig) (*CommandResponse, error) {
return nil, nil
},
matchFunc: func(_ Input) bool {
return true
},
instructionFunc: func(_ *HelpInput) string {
return ""
},
},
watcher: &DummyConfigWatcher{
ReadFunc: func(_ context.Context, _ BotType, _ string, cfg interface{}) error {
config, ok := cfg.(*config) // Pointer is passed
if !ok {
t.Errorf("Unexpected type is passed: %T.", cfg)
return nil
}
config.text = "texts"
return nil
},
},
validateConfig: func(cfg interface{}) error {
config, ok := cfg.(config) // Value is passed
if !ok {
return fmt.Errorf("unexpected type is passed: %T", cfg)
}
if config.text != "texts" {
return fmt.Errorf("unexpected value is set: %s", config.text)
}
return nil
},
hasErr: false,
},
{
props: &CommandProps{
botType: "botType",
identifier: "fileNotFound",
config: &config{},
commandFunc: func(_ context.Context, _ Input, _ ...CommandConfig) (*CommandResponse, error) {
return nil, nil
},
matchFunc: func(_ Input) bool {
return true
},
instructionFunc: func(_ *HelpInput) string {
return ""
},
},
watcher: &DummyConfigWatcher{
ReadFunc: func(_ context.Context, botType BotType, id string, cfg interface{}) error {
return &ConfigNotFoundError{
BotType: botType,
ID: id,
}
},
},
validateConfig: func(cfg interface{}) error {
config, ok := cfg.(*config)
if !ok {
return fmt.Errorf("unexpected type is passed: %T", cfg)
}
if config.text != "" {
return fmt.Errorf("unexpected value is set: %s", config.text)
}
return nil
},
hasErr: false,
},
{
props: &CommandProps{
botType: "botType",
identifier: "fileNotFound",
config: &config{},
commandFunc: func(_ context.Context, _ Input, _ ...CommandConfig) (*CommandResponse, error) {
return nil, nil
},
matchFunc: func(_ Input) bool {
return true
},
instructionFunc: func(_ *HelpInput) string {
return ""
},
},
watcher: &DummyConfigWatcher{
ReadFunc: func(_ context.Context, _ BotType, _ string, _ interface{}) error {
return errors.New("unacceptable error")
},
},
hasErr: true,
},
}
for i, tt := range tests {
t.Run(strconv.Itoa(i), func(t *testing.T) {
command, err := buildCommand(context.TODO(), tt.props, tt.watcher)
if tt.hasErr {
if err == nil {
t.Error("Expected error is not returned.")
}
return
}
if command == nil {
t.Fatal("Built command is not returned.")
}
if tt.props.config != nil {
typed := command.(*defaultCommand)
err = tt.validateConfig(typed.configWrapper.value)
if err != nil {
t.Error(err.Error())
}
}
})
}
}