-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathcommon.js
1791 lines (1665 loc) · 77.8 KB
/
common.js
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
const assert = require('assert');
const when = require('when');
const sequence = require('when/sequence');
const validator = require('../../lib/validator');
let fs = require('fs');
var _ = require('lodash');
const User_Test_Space_Title = 'Framework User Created Test Room';
const Bot_Test_Space_Title = 'Framework Bot Created Test Room';
module.exports = {
// Parent test will init the framework and SDK objects
setFramework: function (f) {
this.framework = f;
},
setUser: function (w) {
this.userWebex = w;
},
setUserPerson: function (p) {
this.userPerson = p;
},
setDisallowedUser: function (d) {
this.disallowedUserSDK = d;
},
setDisallowedUserPerson: function (p) {
this.disallowedUserPerson = p;
},
getDisallowedUser: function () {
return (this.disallowedUserSDK);
},
getPersonInfoForUser(userSDK) {
if (userSDK == this.userWebex) {
return this.userPerson;
} else if (userSDK == this.disallowedUserSDK) {
return this.disallowedUserPerson;
} else {
return {};
}
},
// Default value if setter is not called
preMochaTimeout: 35000,
setMochaTimeout: function(t) {
// We will timeout 80% faster than Mocha
this.preMochaTimeout = t - t/10*2;
},
// Common Tasks used by tests
initFramework: function (testName, framework, userWebex) {
let testInfo = this.testInfo;
testInfo.config.testName = testName;
initTestInfo(this.testInfo);
console.log('In initFramework...');
// Wait for framework to generate events that indicate it started succesfully
const started = new Promise((resolve) => {
this.frameworkStartHandler(framework, testInfo, resolve);
});
const initialized = new Promise((resolve) => {
this.frameworkInitializedHandler(framework, testInfo, resolve);
});
framework.start()
.catch((e) => {
console.error(`Framework initialization failed: ${e.message}, abandon all tests!`);
process.exit(-1);
});
// While we wait for framework, lets validate the user
let userInfoIsReady = userWebex.people.get('me');
console.log('Waiting for framework initialization to complete...');
// Now wait until framework is initialized
return waitForPromisesWithTimeout([started, initialized], this.preMochaTimeout, testInfo)
.then(() => {
if (framework.getWebexSDK().config.defaultMercuryOptions) {
return Promise.reject(new Error('Framework initialized but has a proxy config when none was set!'));
}
myAssert(testInfo, validator.isFramework(framework),
'Framework did not initialize succesfully');
framework.debug(`${framework.email} is in ${framework.bots.length} at the start of the tests.`);
if (process.env.CLEANUP_USER_ROOMS) {
return asUserCleanupFromPreviousTests(userWebex, framework);
} else {
return when(true);
}
}).then(() => {
// Make sure we have user info before next step...
return when(userInfoIsReady).catch((e) => {
console.error(`Could not initialize user with USER_API_TOKEN: ${e.message}`);
return Promise.reject(e);
});
}).then((person) => {
this.userPerson = person;
myAssert(testInfo, validator.isPerson(person),
'getPerson did not return a valid person');
// All went well, we are ready to start running tests
// Each test should register listeners for all framework generated events.
// This catch-all listener will detect any events that don't have listeners
registerUnexpectedEventsHandler(framework, testInfo);
// Finally, see if there is a 1-1 space between test bot and test user
return this.cleanupFromPreviousTestsAndFindDirectSpace(framework, this.userPerson);
});
},
stopFramework: function (testName, framework) {
if (framework) {
let testInfo = this.testInfo;
this.testInfo.config.testName = testName;
const stopped = new Promise((resolve) => {
this.frameworkStopHandler(framework, testInfo, resolve);
});
// remove the catch-all listener
removeUnexpectedEventsHandler(framework);
return framework.stop()
.then(() => when(stopped))
.catch((e) => console.error(`Failed during framework.stop(): ${e.message}`));
}
},
userSendsAttachmentActionAndBotMayRespond: function (framework, testInfo, cardMsgId, inputs,) {
initTestInfo(testInfo);
let attachmentAction;
// Wait for the events associated with a new button press before completing test..
let attachmentActionEvent = new Promise((resolve) => {
this.frameworkAttachementActionEventHandler(framework,
testInfo, resolve);
});
return testInfo.config.userUnderTest.attachmentActions.create({
// Emulate an Action.Submit button press
type: 'submit',
messageId: cardMsgId,
inputs
})
.then((a) => {
attachmentAction = a;
assert(validator.isAttachmentAction(attachmentAction),
'attachmentAction returned by sdk.attachmentActions.create() was not valid');
return waitForPromisesWithTimeout([attachmentActionEvent], this.preMochaTimeout, testInfo);
})
.then(() => {
assert(validator.objIsEqual(attachmentAction, testInfo.out.attachmentAction),
`"${testInfo.config.testName}" failed: attachmentAction returned by API did not match the one from the attachmentAction event`);
// Wait for the events associated with a new message before completing test..
return checkInterimtestInfo(testInfo, attachmentAction);
});
},
userSendsDMToBot: function (framework, testInfo, markdown, heardPromise) {
initTestInfo(testInfo);
let eventPromises = [];
// Wait for the events associated with a new message before completing test..
eventPromises.push(new Promise((resolve) => {
this.frameworkMessageCreatedEventHandler(framework, testInfo, resolve);
}));
// If there is a heardPromise this is a late Discovery Test
if (heardPromise) {
eventPromises.push(new Promise((resolve) => {
this.frameworkSpawnedHandler(framework, testInfo, resolve);
}));
eventPromises.push(heardPromise);
}
// As the user, send the message, mentioning the bot
return testInfo.config.userUnderTest.messages.create({
toPersonId: framework.person.id,
markdown: markdown
})
.then((m) => {
myAssert(testInfo, validator.isMessage(m),
'create message did not return a valid message');
testInfo.out.messageId = m.id;
// Wait for all the event handlers and the heard handler to fire
return waitForPromisesWithTimeout(eventPromises, this.preMochaTimeout, testInfo);
})
.catch((e) => {
console.error(`${testInfo.config.testName} failed: ${e.message}`);
return Promise.reject(e);
});
},
addBotToSpace: function (framework, testInfo, shouldFail) {
// Configure this test to Wait for the events associated with a new membership
initTestInfo(testInfo);
let spawnEvents = [];
if (shouldFail) {
spawnEvents = this.registerMembershipEventsForDectivatedBot(framework, '', testInfo);
} else {
spawnEvents.push(new Promise((resolve) => {
this.frameworkMembershipCreatedHandler(framework, testInfo, resolve);
}));
spawnEvents.push(new Promise((resolve) => {
this.frameworkSpawnedHandler(framework, testInfo, resolve);
}));
}
let theUser = this.userWebex;
if (testInfo.config.userUnderTest) {
theUser = testInfo.config.userUnderTest;
}
// Add the bot to our user created space
return theUser.memberships.create({
roomId: testInfo.config.roomUnderTest.id,
personId: framework.person.id
})
.then((m) => {
return myAssert(testInfo, validator.isMembership(m),
'create memebership did not return a valid membership');
})
// Wait for the expected events
.then(() => waitForPromisesWithTimeout(spawnEvents, this.preMochaTimeout, testInfo)
.then(() => {
let bot = testInfo.out.newBot;
this.createBotEventHandlers(bot);
if (!shouldFail) {
myAssert(testInfo, framework.getBotByRoomId(bot.room.id),
'After spawn new bot is not in framework\'s bot array');
}
return bot;
}).then((bot) => checkInterimtestInfo(testInfo, bot)));
},
botAddUsersToSpace: function (framework, testInfo, userEmails) {
initTestInfo(testInfo);
testInfo.disallowedUserEmail = [];
let guideAdded = false;
if (framework.options.restrictedToEmailDomains) {
for (let i = 0; i < userEmails.length; i++) {
if (this.isDisallowedEmailDomain(userEmails[i], framework.options.restrictedToEmailDomains)) {
testInfo.disallowedUserEmail.push(userEmails[i]);
}
}
}
if (framework.options.guideEmails) {
let guides = userEmails.filter(e => {
return (-1 != framework.guideEmails.indexOf(_.toLower(e)));
});
if (guides.length) {
guideAdded = true;
}
}
let eventPromises = [];
if (testInfo.config.botUnderTest.active) {
// Active bot should behave normally when a non restricted member enters
eventPromises = this.registerMembershipHandlers(framework, testInfo, userEmails);
} else if ((!testInfo.config.botUnderTest.active) && (guideAdded)) {
// Inactive bot should do a membership rules spawn when guide enters
// This will fail if the space also includes restricted domain users -- not currently in tests
eventPromises = this.registerMembershipEventsForGuideAdded(framework, testInfo.disallowedUserEmail, testInfo);
} else if (!testInfo.config.botUnderTest.active) {
// An inactive bot will remain inactive when non-guide users enter, memberEnters will be swallowed
eventPromises = this.registerMembershipEventsForInactiveBot(framework, testInfo.disallowedUserEmail, testInfo);
} else {
// This membership will trigger a membership rules "despawn"
eventPromises = this.registerMembershipEventsForDectivatedBot(framework, testInfo.disallowedUserEmail, testInfo);
}
// Add the users to the space with the bot
return testInfo.config.botUnderTest.add(userEmails)
.then((emails) => {
// Todo update this to check each email
myAssert(testInfo, (emails.length === userEmails.length),
`bot.add did not add all the requested users in test "${testInfo.config.testName}"`);
// Wait for all the event handlers to fire
return waitForPromisesWithTimeout(eventPromises, this.preMochaTimeout, testInfo);
}).then(() => {
delete testInfo.multipleEvents;
return checkInterimtestInfo(testInfo);
});
},
isDisallowedEmailDomain(email, allowedDomainList) {
let domain = _.split(_.toLower(email), '@', 2)[1];
if ((domain === 'webex.bot') || (domain === 'sparkbot.io')) {
return false; // ignore bots
}
if (-1 === allowedDomainList.indexOf(domain)) {
return true;
} else {
return false;
}
},
botRemoveUserFromSpace: function (framework, testInfo, userEmail,
numDisallowedUsersInSpace, isDisallowedUser) {
initTestInfo(testInfo);
let eventPromises = [];
let guideRemoved = false;
if ((framework.options.guideEmails) &&
(-1 != framework.guideEmails.indexOf(_.toLower(userEmail)))) {
guideRemoved = true;
}
if (!testInfo.config.botUnderTest.active) {
myAssert(testInfo, numDisallowedUsersInSpace,
`botRemoveUserFromSpace() error: ${testInfo.config.testName}set numDisallowedUsersInSpace to ${numDisallowedUsersInSpace}`);
eventPromises = this.registerMembershipDeletedEventsWhenDisallowedUserExits(framework, testInfo, numDisallowedUsersInSpace);
} else if (guideRemoved) {
// A currently uncovered test case is removing one guide when another is still present
eventPromises = this.registerGuideRemovedFromSpaceEvents(framework, testInfo);
} else {
eventPromises = this.registerMembershipDeletedHandlers(framework, testInfo);
}
// Add the users to the space with the bot
return testInfo.config.botUnderTest.remove(userEmail)
.then((emails) => {
// Todo update this to check each email
myAssert(testInfo, (emails[0] === userEmail),
`bot.remove did not remove the requested users in test "${testInfo.config.testName}"`);
if (isDisallowedUser) {
testInfo.disallowedUserEmail = this.disallowedUserPerson.emails[0];
}
// Wait for all the event handlers to fire
return waitForPromisesWithTimeout(eventPromises, this.preMochaTimeout, testInfo);
}).then(() => checkInterimtestInfo(testInfo));
},
registerMembershipEventsForGuideAdded: function (framework, disallowedEmails, testInfo) {
//initTestInfo(testInfo);
let eventPromises = [];
let swallowedEvents;
// These events should occur with a new membership that adds a guide
// to a previously unguided space
eventPromises.push(new Promise((resolve) => {
this.frameworkMembershipCreatedHandler(framework, testInfo, resolve);
}));
eventPromises.push(new Promise((resolve) => {
this.frameworkSpawnedHandler(framework, testInfo, resolve);
}));
if (framework.membershipRulesAllowedResponse) {
// When Guides are removed from space with bot expect a
// message from the bot saying it won't work
testInfo.checkMembershipRulesAllowedResponse = true;
eventPromises.push(new Promise((resolve) => {
this.frameworkMessageCreatedEventHandler(framework, testInfo, resolve);
}));
}
swallowedEvents = ['memberEnters', 'spawn'];
eventPromises.push(new Promise((resolve) => {
this.frameworkMembershipRulesEventHandler(framework,
swallowedEvents, testInfo,
false, /* don't error on unexpected swallowed events */
resolve);
}));
return (eventPromises);
},
registerMembershipEventsForInactiveBot: function (framework, disallowedEmails, testInfo) {
//initTestInfo(testInfo);
let eventPromises = [];
let swallowedEvents;
// These events should occur when a new member will not change a bot's inactive status
eventPromises.push(new Promise((resolve) => {
this.frameworkMembershipCreatedHandler(framework, testInfo, resolve);
}));
// the memberEnters event should be "swallowed", and the bot should not respond
swallowedEvents = ['memberEnters'];
eventPromises.push(new Promise((resolve) => {
this.frameworkMembershipRulesEventHandler(framework,
swallowedEvents, testInfo,
false, /* don't error on unexpected swallowed events */
resolve);
}));
return (eventPromises);
},
registerMembershipEventsForDectivatedBot: function (framework, disallowedEmails, testInfo) {
let eventPromises = [];
let swallowedEvents;
// These events should occur with a new membership that violates a memebership rule
eventPromises.push(new Promise((resolve) => {
this.frameworkMembershipCreatedHandler(framework, testInfo, resolve);
}));
if (disallowedEmails) {
// Since this user is disallowed we will get a message telling us the bot is deactivating
eventPromises.push(new Promise((resolve) => {
this.frameworkMessageCreatedEventHandler(framework, testInfo, resolve);
}));
// It will also generate a despawn event with the membership of the dissallowed user
eventPromises.push(new Promise((resolve) => {
this.frameworkDespawnHandler(framework, testInfo, resolve);
}));
// Finally, we will get some membership-rules events,
// and one "swallowed" memberEnters for each dissallowed user
swallowedEvents = ['despawn'];
} else if (('guideEmails' in framework) && framework.guideEmails.length &&
framework.membershipRulesDisallowedResponse) {
// Bot in Guided Mode being added to a space with no guides expect a
// message from the bot saying it won't work and a "swallowed" spawn event
testInfo.checkMembershipRulesDisallowedResponse = true;
eventPromises.push(new Promise((resolve) => {
this.frameworkMessageCreatedEventHandler(framework, testInfo, resolve);
}));
swallowedEvents = ['spawn'];
} else {
// If now disallowed user we are adding a bot to a disallowed space
// We will swallow a spawn event
swallowedEvents = ['spawn'];
}
if (disallowedEmails.length){
for (let i=0; i<disallowedEmails.length; i++) {
swallowedEvents.push('memberEnters');
}
}
// and a message about the "disallowed" despawning
eventPromises.push(new Promise((resolve) => {
this.frameworkMembershipRulesEventHandler(framework,
swallowedEvents, testInfo,
false, /* don't error on unexpected swallowed events */
resolve);
}));
return (eventPromises);
},
registerMembershipHandlers: function (framework, testInfo, userEmails) {
let eventPromises = [];
let swallowedEvents = [];
let disallowedMemberAdded = false;
testInfo.multipleEvents = {};
userEmails.forEach((userEmail) => {
// MembershipCreated events occur for all scenarios
if (!testInfo.multipleEvents?.membershipCreated) {
eventPromises.push(new Promise((resolve) => {
this.frameworkMembershipCreatedHandler(framework, testInfo, resolve);
}));
testInfo.multipleEvents.membershipCreated = 1;
} else {
testInfo.multipleEvents.membershipCreated += 1;
}
if ((!disallowedMemberAdded) && (!testInfo.disallowedUserEmail.includes(userEmail))) {
// These events should occur with a regular new membership to an active room
if (!testInfo.multipleEvents?.memberEnters) {
eventPromises.push(new Promise((resolve) => {
this.frameworkMemberEntersHandler(framework, testInfo, resolve);
}));
eventPromises.push(new Promise((resolve) => {
testInfo.config.botUnderTest.memberEntersHandler(testInfo, resolve);
}));
testInfo.multipleEvents.memberEnters = 1;
testInfo.multipleEvents.botMemberEnters = 1;
} else {
testInfo.multipleEvents.memberEnters += 1;
testInfo.multipleEvents.botMemberEnters += 1;
}
} else if ((!disallowedMemberAdded) && (testInfo.disallowedUserEmail.includes(userEmail))) {
// These events occur when a disallowed user is added to an enabled bot
// It will also generate a despawn event with the membership of the dissallowed user
eventPromises.push(new Promise((resolve) => {
this.frameworkDespawnHandler(framework, testInfo, resolve);
}));
if (framework.membershipRulesStateMessageResponse) {
eventPromises.push(new Promise((resolve) => {
this.frameworkMessageCreatedEventHandler(framework, testInfo, resolve);
}));
}
// Finally, we will get some membership-rules events,
swallowedEvents.push('memberEnters');
swallowedEvents.push('despawn');
disallowedMemberAdded = true;
} else {
// These events occur when a user is added to a disabled bot
swallowedEvents.push('memberEnters');
}
});
// If we are generating any swallowed memberships rules events wait for them
if (swallowedEvents.length) {
eventPromises.push(new Promise((resolve) => {
this.frameworkMembershipRulesEventHandler(framework,
swallowedEvents, testInfo,
false, /* don't error on unexpected swallowed events */
resolve);
}));
}
return (eventPromises);
},
registerMembershipDeletedHandlers: function (framework, testInfo) {
let eventPromises = [];
let bot = testInfo.config.botUnderTest;
// Framework always gets the membership change event
eventPromises.push(new Promise((resolve) => {
this.frameworkMembershipDeletedHandler(framework, testInfo, resolve);
}));
eventPromises.push(new Promise((resolve) => {
this.frameworkMemberExitsHandler(framework, testInfo, resolve);
}));
if (bot != null) {
eventPromises.push(new Promise((resolve) => {
bot.memberExitsHandler(testInfo, resolve);
}));
}
return (eventPromises);
},
registerGuideRemovedFromSpaceEvents: function (framework, testInfo) {
let eventPromises = [];
let swallowedEvents;
// Framework always gets the membership change event
eventPromises.push(new Promise((resolve) => {
this.frameworkMembershipDeletedHandler(framework, testInfo, resolve);
}));
// TODO check if other guides are in the space, we assume we'll be disallowed at this point
eventPromises.push(new Promise((resolve) => {
this.frameworkDespawnHandler(framework, testInfo, resolve);
}));
if (framework.membershipRulesDisallowedResponse) {
// When Guides are removed from space with bot expect a
// message from the bot saying it won't work
testInfo.checkMembershipRulesDisallowedResponse = true;
eventPromises.push(new Promise((resolve) => {
this.frameworkMessageCreatedEventHandler(framework, testInfo, resolve);
}));
}
// Finally, we will get some membership-rules events, a "swallowed" memberExits
// and a message about the re-spawning
swallowedEvents = ['despawn'];
eventPromises.push(new Promise((resolve) => {
this.frameworkMembershipRulesEventHandler(framework,
swallowedEvents, testInfo, true, resolve);
}));
return (eventPromises);
},
registerMembershipDeletedEventsWhenDisallowedUserExits: function (framework, testInfo, numDisallowedUsersInSpace) {
let eventPromises = [];
// Framework always gets the membership change event
eventPromises.push(new Promise((resolve) => {
this.frameworkMembershipDeletedHandler(framework, testInfo, resolve);
}));
if (numDisallowedUsersInSpace === 1) {
// Last disallowed member leaving will "re-spawn" the bot
eventPromises.push(new Promise((resolve) => {
this.frameworkSpawnedHandler(framework, testInfo, resolve);
}));
// If configured to get a "now active" message, wait for messageCreated event
if (framework.membershipRulesAllowedResponse) {
eventPromises.push(new Promise((resolve) => {
this.frameworkMessageCreatedEventHandler(framework, testInfo, resolve);
}));
testInfo.checkMembershipRulesAllowedResponse = true;
}
// Finally, we will get some membership-rules events, a "swallowed" memberExits
// and a message about the re-spawning
eventPromises.push(new Promise((resolve) => {
this.frameworkMembershipRulesEventHandler(framework,
['spawn', 'memberExits'], testInfo, true, resolve);
}));
} else {
// If not last disallowed user there is no membership-rules spawn event
eventPromises.push(new Promise((resolve) => {
this.frameworkMembershipRulesEventHandler(framework,
['memberExits'], testInfo, true, resolve);
}));
}
return (eventPromises);
},
botLeaveSpace: function (framework, testInfo) {
initTestInfo(testInfo);
let leaveSpaceEvents = [];
leaveSpaceEvents.push(new Promise((resolve) => {
this.frameworkMembershipDeletedHandler(framework, testInfo, resolve);
}));
if (testInfo.config.botUnderTest.active) {
leaveSpaceEvents.push(new Promise((resolve) => {
testInfo.config.botUnderTest.stopHandler(testInfo, resolve);
}));
leaveSpaceEvents.push(new Promise((resolve) => {
this.frameworkDespawnHandler(framework, testInfo, resolve);
}));
} else {
// Wait for the membership rules despawn event
// There is no 'stop' event because the bot is not in the 'started' state
leaveSpaceEvents.push(new Promise((resolve) => {
this.frameworkMembershipRulesEventHandler(framework, ['despawn'],
testInfo, true, resolve);
}));
}
return testInfo.config.botUnderTest.exit()
.then(() => waitForPromisesWithTimeout(leaveSpaceEvents, this.preMochaTimeout, testInfo)
.then(() => checkInterimtestInfo(testInfo)));
},
botCreateSpace: function (framework, testInfo, members) {
initTestInfo(testInfo);
let botCreatedRoomBot = null;
// Wait for the events associated with a new membership before completing test..
const roomCreated = new Promise((resolve) => {
this.frameworkRoomCreatedHandler(framework, testInfo, resolve);
});
const membershipCreatedEvent = new Promise((resolve) => {
this.frameworkMembershipCreatedHandler(framework, testInfo, resolve);
});
const spawned = new Promise((resolve) => {
this.frameworkSpawnedHandler(framework, testInfo, resolve);
});
return testInfo.config.botUnderTest.newRoom(Bot_Test_Space_Title, members)
.then((b) => {
botCreatedRoomBot = b;
myAssert(testInfo, validator.isBot(b),
'Bot returned by bot.newRoom is not valid.');
myAssert(testInfo, validator.isRoom(b.room),
'Room returned by bot.newRoom is not valid.');
this.createBotEventHandlers(b);
return waitForPromisesWithTimeout([roomCreated], this.preMochaTimeout, testInfo);
})
// Wait for framework's membershipCreated event
.then(() => {
myAssert(testInfo, (testInfo.out.room.id == botCreatedRoomBot.room.id),
'Room from framework roomCreated event does not match ' +
'the one in the bot returned by newRoom()');
return waitForPromisesWithTimeout([membershipCreatedEvent], this.preMochaTimeout, testInfo);
})
.then(() => {
myAssert(testInfo, (testInfo.out.membership.id === botCreatedRoomBot.membership.id),
'Membership from framework membershipCreated event does not match ' +
'the one in the bot returned by newRoom()');
return waitForPromisesWithTimeout([spawned], this.preMochaTimeout, testInfo);
})
// Wait for framework's spawned event
.then(() => {
myAssert(testInfo, (testInfo.out.newBot.id == botCreatedRoomBot.id),
'Bot from framework spawned event does not match the one returned by newRoom()');
myAssert(testInfo, framework.getBotByRoomId(botCreatedRoomBot.room.id),
'After spawn new bot is not in framework\'s bot array');
return when(botCreatedRoomBot);
})
.then((bot) => checkInterimtestInfo(testInfo, bot));
},
userSendMessage: function (framework, testInfo, testData) {
initTestInfo(testInfo);
// We mention the bot when the test is running as a bot account
// Only register for mention events, if we are mentioning the bot
let isMention = false;
let bot = testInfo.config.botUnderTest;
let markdown = testData.msgText;
if ((framework.isBotAccount) && (testInfo.config.roomUnderTest.type != 'direct')) {
// Add a bot mention at the beginning of the message or position indicated
if ('mentionIndex' in testData) {
let words = markdown.split(' ');
words.splice(testData.mentionIndex, 0, `<@personId:${bot.person.id}>`);
markdown = words.join(' ');
} else {
markdown = `<@personId:${bot.person.id}> ${markdown}`;
}
isMention = true;
}
// As the user, send the message, mentioning the bot
let msgObj = {
roomId: bot.room.id,
markdown: markdown
};
if ('files' in testData) {msgObj.files = testData.files;}
// Set up handlers for the message events
let eventPromises = [];
if (bot.active) {
eventPromises = this.registerMessageHandlers(isMention, framework, msgObj, testInfo);
} else {
eventPromises = this.getInactiveBotEventArray(isMention, framework, msgObj, testInfo, testData.hearsInfo);
}
// Register the specified framework.hears handlers for the message
testData.hearsInfo.forEach((info) => {
let calledHearsPromise = new Promise((resolve) => {
info.functionId = framework.hears(info.phrase, (b, t) => {
testInfo.out.got.push(`hears(${info.phrase})`);
framework.debug(`Bot heard message "${t.message.text}" that user posted`);
myAssert(testInfo, (b.id === bot.id),
`bot returned in framework.hears(${info.phrase}) is not the one expected`);
myAssert(testInfo, validator.objIsEqual(t, testInfo.out.trigger),
`trigger returned in framework.hears(${info.phrase}) was not as expected`);
myAssert(testInfo, validator.objIsEqual(t.message, testInfo.out.message),
`trigger.message returned in framework.hears(${info.phrase}) was not as expected\n
got: "${t.message.text}", expected: ${testInfo.out.message.text}`);
if (('command' in info) && ('prompt' in info)) {
myAssert(testInfo, t.command == info.command,
`trigger.command returned in framework.hears(${info.phrase}) was not as expected`);
myAssert(testInfo, t.prompt == info.prompt,
`trigger.prompt returned in framework.hears(${info.phrase}) was not as expected`);
}
resolve(true);
}, info.helpString, info.priority);
});
if (bot.active) {
// Only wait for it to be called if our bot is active (not disabled by membership rules)
testInfo.in.expected.push(`hears(${info.phrase})`);
framework.debug(`Adding framework.hears(${info.phrase}) for test "${testInfo.config.testName}"`);
eventPromises.push(calledHearsPromise);
}
});
// kick it all off with a message
return testInfo.config.userUnderTest.messages.create(msgObj)
.then((m) => {
myAssert(testInfo, validator.isMessage(m),
`Test:${testInfo.config.testName}create message did not return a valid message`);
// Wait for all the event handlers and the heard handler to fire
return waitForPromisesWithTimeout(eventPromises, this.preMochaTimeout, testInfo);
})
.then(() => checkInterimtestInfo(testInfo))
.then(() => when(testInfo.out.trigger));
},
botRespondsToTrigger: function (framework, testInfo, shouldBeAllowed) {
initTestInfo(testInfo);
let bot = testInfo.config.botUnderTest;
let shouldFail = false;
let botResponse = {
testName: testInfo.config.testName,
format: 'markdown'
};
if ((shouldBeAllowed != undefined) && (shouldBeAllowed == false)) {
shouldFail = true;
}
if (!testInfo.config.priorTestsTrigger) {
if (bot.active) {
// This can occur if the previous tests failed
return when.reject(new Error(`${testInfo.config.testName} didn't run. No trigger to respond to`));
} else {
// No trigger with a deactivated bot is normal.
botResponse.msgText = 'Membership Rules should have prevented this message from being sent!';
}
} else {
// Builds the response based on the trigger
let trigger = testInfo.config.priorTestsTrigger;
botResponse.msgText = `I heard the entry from ${trigger.person.displayName}:\n`;
botResponse.msgText += (trigger.message.text) ? `* text: ${trigger.message.text}\n` : '';
botResponse.msgText += (trigger.message.html) ? `* html: ${trigger.message.html}\n` : '';
}
framework.debug(botResponse);
return this.botSendsMessage(framework, testInfo, botResponse, shouldFail);
},
botSendsMessage: function(framework, testInfo, botMsgTest, shouldFail) {
let bot = testInfo.config.botUnderTest;
let frameworkMessageFormat = framework.messageFormat;
let rejectMessage = `"${testInfo.config.testName}" failed:`;
let botMethod = ('botMethod' in botMsgTest) ? botMsgTest.botMethod : 'say';
let sentText = (botMsgTest.msgObject?.text) ? botMsgTest.msgObject.text : botMsgTest.msgText;
let sentMarkdown = false;
let sentFiles = (botMsgTest.msgObject?.file) ? botMsgTest.msgObject.file : botMsgTest.file;
let sayPromise;
let message = {};
if ((botMsgTest.frameworkFormat == 'markdown') ||
(botMsgTest.format == 'markdown') || (botMsgTest.msgObject?.markdown)) {
sentMarkdown = true;
sentText = '';
}
if (!shouldFail) {
if (botMsgTest?.shouldFail == true) {
shouldFail = true;
}
}
if ((!sentFiles) && ((botMethod == 'uploadStream') || (botMethod == 'sayWithLocalFile'))) {
throw(new Error(`${rejectMessage} invalid bot message test. ` +
`If botMethod=="${botMethod}", test must include "file"`));
}
// When the bot sends a message the framework WILL generate a
// messageCreated event, but will not generate other message related events
// that occur when the message is sent by any other member in the space
let messageEvent = null;
if ((!shouldFail) && (bot.active)) {
if (botMethod != 'censor') {
messageEvent = new Promise((resolve) => {
this.frameworkMessageCreatedEventHandler(framework, testInfo, resolve);
});
} else {
messageEvent = new Promise((resolve) => {
this.frameworkMessageDeletedEventHandler(framework, testInfo, resolve);
});
}
}
if ('frameworkFormat' in botMsgTest) {
framework.messageFormat = botMsgTest.frameworkFormat;
}
if (botMethod == 'sayWithLocalFile') {
if ('msgText' in botMsgTest) {
sayPromise = bot.sayWithLocalFile(botMsgTest.msgText, botMsgTest.file);
} else {
sayPromise = bot.sayWithLocalFile(null, botMsgTest.file);
}
} else if (botMethod == 'uploadStream') {
let stream = fs.createReadStream(botMsgTest.file);
sayPromise = bot.uploadStream(stream);
} else if (botMethod == 'reply') {
let replyMsg = ('msgObject' in botMsgTest) ? botMsgTest.msgObject : botMsgTest.msgText;
let parentIdentifer = ('parentObj' in botMsgTest) ? botMsgTest.parentObj : botMsgTest.parentId;
if ('format' in botMsgTest) {
sayPromise = bot.reply(parentIdentifer, replyMsg, botMsgTest.format);
} else {
sayPromise = bot.reply(parentIdentifer, replyMsg);
}
} else if (botMethod == 'sendCard') {
myAssert(('cardJson' in botMsgTest),
`${rejectMessage} invalid bot message test. If botMethod=="sendCard", test must include "cardJson"`);
let cardJson = require(botMsgTest.cardJson);
if ('fallback' in botMsgTest) {
sayPromise = bot.sendCard(cardJson, botMsgTest.fallback);
} else {
sayPromise = bot.sendCard(cardJson);
}
} else if (botMethod == 'censor') {
let censorMsgIdentifer = ('parentObj' in botMsgTest) ? botMsgTest.parentObj : botMsgTest.parentId;
sayPromise = bot.censor(censorMsgIdentifer);
} else { // assume bot.say() test
if ('format' in botMsgTest) {
if ('msgText' in botMsgTest) {
sayPromise = bot.say(botMsgTest.format, botMsgTest.msgText);
} else if ('msgObject' in botMsgTest) {
sayPromise = bot.say(botMsgTest.format, botMsgTest.msgObject);
} else {
when.reject(new Error('invalid bot message test. If "format" is set, test must also contain "msgObject" or "msgText"'));
}
} else if ('msgText' in botMsgTest) {
sayPromise = bot.say(botMsgTest.msgText);
} else if ('msgObject' in botMsgTest) {
sayPromise = bot.say(botMsgTest.msgObject);
} else {
when.reject(new Error('invalid bot message test. bot.say test must contain "msgObject" or "msgText"'));
}
}
return when(sayPromise)
.then((m) => {
if (botMethod != 'censor') {
message = m;
framework.messageFormat = frameworkMessageFormat;
myAssert(testInfo, validator.isMessage(m),
`${rejectMessage} bot.${botMethod} did not return a valid message`);
if (sentText) {
myAssert(testInfo, m.text == sentText,
`${rejectMessage} bot.${botMethod} did not return a message with same text field`);
}
if (sentMarkdown) {
myAssert(testInfo, m.markdown.length,
`${rejectMessage} bot.${botMethod} did not return a message with markdown`);
}
if (sentFiles) {
myAssert(testInfo, m.files.length,
`${rejectMessage} bot.${botMethod} did not return a message webex file URLs`);
}
if (botMethod == 'sendCard') {
myAssert((typeof m.attachments === 'object'),
`${rejectMessage} bot.${botMethod} did not return a message with a card attachment`);
}
}
return waitForPromisesWithTimeout([messageEvent], this.preMochaTimeout, testInfo);
})
.then(() => {
if (shouldFail) {
let msg = `${testInfo.config.testName} bot.${botMethod} was successful but should have failed.`;
console.error(msg);
return when.reject(new Error(msg));
}
myAssert(validator.objIsEqual(message, testInfo.out.message),
`${rejectMessage} message returned by API did not match the one from the messageCreated event`);
return checkInterimtestInfo(testInfo, testInfo.out.message);
}).catch((e) => {
framework.messageFormat = frameworkMessageFormat;
if (shouldFail) {
// bot.say correctly failed due to membership rules
return when.resolve(true);
}
console.error(`${testInfo.config.testName} failed: ${e.message}`);
return when.reject(new Error(e));
});
},
botDeletesSpace: function(framework, testInfo) {
initTestInfo(testInfo);
let room = testInfo.config.roomUnderTest;
myAssert(testInfo, validator.isRoom(room),
'Invalid testInfo.config.roomUnderTest in common.botDeletesSpace()');
return framework.webex.memberships.list({roomId: room.id})
.then((memberships) => memberships.items.length - 1)
.catch((e) => {
e.message = `Bot failed to get memberships from "${room.title}" before deleting it: ${e.message}`;
return when.reject(e);
})
.then((numOtherUsers) => {
let implodeEvents = [];
implodeEvents.push(new Promise((resolve) => {
this.frameworkMembershipDeletedHandler(framework, testInfo, resolve);
}));
if (numOtherUsers) {
// wait for membershipDeleted from the bot and all other users
testInfo.multipleEvents = {};
testInfo.multipleEvents.membershipDeleted = 1 + numOtherUsers;
framework.debug(`Expecting a total of ${testInfo.multipleEvents.membershipDeleted} ` +
`MembershipDeleted events to occur when bot deletes "${room.title}"`);
}
if (testInfo.config.botUnderTest.active) {
implodeEvents.push(new Promise((resolve) => {
testInfo.config.botUnderTest.stopHandler(testInfo, resolve);
}));
implodeEvents.push(new Promise((resolve) => {
this.frameworkDespawnHandler(framework, testInfo, resolve);
}));
} else {
// Our real despawn event will be "swallowed" if membership rules already did it
implodeEvents.push(new Promise((resolve) => {
this.frameworkMembershipRulesEventHandler(framework, ['despawn'], testInfo, false, resolve);
}));
}
return testInfo.config.botUnderTest.implode()
.then(() => waitForPromisesWithTimeout(implodeEvents, this.preMochaTimeout, testInfo)
.then(() => {
delete testInfo.multipleEvents;
return checkInterimtestInfo(testInfo);
}));
});
},
registerMessageHandlers: function (isMention, framework, msg, testInfo) {
let eventPromises = [];
let bot = testInfo.config.botUnderTest;
// Wait for the events associated with a new message before completing test..
eventPromises.push(new Promise((resolve) => {
this.frameworkMessageCreatedEventHandler(framework, testInfo, resolve);
}));
if (isMention) {
eventPromises.push(new Promise((resolve) => {
this.frameworkMentionedHandler(framework, testInfo, resolve);
}));
eventPromises.push(new Promise((resolve) => {
bot.mentionedHandler(testInfo, resolve);
}));
}
if ('files' in msg) {
eventPromises.push(new Promise((resolve) => {
this.frameworkFilesHandler(framework, testInfo, resolve);
}));
eventPromises.push(new Promise((resolve) => {
bot.filesHandler(testInfo, resolve);
}));
}
eventPromises.push(new Promise((resolve) => {
this.frameworkMessageHandler(framework, testInfo, resolve);
}));
eventPromises.push(new Promise((resolve) => {
bot.messageHandler(testInfo, resolve);
}));
return eventPromises;
},
getInactiveBotEventArray: function (isMention, framework, msgObj, testInfo, hearsInfo) {
let eventPromises = [];
let swallowedEventsArray = [];
// Wait for the events associated with a new message before completing test..
eventPromises.push(new Promise((resolve) => {
this.frameworkMessageCreatedEventHandler(framework, testInfo, resolve);
}));
swallowedEventsArray = ['message'];
hearsInfo.forEach(() => {
swallowedEventsArray.push('hears');
});
if (isMention) {
swallowedEventsArray.push('mentioned');
}
if ('files' in msgObj) {
swallowedEventsArray.push('files');
}