forked from DevExpress/testcafe
/
driver.js
1832 lines (1438 loc) · 66.5 KB
/
driver.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
import hammerhead from './deps/hammerhead';
import {
RequestBarrier,
ScriptExecutionEmitter,
ClientRequestEmitter,
pageUnloadBarrier,
eventUtils,
domUtils,
arrayUtils,
serviceUtils,
preventRealEvents,
disableRealEventsPreventing,
waitFor,
delay,
getTimeLimitedPromise,
browser,
} from './deps/testcafe-core';
import { cursor } from './deps/testcafe-automation';
import { StatusBar } from './deps/testcafe-ui';
import {
CHECK_IFRAME_DRIVER_LINK_DELAY,
SEND_STATUS_REQUEST_TIME_LIMIT,
SEND_STATUS_REQUEST_RETRY_DELAY,
SEND_STATUS_REQUEST_RETRY_COUNT,
CHECK_STATUS_RETRY_DELAY,
CHECK_CHILD_WINDOW_DRIVER_LINK_DELAY,
} from '../../utils/browser-connection-timeouts';
import TEST_RUN_MESSAGES from '../../test-run/client-messages';
import COMMAND_TYPE from '../../test-run/commands/type';
import { TEST_RUN_ERRORS } from '../../errors/types';
import {
isBrowserManipulationCommand,
isCommandRejectableByPageError,
isExecutableInTopWindowOnly,
} from '../../test-run/commands/utils';
import STATUS_BAR_DEBUG_ACTION from '../../utils/debug-action';
import {
UncaughtErrorOnPage,
ClientFunctionExecutionInterruptionError,
ActionElementNotIframeError,
ActionIframeIsNotLoadedError,
ActionElementNotFoundError,
ActionElementIsInvisibleError,
CurrentIframeIsNotLoadedError,
CurrentIframeNotFoundError,
CurrentIframeIsInvisibleError,
CannotObtainInfoForElementSpecifiedBySelectorError,
UncaughtErrorInCustomClientScriptCode,
UncaughtErrorInCustomClientScriptLoadedFromModule,
ChildWindowIsNotLoadedError,
CannotSwitchToWindowError,
CloseChildWindowError,
ChildWindowClosedBeforeSwitchingError,
ParentWindowNotFoundError,
PreviousWindowNotFoundError,
CannotCloseWindowWithChildrenError,
CannotCloseWindowWithoutParentError,
WindowNotFoundError,
CannotRestoreChildWindowError,
} from '../../shared/errors';
import BrowserConsoleMessages from './client-browser-console-messages';
import NativeDialogTracker from './native-dialog-tracker';
import {
SwitchToWindowValidationMessage,
CloseWindowValidationMessage,
CloseWindowCommandMessage,
SwitchToWindowCommandMessage,
SetNativeDialogHandlerMessage,
GetWindowsMessage,
ChildWindowIsLoadedInFrameMessage,
TYPE as MESSAGE_TYPE,
} from './driver-link/messages';
import ContextStorage from './storage';
import DriverStatus from './status';
import generateId from './generate-id';
import ChildIframeDriverLink from './driver-link/iframe/child';
import createReplicator from './command-executors/client-functions/replicator/index';
import SelectorNodeTransform from './command-executors/client-functions/replicator/transforms/selector-node-transform';
import ActionExecutor from '../../shared/actions/action-executor';
import executeManipulationCommand from './command-executors/browser-manipulation';
import executeNavigateToCommand from './command-executors/execute-navigate-to';
import {
getResult as getExecuteSelectorResult,
getResultDriverStatus as getExecuteSelectorResultDriverStatus,
} from './command-executors/execute-selector';
import executeChildWindowDriverLinkSelector from './command-executors/execute-child-window-driver-link-selector';
import ClientFunctionExecutor from './command-executors/client-functions/client-function-executor';
import ChildWindowDriverLink from './driver-link/window/child';
import ParentWindowDriverLink from './driver-link/window/parent';
import sendConfirmationMessage from './driver-link/send-confirmation-message';
import DriverRole from './role';
import { CHECK_CHILD_WINDOW_CLOSED_INTERVAL, WAIT_FOR_WINDOW_DRIVER_RESPONSE_TIMEOUT } from './driver-link/timeouts';
import sendMessageToDriver from './driver-link/send-message-to-driver';
import getExecutorResultDriverStatus from './command-executors/get-executor-result-driver-status';
import SelectorExecutor from './command-executors/client-functions/selector-executor';
import SelectorElementActionTransform from './command-executors/client-functions/replicator/transforms/selector-element-action-transform';
import BarriersComplex from '../../shared/barriers/complex-barrier';
import createErrorCtorCallback from '../../shared/errors/selector-error-ctor-callback';
import './command-executors/actions-initializer';
const settings = hammerhead.settings;
const transport = hammerhead.transport;
const Promise = hammerhead.Promise;
const messageSandbox = hammerhead.eventSandbox.message;
const storages = hammerhead.storages;
const nativeMethods = hammerhead.nativeMethods;
const DateCtor = nativeMethods.date;
const listeners = hammerhead.eventSandbox.listeners;
const TEST_DONE_SENT_FLAG = 'testcafe|driver|test-done-sent-flag';
const PENDING_STATUS = 'testcafe|driver|pending-status';
const EXECUTING_CLIENT_FUNCTION_DESCRIPTOR = 'testcafe|driver|executing-client-function-descriptor';
const SELECTOR_EXECUTION_START_TIME = 'testcafe|driver|selector-execution-start-time';
const PENDING_PAGE_ERROR = 'testcafe|driver|pending-page-error';
const ACTIVE_IFRAME_SELECTOR = 'testcafe|driver|active-iframe-selector';
const TEST_SPEED = 'testcafe|driver|test-speed';
const ASSERTION_RETRIES_TIMEOUT = 'testcafe|driver|assertion-retries-timeout';
const ASSERTION_RETRIES_START_TIME = 'testcafe|driver|assertion-retries-start-time';
const CONSOLE_MESSAGES = 'testcafe|driver|console-messages';
const PENDING_CHILD_WINDOW_COUNT = 'testcafe|driver|pending-child-window-count';
const ACTION_IFRAME_ERROR_CTORS = {
NotLoadedError: ActionIframeIsNotLoadedError,
NotFoundError: ActionElementNotFoundError,
IsInvisibleError: ActionElementIsInvisibleError,
};
const CURRENT_IFRAME_ERROR_CTORS = {
NotLoadedError: CurrentIframeIsNotLoadedError,
NotFoundError: CurrentIframeNotFoundError,
IsInvisibleError: CurrentIframeIsInvisibleError,
};
const COMMAND_EXECUTION_MAX_TIMEOUT = Math.pow(2, 31) - 1;
const EMPTY_COMMAND_EVENT_WAIT_TIMEOUT = 30 * 1000;
const CHILD_WINDOW_CLOSED_EVENT_TIMEOUT = 2000;
const RESTORE_CHILD_WINDOWS_TIMEOUT = 30 * 1000;
const STATUS_WITH_COMMAND_RESULT_EVENT = 'status-with-command-result-event';
const EMPTY_COMMAND_EVENT = 'empty-command-event';
const CHILD_WINDOW_CLOSED_EVENT = 'child-window-closed';
export default class Driver extends serviceUtils.EventEmitter {
constructor (testRunId, communicationUrls, runInfo, options) {
super();
this.COMMAND_EXECUTING_FLAG = 'testcafe|driver|command-executing-flag';
this.EXECUTING_IN_IFRAME_FLAG = 'testcafe|driver|executing-in-iframe-flag';
this.PENDING_WINDOW_SWITCHING_FLAG = 'testcafe|driver|pending-window-switching-flag';
this.WINDOW_COMMAND_API_CALL_FLAG = 'testcafe|driver|window-command-api-flag';
this.testRunId = testRunId;
this.heartbeatUrl = communicationUrls.heartbeat;
this.browserStatusUrl = communicationUrls.status;
this.browserStatusDoneUrl = communicationUrls.statusDone;
this.browserActiveWindowId = communicationUrls.activeWindowId;
this.userAgent = runInfo.userAgent;
this.fixtureName = runInfo.fixtureName;
this.testName = runInfo.testName;
this.selectorTimeout = options.selectorTimeout;
this.pageLoadTimeout = options.pageLoadTimeout;
this.childWindowReadyTimeout = options.childWindowReadyTimeout;
this.initialSpeed = options.speed;
this.skipJsErrors = options.skipJsErrors;
this.dialogHandler = options.dialogHandler;
this.canUseDefaultWindowActions = options.canUseDefaultWindowActions;
this.isFirstPageLoad = settings.get().isFirstPageLoad;
this.customCommandHandlers = {};
this.contextStorage = null;
this.nativeDialogsTracker = null;
this.childIframeDriverLinks = [];
this.activeChildIframeDriverLink = null;
this.childWindowDriverLinks = [];
this.parentWindowDriverLink = null;
this.statusBar = null;
this.windowId = this._getCurrentWindowId();
this.role = DriverRole.replica;
this.setAsMasterInProgress = false;
this.checkClosedChildWindowIntervalId = null;
const requestEmitter = new ClientRequestEmitter();
this.pageInitialRequestBarrier = new RequestBarrier(requestEmitter);
this.readyPromise = this._getReadyPromise();
this._initChildDriverListening();
pageUnloadBarrier.init();
preventRealEvents();
hammerhead.on(hammerhead.EVENTS.uncaughtJsError, err => this._onJsError(err));
hammerhead.on(hammerhead.EVENTS.unhandledRejection, err => this._onJsError(err));
hammerhead.on(hammerhead.EVENTS.consoleMethCalled, e => this._onConsoleMessage(e));
hammerhead.on(hammerhead.EVENTS.beforeFormSubmit, e => this._onFormSubmit(e));
hammerhead.on(hammerhead.EVENTS.windowOpened, e => this._onChildWindowOpened(e));
this.setCustomCommandHandlers(COMMAND_TYPE.unlockPage, () => this._unlockPageAfterTestIsDone());
this.setCustomCommandHandlers(COMMAND_TYPE.getActiveElement, () => this._getActiveElement());
// NOTE: initiate the child links restoring process before the window is reloaded
listeners.addInternalEventBeforeListener(window, ['beforeunload'], () => {
this._sendStartToRestoreCommand();
});
this.replicator = createReplicator([ new SelectorNodeTransform() ]);
}
_isOpenedInIframe () {
const opener = window.opener;
return opener && opener.top && opener.top !== opener;
}
set speed (val) {
this.contextStorage.setItem(TEST_SPEED, val);
}
get speed () {
return this.contextStorage.getItem(TEST_SPEED);
}
get consoleMessages () {
return new BrowserConsoleMessages(this.contextStorage.getItem(CONSOLE_MESSAGES));
}
set consoleMessages (messages) {
return this.contextStorage.setItem(CONSOLE_MESSAGES, messages ? messages.getCopy() : null);
}
async _getReadyPromise () {
await eventUtils.documentReady(this.pageLoadTimeout);
await this.pageInitialRequestBarrier.wait(true);
}
_hasPendingActionFlags (contextStorage) {
return contextStorage.getItem(this.COMMAND_EXECUTING_FLAG) ||
contextStorage.getItem(this.EXECUTING_IN_IFRAME_FLAG);
}
_getCurrentWindowId () {
const currentUrl = window.location.toString();
const parsedProxyUrl = hammerhead.utils.url.parseProxyUrl(currentUrl);
return parsedProxyUrl && parsedProxyUrl.windowId || null;
}
// Error handling
_onJsError (err) {
// NOTE: we should not send any message to the server if we've
// sent the 'test-done' message but haven't got the response.
if (this.skipJsErrors || this.contextStorage.getItem(TEST_DONE_SENT_FLAG))
return Promise.resolve();
const error = new UncaughtErrorOnPage(err.stack, err.pageUrl);
if (!this.contextStorage.getItem(PENDING_PAGE_ERROR))
this.contextStorage.setItem(PENDING_PAGE_ERROR, error);
return null;
}
_unlockPageAfterTestIsDone () {
disableRealEventsPreventing();
return Promise.resolve();
}
async _getActiveElement () {
const activeElement = domUtils.getActiveElement();
return this.replicator.encode(activeElement);
}
_failIfClientCodeExecutionIsInterrupted () {
// NOTE: ClientFunction should be used primarily for observation. We raise
// an error if the page was reloaded during ClientFunction execution.
const executingClientFnDescriptor = this.contextStorage.getItem(EXECUTING_CLIENT_FUNCTION_DESCRIPTOR);
if (executingClientFnDescriptor) {
this._onReady(new DriverStatus({
isCommandResult: true,
executionError: new ClientFunctionExecutionInterruptionError(executingClientFnDescriptor.instantiationCallsiteName),
}));
return true;
}
return false;
}
onCustomClientScriptError (err, moduleName) {
const error = moduleName
? new UncaughtErrorInCustomClientScriptLoadedFromModule(err, moduleName)
: new UncaughtErrorInCustomClientScriptCode(err);
if (!this.contextStorage.getItem(PENDING_PAGE_ERROR))
this.contextStorage.setItem(PENDING_PAGE_ERROR, error);
}
_addChildWindowDriverLink (e) {
const childWindowDriverLink = new ChildWindowDriverLink(e.window, e.windowId);
this.childWindowDriverLinks.push(childWindowDriverLink);
this._ensureClosedChildWindowWatcher();
}
_ensureClosedChildWindowWatcher () {
if (this.checkClosedChildWindowIntervalId)
return;
this.checkClosedChildWindowIntervalId = nativeMethods.setInterval.call(window, () => {
const firstClosedChildWindowDriverLink = arrayUtils.find(this.childWindowDriverLinks, childWindowDriverLink => childWindowDriverLink.driverWindow.closed);
if (!firstClosedChildWindowDriverLink)
return;
this.emit(CHILD_WINDOW_CLOSED_EVENT);
arrayUtils.remove(this.childWindowDriverLinks, firstClosedChildWindowDriverLink);
if (!firstClosedChildWindowDriverLink.ignoreMasterSwitching)
this._setCurrentWindowAsMaster();
if (!this.childWindowDriverLinks.length) {
nativeMethods.clearInterval.call(window, this.checkClosedChildWindowIntervalId);
delete this.checkClosedChildWindowIntervalId;
}
}, CHECK_CHILD_WINDOW_CLOSED_INTERVAL);
}
_setAsMasterInProgressOrCompleted () {
return this.setAsMasterInProgress || this.role === DriverRole.master;
}
_setCurrentWindowAsMaster () {
if (this._setAsMasterInProgressOrCompleted())
return;
this.setAsMasterInProgress = true;
this._clearActiveChildIframeInfo();
Promise.resolve()
.then(() => {
return browser.setActiveWindowId(this.browserActiveWindowId, hammerhead.createNativeXHR, this.windowId);
})
.then(() => {
this._startInternal({
finalizePendingCommand: true,
isFirstRequestAfterWindowSwitching: true,
});
this.setAsMasterInProgress = false;
})
.catch(() => {
this._onReady(new DriverStatus({
isCommandResult: true,
executionError: new CannotSwitchToWindowError(),
}));
});
}
_onChildWindowOpened (e) {
this._addChildWindowDriverLink(e);
this._switchToChildWindow(e.windowId);
}
_sendStartToRestoreCommand () {
if (!this.contextStorage)
return;
// NOTE: the situation is possible when the child window responds before the parent window is reloaded,
// so we should not respond to the child window if the parent window is not reloaded
this._stopRespondToChildren = true;
// NOTE: save the child window count that we expect to restore after the parent window is reloaded
this.contextStorage.setItem(PENDING_CHILD_WINDOW_COUNT, this.childWindowDriverLinks.length);
for (const childLink of this.childWindowDriverLinks)
childLink.startToRestore();
}
// HACK: For https://github.com/DevExpress/testcafe/issues/3560
// We have to cancel every form submit after a test is done
// to prevent requests to a closed session
_onFormSubmit (e) {
// NOTE: We need to refactor this code to avoid the undefined value in contextStorage
// https://github.com/DevExpress/testcafe/issues/4360
if (this.contextStorage && this.contextStorage.getItem(TEST_DONE_SENT_FLAG))
e.preventSubmit = true;
}
// Console messages
_onConsoleMessage ({ meth, line }) {
const messages = this.consoleMessages;
messages.addMessage(meth, line, this.windowId);
this.consoleMessages = messages;
}
// Status
_addPendingErrorToStatus (status) {
const pendingPageError = this.contextStorage.getItem(PENDING_PAGE_ERROR);
if (pendingPageError) {
this.contextStorage.setItem(PENDING_PAGE_ERROR, null);
status.pageError = pendingPageError;
}
}
_addUnexpectedDialogErrorToStatus (status) {
const dialogError = this.nativeDialogsTracker.getUnexpectedDialogError();
status.pageError = status.pageError || dialogError;
}
_addConsoleMessagesToStatus (status) {
status.consoleMessages = this.consoleMessages;
this.consoleMessages = null;
}
_addPendingWindowSwitchingStateToStatus (status) {
status.isPendingWindowSwitching = this._isPendingSwitchingWindow();
}
_sendStatusRequest (status) {
const statusRequestOptions = {
cmd: TEST_RUN_MESSAGES.ready,
status: status,
disableResending: true,
allowRejecting: true,
};
const requestAttempt = () => getTimeLimitedPromise(transport.asyncServiceMsg(statusRequestOptions), SEND_STATUS_REQUEST_TIME_LIMIT);
const retryRequest = () => delay(SEND_STATUS_REQUEST_RETRY_DELAY).then(requestAttempt);
let statusPromise = requestAttempt();
for (let i = 0; i < SEND_STATUS_REQUEST_RETRY_COUNT; i++)
statusPromise = statusPromise.catch(retryRequest);
return statusPromise;
}
_sendStatus (status) {
// NOTE: We should not modify the status if it is resent after
// the page load because the server has cached the response
if (!status.resent) {
this._addPendingErrorToStatus(status);
this._addUnexpectedDialogErrorToStatus(status);
this._addConsoleMessagesToStatus(status);
this._addPendingWindowSwitchingStateToStatus(status);
}
this.contextStorage.setItem(PENDING_STATUS, status);
let readyCommandResponse = null;
// NOTE: postpone status sending if the page is unloading
return pageUnloadBarrier
.wait(0)
.then(() => this._sendStatusRequest(status))
//NOTE: do not execute the next command if the page is unloading
.then(res => {
readyCommandResponse = res;
return pageUnloadBarrier.wait(0);
})
.then(() => {
this.contextStorage.setItem(PENDING_STATUS, null);
return readyCommandResponse;
});
}
// Iframes and child windows interaction
_addChildIframeDriverLink (id, driverWindow) {
let childIframeDriverLink = this._getChildIframeDriverLinkByWindow(driverWindow);
if (!childIframeDriverLink) {
const driverId = `${this.testRunId}-${generateId()}`;
childIframeDriverLink = new ChildIframeDriverLink(driverWindow, driverId);
this.childIframeDriverLinks.push(childIframeDriverLink);
}
childIframeDriverLink.sendConfirmationMessage(id);
}
_getTargetWindowNotFoundResult (errCode, errMsg) {
return Promise.resolve({
success: false,
errCode,
errMsg,
});
}
_getChildWindowValidateResult (arr) {
const success = arr.find(item => item.result.success);
if (success)
return success.result;
let errItem = arr.find(item => {
return item.result.errCode === TEST_RUN_ERRORS.cannotCloseWindowWithChildrenError ||
item.result.errCode === TEST_RUN_ERRORS.cannotCloseWindowWithoutParent;
});
if (!errItem)
errItem = arr.find(item => !!item.result.errCode);
return errItem ? { errCode: errItem.result.errCode } : void 0;
}
async _handleWindowValidation (msg, wnd, getWindowFoundResult, WindowValidationMessageCtor) {
const result = await this._validateWindow(msg, wnd, getWindowFoundResult, WindowValidationMessageCtor);
sendConfirmationMessage({
requestMsgId: msg.id,
window: wnd,
result,
});
}
_getWindowInfo () {
const parsedUrl = hammerhead.utils.url.parseProxyUrl(window.location.toString());
return {
id: this.windowId,
title: document.title,
url: parsedUrl.destUrl,
};
}
_isTargetWindow (msg) {
return msg.windowId === this.windowId;
}
async _validateWindow (msg, wnd, getWindowFoundResult, WindowValidationMessageCtor) {
const windowExists = this._isTargetWindow(msg);
if (windowExists)
return getWindowFoundResult();
if (!this.childWindowDriverLinks.length)
return this._getTargetWindowNotFoundResult(TEST_RUN_ERRORS.targetWindowNotFoundError);
const searchQueries = this.childWindowDriverLinks.map(childWindowDriverLink => {
return childWindowDriverLink.findChildWindows(msg, WindowValidationMessageCtor);
});
const searchResults = await Promise.all(searchQueries);
return this._getChildWindowValidateResult(searchResults);
}
static _createWindowValidationError ({ errCode }) {
if (errCode === TEST_RUN_ERRORS.cannotCloseWindowWithChildrenError)
return new CannotCloseWindowWithChildrenError();
if (errCode === TEST_RUN_ERRORS.cannotCloseWindowWithoutParent)
return new CannotCloseWindowWithoutParentError();
return new WindowNotFoundError();
}
_getCloseWindowFoundResult () {
if (!this.parentWindowDriverLink) {
return Promise.resolve({
success: false,
errCode: TEST_RUN_ERRORS.cannotCloseWindowWithoutParent,
});
}
if (this.childWindowDriverLinks.length) {
return Promise.resolve({
success: false,
errCode: TEST_RUN_ERRORS.cannotCloseWindowWithChildrenError,
});
}
return Promise.resolve({ success: true });
}
_handleCloseWindowValidation (msg, wnd) {
const getWindowFoundResult = () => {
return this._getCloseWindowFoundResult();
};
return this._handleWindowValidation(msg, wnd, getWindowFoundResult, CloseWindowValidationMessage);
}
_handleSwitchToWindowValidation (msg, wnd) {
const getWindowFoundResult = () => {
return Promise.resolve({ success: true });
};
return this._handleWindowValidation(msg, wnd, getWindowFoundResult, SwitchToWindowValidationMessage);
}
async _handleCloseWindow (msg, wnd) {
await this._closeWindow(msg, wnd);
sendConfirmationMessage({
requestMsgId: msg.id,
window: wnd,
});
}
_closeWindowAndWait (childWindowToClose, msg) {
const waitWindowForClose = this._createWaitForEventPromise(CHILD_WINDOW_CLOSED_EVENT, CHILD_WINDOW_CLOSED_EVENT_TIMEOUT);
childWindowToClose.ignoreMasterSwitching = !msg.isCurrentWindow;
childWindowToClose.driverWindow.close();
return waitWindowForClose;
}
_closeWindow (msg) {
if (!this.childWindowDriverLinks.length)
return Promise.resolve();
const childWindowToClose = this.childWindowDriverLinks.find(link => link.windowId === msg.windowId);
if (childWindowToClose)
return this._closeWindowAndWait(childWindowToClose, msg);
const searchQueries = this.childWindowDriverLinks.map(childWindowDriverLink => {
return childWindowDriverLink.findChildWindows(msg, CloseWindowCommandMessage);
});
return Promise.all(searchQueries);
}
async _getWindows () {
if (!this.childWindowDriverLinks.length)
return [this._getWindowInfo()];
const searchQueries = this.childWindowDriverLinks.map(childWindowDriverLink => {
return childWindowDriverLink.findChildWindows({}, GetWindowsMessage);
});
const searchResults = await Promise.all(searchQueries);
let result = [this._getWindowInfo()];
for (const item of searchResults) {
if (Array.isArray(item.result))
result = result.concat(item.result);
}
return result;
}
async _handleGetWindows (msg, wnd) {
const result = await this._getWindows(msg, wnd);
sendConfirmationMessage({
requestMsgId: msg.id,
window: wnd,
result,
});
}
async _handleSwitchToWindow (msg, wnd) {
await this._switchToWindow(msg);
sendConfirmationMessage({
requestMsgId: msg.id,
window: wnd,
});
}
_switchToWindow (msg) {
if (this._isTargetWindow(msg)) {
return Promise.resolve()
.then(() => {
this._setCurrentWindowAsMaster();
});
}
if (!this.childWindowDriverLinks.length)
return Promise.resolve();
return Promise.all(this.childWindowDriverLinks.map(childWindowDriverLink => {
return childWindowDriverLink.findChildWindows(msg, SwitchToWindowCommandMessage);
}));
}
_handleSetAsMasterMessage (msg, wnd) {
// NOTE: The 'setAsMaster' message can be send a few times because
// the 'sendMessageToDriver' function resend messages if the message confirmation is not received in 1 sec.
// This message can be send even after driver is started.
if (this._setAsMasterInProgressOrCompleted())
return;
this.setAsMasterInProgress = true;
sendConfirmationMessage({
requestMsgId: msg.id,
window: wnd,
});
Promise.resolve()
.then(() => {
return browser.setActiveWindowId(this.browserActiveWindowId, hammerhead.createNativeXHR, this.windowId);
})
.then(() => {
this._startInternal({
finalizePendingCommand: msg.finalizePendingCommand,
result: { id: this.windowId },
});
this.setAsMasterInProgress = false;
})
.catch(() => {
this._onReady(new DriverStatus({
isCommandResult: true,
executionError: new CannotSwitchToWindowError(),
}));
});
}
_handleCloseAllWindowsMessage (msg, wnd) {
this._closeAllChildWindows()
.then(() => {
sendConfirmationMessage({
requestMsgId: msg.id,
window: wnd,
});
})
.catch(() => {
this._onReady(new DriverStatus({
isCommandResult: true,
executionError: new CloseChildWindowError(),
}));
});
}
_handleStartToRestoreChildLinkMessage () {
this.parentWindowDriverLink.restoreChild(this._getCurrentWindowId());
}
_handleHasPendingActionFlags (msg, window) {
const result = this._hasPendingActionFlags(this.contextStorage);
sendConfirmationMessage({
requestMsgId: msg.id,
window,
result,
});
}
_handleRestoreChildLink (msg, wnd) {
if (this._stopRespondToChildren)
return;
this._addChildWindowDriverLink({ window: wnd, windowId: msg.windowId });
const allChildWindowLinksRestored = this.childWindowDriverLinks.length === this.contextStorage.getItem(PENDING_CHILD_WINDOW_COUNT);
if (allChildWindowLinksRestored && this._restoreChildWindowsPromiseResolver) {
this._restoreChildWindowsPromiseResolver();
delete this._restoreChildWindowsPromiseResolver;
this.contextStorage.setItem(PENDING_CHILD_WINDOW_COUNT, 0);
}
sendConfirmationMessage({
requestMsgId: msg.id,
window: wnd,
});
}
_handleChildWindowIsOpenedInIFrame () {
// NOTE: when the child window is opened in iframe we need to wait until the
// child window is fully loaded
this._pendingChildWindowInIFrame = new Promise(resolve => {
this._resolvePendingChildWindowInIframe = resolve;
});
}
_handleChildWindowIsLoadedInIFrame (msg, wnd) {
sendConfirmationMessage({
requestMsgId: msg.id,
window: wnd,
});
this._resolvePendingChildWindowInIframe();
const childWindowDriverLinkExists = !!this.childWindowDriverLinks.find(link => link.windowId === msg.windowId);
if (!childWindowDriverLinkExists)
this._onChildWindowOpened({ window: wnd, windowId: msg.windowId });
}
_handleStopInternalFromFrame (msg, wnd) {
sendConfirmationMessage({
requestMsgId: msg.id,
window: wnd,
});
this.contextStorage.setItem(this.EXECUTING_IN_IFRAME_FLAG, false);
this._stopInternal();
}
_initChildDriverListening () {
messageSandbox.on(messageSandbox.SERVICE_MSG_RECEIVED_EVENT, e => {
const msg = e.message;
const window = e.source;
switch (msg.type) {
case MESSAGE_TYPE.establishConnection:
this._addChildIframeDriverLink(msg.id, window);
break;
case MESSAGE_TYPE.childWindowIsOpenedInIFrame:
this._handleChildWindowIsOpenedInIFrame(msg, window);
break;
case MESSAGE_TYPE.childWindowIsLoadedInIFrame:
this._handleChildWindowIsLoadedInIFrame(msg, window);
break;
case MESSAGE_TYPE.stopInternalFromFrame:
this._handleStopInternalFromFrame(msg, window);
break;
case MESSAGE_TYPE.setAsMaster:
this._handleSetAsMasterMessage(msg, window);
break;
case MESSAGE_TYPE.switchToWindow:
this._handleSwitchToWindow(msg, window);
break;
case MESSAGE_TYPE.closeWindow:
this._handleCloseWindow(msg, window);
break;
case MESSAGE_TYPE.switchToWindowValidation:
this._handleSwitchToWindowValidation(msg, window);
break;
case MESSAGE_TYPE.closeWindowValidation:
this._handleCloseWindowValidation(msg, window);
break;
case MESSAGE_TYPE.getWindows:
this._handleGetWindows(msg, window);
break;
case MESSAGE_TYPE.closeAllChildWindows:
this._handleCloseAllWindowsMessage(msg, window);
break;
case MESSAGE_TYPE.startToRestoreChildLink:
this._handleStartToRestoreChildLinkMessage();
break;
case MESSAGE_TYPE.hasPendingActionFlags:
this._handleHasPendingActionFlags(msg, window);
break;
case MESSAGE_TYPE.restoreChildLink:
this._handleRestoreChildLink(msg, window);
}
});
}
_getChildIframeDriverLinkByWindow (driverWindow) {
return arrayUtils.find(this.childIframeDriverLinks, link => link.driverWindow === driverWindow);
}
_getChildWindowDriverLinkByWindow (childDriverWindow) {
return arrayUtils.find(this.childWindowDriverLinks, link => link.driverWindow === childDriverWindow);
}
_runInActiveIframe (command) {
let runningChain = Promise.resolve();
const activeIframeSelector = this.contextStorage.getItem(ACTIVE_IFRAME_SELECTOR);
// NOTE: if the page was reloaded we restore the active child driver link via the iframe selector
if (!this.activeChildIframeDriverLink && activeIframeSelector)
runningChain = this._switchToIframe(activeIframeSelector, CURRENT_IFRAME_ERROR_CTORS);
runningChain
.then(() => {
this.contextStorage.setItem(this.EXECUTING_IN_IFRAME_FLAG, true);
return this.activeChildIframeDriverLink.executeCommand(command, this.speed);
})
.then(status => this._onCommandExecutedInIframe(status))
.catch(err => this._onCommandExecutedInIframe(new DriverStatus({
isCommandResult: true,
executionError: err,
})));
}
_onCommandExecutedInIframe (status) {
this.contextStorage.setItem(this.EXECUTING_IN_IFRAME_FLAG, false);
let promise = Promise.resolve();
if (this._pendingChildWindowInIFrame)
promise = this._pendingChildWindowInIFrame;
promise.then(() => {
this._onReady(status);
});
}
_ensureChildIframeDriverLink (iframeWindow, ErrorCtor, selectorTimeout) {
// NOTE: a child iframe driver should establish connection with the parent when it's loaded.
// Here we are waiting while the appropriate child iframe driver do this if it didn't do yet.
return waitFor(() => this._getChildIframeDriverLinkByWindow(iframeWindow), CHECK_IFRAME_DRIVER_LINK_DELAY, selectorTimeout)
.catch(() => {
throw new ErrorCtor();
});
}
_ensureChildWindowDriverLink (childWindow, ErrorCtor, timeout) {
// NOTE: a child window driver should establish connection with the parent when it's loaded.
// Here we are waiting while the appropriate child window driver do this if it didn't do yet.
return waitFor(() => this._getChildWindowDriverLinkByWindow(childWindow), CHECK_CHILD_WINDOW_DRIVER_LINK_DELAY, timeout)
.catch(() => {
throw new ErrorCtor();
});
}
_switchToIframe (selector, iframeErrorCtors) {
const hasSpecificTimeout = typeof selector.timeout === 'number';
const commandSelectorTimeout = hasSpecificTimeout ? selector.timeout : this.selectorTimeout;
return getExecuteSelectorResult(selector, commandSelectorTimeout, null,
fn => new iframeErrorCtors.NotFoundError(null, fn), () => new iframeErrorCtors.IsInvisibleError(), this.statusBar)
.then(iframe => {
if (!domUtils.isIframeElement(iframe))
throw new ActionElementNotIframeError();
return this._ensureChildIframeDriverLink(nativeMethods.contentWindowGetter.call(iframe),
iframeErrorCtors.NotLoadedError, commandSelectorTimeout);
})
.then(childDriverLink => {
childDriverLink.availabilityTimeout = commandSelectorTimeout;
this.activeChildIframeDriverLink = childDriverLink;
this.contextStorage.setItem(ACTIVE_IFRAME_SELECTOR, selector);
});
}
_createWaitForEventPromise (eventName, timeout) {
let eventHandler = null;
const timeoutPromise = new Promise(resolve => {
nativeMethods.setTimeout.call(window, () => {
this.off(eventName, eventHandler);
resolve();
}, timeout);
});
const resultPromise = new Promise(resolve => {
eventHandler = function () {
this.off(eventName, eventHandler);
resolve();
};
this.on(eventName, eventHandler);
});
return Promise.race([timeoutPromise, resultPromise]);
}
_waitForCurrentCommandCompletion () {
if (!this.contextStorage.getItem(this.COMMAND_EXECUTING_FLAG))
return Promise.resolve();
return this._createWaitForEventPromise(STATUS_WITH_COMMAND_RESULT_EVENT, COMMAND_EXECUTION_MAX_TIMEOUT);
}
_waitForEmptyCommand () {
return this._createWaitForEventPromise(EMPTY_COMMAND_EVENT, EMPTY_COMMAND_EVENT_WAIT_TIMEOUT);
}