This repository was archived by the owner on Apr 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathhelpers.js
2275 lines (2071 loc) · 67.7 KB
/
helpers.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const restmail = require('../../lib/restmail');
const TestHelpers = require('../../lib/helpers');
const selectors = require('./selectors');
const pollUntil = require('leadfoot/helpers/pollUntil');
const Url = require('url');
const Querystring = require('querystring');
const nodeXMLHttpRequest = require('xmlhttprequest');
const assert = intern.getPlugin('chai').assert;
// Default options for TOTP
const otplib = require('otplib');
otplib.authenticator.options = {encoding: 'hex'};
const FxaClient = require('fxa-js-client');
const got = require('got');
const config = intern._config;
const AUTH_SERVER_ROOT = config.fxaAuthRoot;
const CONTENT_SERVER = config.fxaContentRoot;
const EXTERNAL_SITE_LINK_TEXT = 'More information';
const EXTERNAL_SITE_URL = 'http://example.com';
const FORCE_AUTH_URL = config.fxaContentRoot + 'force_auth';
const OAUTH_APP = config.fxaOAuthApp;
const RESET_PASSWORD_URL = config.fxaContentRoot + 'reset_password';
const SETTINGS_URL = config.fxaContentRoot + 'settings';
const SIGNIN_URL = config.fxaContentRoot + 'signin';
const SIGNUP_URL = config.fxaContentRoot + 'signup';
const ENABLE_TOTP_URL = `${SETTINGS_URL}/two_step_authentication`;
const UNTRUSTED_OAUTH_APP = config.fxaUntrustedOauthApp;
/**
* Convert a function to a form that can be used as a `then` callback.
* If the callback fails a screenshot will be taken.
*
* Example usage:
*
* const fillOutSignUp = thenify(function (email, password) {
* return this.parent
* .then(....
* });
*
* ...
* .then(fillOutSignUp(email, password))
* ...
*
* @param {function} callback - Function to convert
* @param {object} [context] - in which to call callback
* @returns {function} that can be used in a promise
*/
function thenify(callback, context) {
return function () {
var args = arguments;
return function () {
let capturedError;
return callback.apply(context || this, args)
.then(null, err => {
// The error has to be swallowed before a screenshot
// can be taken or else takeScreenshot is never called
// because `this.parent` is a promise that has already
// been rejected.
capturedError = err;
})
.then(function (result) {
if (capturedError) {
if (! capturedError.screenshotTaken) {
capturedError.screenshotTaken = true;
return this.parent.then(takeScreenshot()) //eslint-disable-line no-use-before-define
.then(() => {
throw capturedError;
});
} else {
throw capturedError;
}
}
return result;
});
};
};
}
/**
* Take a screen shot, write a base64 encoded image to the console
*/
const takeScreenshot = function () {
return function () {
return this.parent.takeScreenshot()
.then(function (buffer) {
const screenCaptureHost = 'https://screencap.co.uk';
return got.post(`${screenCaptureHost}/png`, { body: buffer, followRedirect: false })
.then((res) => {
console.log(`Screenshot saved at: ${screenCaptureHost}${res.headers.location}`);
}, (err) => {
console.error('Capturing base64 screenshot:');
console.error(`data:image/png;base64,${buffer.toString('base64')}`);
});
});
};
};
/**
* Use document.querySelectorAll to find visible elements
* used for error and success notification animations.
*
*
* Usage: ".then(FunctionalHelpers.visibleByQSA('.success'))"
*
* @param {String} selector
* QSA compatible selector string
* @param {Object} options
* options include polling `timeout`
*/
const visibleByQSA = thenify(function (selector, options = {}) {
var timeout = options.timeout || config.pageLoadTimeout;
return this.parent
.then(pollUntil(function (selector, options) {
var matchingEls = document.querySelectorAll(selector);
if (matchingEls.length === 0) {
return null;
}
if (matchingEls.length > 1) {
throw new Error('Multiple elements matched. Make a more precise selector - ' + selector);
}
var matchingEl = matchingEls[0];
// Check if the element is visible. This is from jQuery source - see
// https://github.com/jquery/jquery/blob/e1b1b2d7fe5aff907a9accf59910bc3b7e4d1dec/src/css/hiddenVisibleSelectors.js#L12
if (! (matchingEl.offsetWidth || matchingEl.offsetHeight || matchingEl.getClientRects().length)) {
return null;
}
// use jQuery if available to check for jQuery animations.
if (typeof $ !== 'undefined' && $(selector).is(':animated')) {
// If the element is animating, try again after a delay. Clicks
// do not always register if the element is in the midst of
// an animation.
return null;
}
return true;
}, [ selector, options ], timeout))
.then(null, function (err) {
if (/ScriptTimeout/.test(String(err))) {
throw new Error(`ElementNotVisible - ${selector}`);
} else {
throw err;
}
});
});
/**
* Check to ensure an element exists
*
* @param {string} selector
* @returns {promise} rejects if element does not exist
*/
const testElementExists = thenify(function (selector) {
return this.parent
.findByCssSelector(selector)
.end();
});
/**
* Click an element defined by `selector`, wait for an optional `readySelector`
* to be displayed.
*
* @param {string} selector
* @param {string} [readySelector]
* @returns {promise}
*/
const click = thenify(function (selector, readySelector) {
return this.parent
.findByCssSelector(selector)
// Ensure the element is visible and not animating before attempting to click.
// Sometimes clicks do not register if the element is in the middle of an animation.
.then(visibleByQSA(selector))
.click()
.then(null, (err) => {
// If element is obscured (possibly by a verification message covering it), attempt
// to scroll to the top of page where it might be visible.
if (/obscures it/.test(err.message)) {
return this.parent
.execute(() => {
window.scrollTo(0, 0);
})
.findByCssSelector(selector)
.click()
.then(null, (err) => {
// STILL obscured? There may be a status message
// overlayed on top. Wait a few seconds and try
// one final time.
if (/obscures it/.test(err.message)) {
return this.parent
.sleep(6000)
.findByCssSelector(selector)
.click()
.end();
}
throw err;
})
.end();
}
// Check to see if the error is a `stale element exception` and
// retry clicking if it is. This could happen if a panel on
// the page is re-rendered causing the element to be removed
// from the DOM.
if (/either the element is no longer attached to the DOM/.test(err.message)) {
return this.parent
.sleep(2000)
.findByCssSelector(selector)
.click()
.then(null, (err) => {
throw err;
})
.end();
}
// re-throw other errors
throw err;
})
.end()
.then(function () {
if (readySelector) {
return this.parent
.then(testElementExists(readySelector));
}
});
});
/**
* Force a focus event to fire on an element.
*
* @param {string} [selector] - selector of element - defaults to the window.
* @returns {promise} - resolves when complete
*/
const focus = thenify(function (selector) {
return this.parent
.execute(function (selector) {
// The only way to reliably cause a Focus Event is to manually create
// one. Just clicking or focusing the window does not work if the
// Selenium window is not in focus. This does however. BAM! See the
// conversation in
// https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/1671
// The hint is: "... a hack to work around synthesized events not behaving properly"
var target = selector ? document.querySelector(selector) : window;
var event = new FocusEvent('focus');
target.dispatchEvent(event);
}, [ selector ]);
});
/**
* Type text into an input element
*
* @param {string} selector
* @param {string} text
* @param {object} [options] options
* @param {boolean} [options.clearValue] - clear element value before
* typing. Defaults to true.
* @returns {promise}
*/
const type = thenify(function (selector, text, options = {}) {
// always clear unless explicitly overridden
var clearValue = options.clearValue !== false;
text = String(text);
return this.parent
.then(click(selector))
.findByCssSelector(selector)
.then(function () {
if (clearValue) {
return this.parent.clearValue();
}
})
.getAttribute('type')
.then(function (type) {
// xxx: bug in selenium 2.47.1, if firefox is out of
// focus it will just type 1 number, split the type
// commands for each character to avoid issues with the
// test runner
// calling `type` with more than one character on the "signup_password"
// screen causes nothing to be written on the second attempt.
if (type === 'number' || type === 'password') {
var index = 0;
var parent = this.parent;
var typeNext = function () {
if (index >= text.length) {
return;
}
var charToType = text.charAt(index);
index++;
return parent
.type(charToType)
.then(typeNext);
};
return typeNext.call(this);
} else {
return this.parent.type(text);
}
})
.end();
});
const clearContentServerState = thenify(function (options) {
options = options || {};
// clear localStorage to avoid polluting other tests.
return this.parent
// always go to the content server so the browser state is cleared,
// switch to the top level frame, if we aren't already. This fixes the
// iframe flow.
.switchToFrame(null)
.setFindTimeout(config.pageLoadTimeout)
.getCurrentUrl()
.then(function (url) {
// only load up the content server if we aren't
// already at the content server.
if (url.indexOf(CONTENT_SERVER) === -1 || options.force) {
return this.parent.get(CONTENT_SERVER + 'clear')
.setFindTimeout(config.pageLoadTimeout)
.findById('fxa-clear-storage-header');
}
})
.clearCookies()
.execute(function () {
try {
localStorage.clear();
sessionStorage.clear();
} catch (e) {
console.log('Failed to clearBrowserState');
// if cookies are disabled, this will blow up some browsers.
}
return true;
}, []);
});
const clear123DoneState = thenify(function (options) {
options = options || {};
var app = options.untrusted ? UNTRUSTED_OAUTH_APP : OAUTH_APP;
/**
* Clearing state for 123done is a bit of a hack.
* When the user clicks "Sign out", the buttons to signup/signin
* are shown without waiting for the XHR request to complete.
* If Selenium moves too quickly and loads another page before the XHR
* request completes, the request is aborted and the user never signs out,
* causing state to hang around and problems later on.
*
* To get around this, manually sign the user out by calling the
* logout endpoint on the server, then notify Selenium when that request
* completes by adding an element to the DOM. Selenium will look for
* the added element.
*/
return this.parent
// switch to the top level frame, if we aren't already. This fixes the
// iframe flow.
.switchToFrame(null)
.setFindTimeout(config.pageLoadTimeout)
.get(app)
.then(testElementExists('#footer-main'))
.execute(function () {
/* global $ */
$.post('/api/logout/')
.always(function () {
$('body').append('<div id="loggedout">Logged out</div>');
});
})
.then(testElementExists('#loggedout'));
});
/**
* Close all windows but the first. Used to cleanup after
* failing functional tests where the test fails when checking
* the 2nd window.
*
* @returns {Promise}
*/
const closeAllButFirstWindow = thenify(function () {
return this.parent
.getAllWindowHandles()
.then(function (handles) {
if (handles.length > 1) {
return this.parent
.switchToWindow(handles[1])
.closeCurrentWindow()
.switchToWindow(handles[0])
.then(closeAllButFirstWindow());
}
});
});
const clearBrowserState = thenify(function (options) {
options = options || {};
if (! ('contentServer' in options)) {
options.contentServer = true;
}
if (! ('123done' in options)) {
options['123done'] = false;
}
if (! ('321done' in options)) {
options['321done'] = false;
}
return this.parent
.then(function () {
if (options.contentServer) {
return this.parent
.then(clearContentServerState(options));
}
})
.then(function () {
if (options['123done']) {
return this.parent
.then(clear123DoneState());
}
})
.then(function () {
if (options['321done']) {
return this.parent
.then(clear123DoneState( { untrusted: true }));
}
})
.then(closeAllButFirstWindow());
});
const clearSessionStorage = thenify(function () {
// clear sessionStorage to avoid polluting other tests.
return this.parent
.execute(function () {
try {
sessionStorage.clear();
} catch (e) {
console.log('Failed to clearSessionStorage');
}
return true;
}, []);
});
/**
* Use document.querySelectorAll to find loaded images.
* Images that are loading/have loaded without error
* will have a naturalWidth > 0, so we check for that.
*
* Usage: ".then(FunctionalHelpers.imageLoadedByQSA('img'))"
*
* @param {String} selector
* QSA compatible selector string
*/
const imageLoadedByQSA = thenify(function(selector, timeout = 10000) {
return this.parent
.then(pollUntil(function (selector) {
var match = document.querySelectorAll(selector);
if (match.length > 1) {
throw new Error('Multiple elements matched. Make a more precise selector');
}
return match[0] && match[0].naturalWidth > 0 ? true : null;
}, [ selector ], timeout));
});
/**
* Use document.querySelectorAll and poll until to find loaded images.
*
* Usage: ".then(FunctionalHelpers.pollUntilGoneByQSA('.disabled'))"
*
* @param {String} selector
* QSA compatible selector string
* @param {Number} [timeout]
* Timeout to wait until element is gone
*/
const pollUntilGoneByQSA = thenify(function(selector, timeout = 10000) {
return this.parent
.then(pollUntil(function (selector) {
return document.querySelectorAll(selector).length === 0 ? true : null;
}, [ selector ], timeout));
});
/**
* Poll until an element is either removed from the DOM or hidden.
*
* @param {String} selector
* QSA compatible selector string
* @param {Number} [timeout=config.pageLoadTimeout]
* Timeout to wait until element is gone or hidden
*/
const pollUntilHiddenByQSA = thenify(function (selector, timeout = config.pageLoadTimeout) {
return this.parent
.then(pollUntil(function (selector) {
const matchingEls = document.querySelectorAll(selector);
if (matchingEls.length === 0) {
return true;
}
if (matchingEls.length > 1) {
throw new Error('Multiple elements matched. Make a more precise selector - ' + selector);
}
const matchingEl = matchingEls[0];
// Check if the element is visible. This is from jQuery source - see
// https://github.com/jquery/jquery/blob/e1b1b2d7fe5aff907a9accf59910bc3b7e4d1dec/src/css/hiddenVisibleSelectors.js#L12
if (! (matchingEl.offsetWidth || matchingEl.offsetHeight || matchingEl.getClientRects().length)) {
return true;
}
// use jQuery if available to check for jQuery animations.
if (typeof $ !== 'undefined' && $(selector).is(':animated')) {
// If the element is animating, try again after a delay. Clicks
// do not always register if the element is in the midst of
// an animation.
return null;
}
return null;
}, [ selector ], timeout))
.then(null, function (err) {
if (/ScriptTimeout/.test(String(err))) {
throw new Error(`ElementNotHidden - ${selector}`);
} else {
throw err;
}
});
});
/**
* Ensure no such element exists.
*
* @param {string} selector of element to ensure does not exist.
* @param {number} [timeoutMS] number of ms to wait for the element. Defaults to 0.
* @returns {promise} resolves when complete, fails if element exists.
*/
const noSuchElement = thenify(function (selector, timeoutMS = 0) {
return this.parent
.setFindTimeout(timeoutMS)
.findByCssSelector(selector)
.then(function () {
throw new Error(selector + ' should not be present');
}, function (err) {
if (/NoSuchElement/.test(String(err))) {
// swallow the error
return;
}
throw err;
})
.end()
.setFindTimeout(config.pageLoadTimeout);
});
/**
* Get an fxa-js-client instance
*
* @returns {Object}
*/
function getFxaClient () {
return new FxaClient(AUTH_SERVER_ROOT, {
xhr: nodeXMLHttpRequest.XMLHttpRequest
});
}
/**
* Get the value of a query parameter
*
* @param {String} paramName
* @returns {promise} that resolves to the query parameter's value
*/
const getQueryParamValue = thenify(function (paramName) {
return this.parent
.getCurrentUrl()
.then(function (url) {
var parsedUrl = Url.parse(url);
var parsedQueryString = Querystring.parse(parsedUrl.query);
return parsedQueryString[paramName];
});
});
/**
* Get an email
*
* @param {string} user - username or email address
* @param {number} index - email index.
* @param {object} [options]
* @param {number} [options.maxAttempts] - number of email fetch attempts
* to make. Defaults to 10.
* @returns {promise} resolves with the email if email is found.
*/
const getEmail = thenify(function (user, index, options) {
if (/@/.test(user)) {
user = TestHelpers.emailToUser(user);
}
// restmail takes a count, not an index. Add 1.
return this.parent
.then(() => restmail.waitForEmail(user, index + 1, options))
.then((emails) => emails[index]);
});
/**
* Delete all emails for `user`
*
* @param {String} user - username or email address
* @returns {Promise} resolves when complete
*/
const deleteAllEmails = thenify(function (user) {
if (/@/.test(user)) {
user = TestHelpers.emailToUser(user);
}
return this.parent
.then(() => restmail.deleteAllEmails(user));
});
/**
* Tests that send an SMS should be wrapped by `disableInProd`. This will
* prevent the tests from running in stage/prod where we should not
* send SMSs to random people.
*
* @param {Function} test
* @returns {Function}
*/
function disableInProd(test) {
if (intern._config.fxaProduction) {
return function () {
};
}
return test;
}
/**
* Get SMS message `index` for `phoneNumber`.
*
* @param {String} phoneNumber
* @param {Number} index
* @param {Object} [options={}]
* @param {Number} [options.maxAttempts] - number of email fetch attempts
* to make. Defaults to 10.
* @returns {Promise} resolves with the SMS, if found.
*/
const getSms = thenify(function (phoneNumber, index, options) {
return this.parent
.then(getEmail(phoneNumberToEmailAddress(phoneNumber), index, options))
.then((email) => {
return email.text.trim();
});
});
/**
* Delete all SMS messages for `phoneNumber`
*
* @param {String} phoneNumber
* @returns {Promise} resolves when complete
*/
const deleteAllSms = thenify(function (phoneNumber) {
return this.parent
.then(deleteAllEmails(phoneNumberToEmailAddress(phoneNumber)));
});
/**
* Convert a phone number to an email address
*
* @param {String} phoneNumber
* @returns {String}
*/
function phoneNumberToEmailAddress(phoneNumber) {
return `sms.+1${phoneNumber}`;
}
/**
* Ensure SMS message `index` for `phoneNumber` matches `smsFormatRegExp`
*
* @param {String} phoneNumber
* @param {Number} index
* @param {RegExp} smsFormatRegExp
* @returns {Promise} resolves when complete
*/
const testSmsFormat = thenify(function (phoneNumber, index, smsFormatRegExp) {
return this.parent
.then(getSms(phoneNumber, index))
.then((sms) => {
assert.isTrue(smsFormatRegExp.test(sms));
});
});
const SIGNIN_CODE_SMS_FORMAT = /m\/([a-zA-Z0-9_-]{8,8})$/;
/**
* Get a signinCode from the SMS message `index` for `phoneNumber`
*
* @param {String} phoneNumber
* @param {Number} index
* @param {RegExp} smsFormatRegExp
* @returns {Promise} resolves with the signinCode when complete
*/
const getSmsSigninCode = thenify(function (phoneNumber, index, options) {
return this.parent
.then(testSmsFormat(phoneNumber, index, SIGNIN_CODE_SMS_FORMAT))
.then(getSms(phoneNumber, index, options))
.then((sms) => {
return SIGNIN_CODE_SMS_FORMAT.exec(sms)[1];
});
});
/**
* Get the email headers
*
* @param {string} user - username or email address
* @param {number} index - email index.
* @param {object} [options]
* @param {number} [options.maxAttempts] - number of email fetch attempts
* to make. Defaults to 10.
* @returns {promise} resolves with the email headers if email is found.
*/
const getEmailHeaders = thenify(function(user, index, options) {
return this.parent
.then(getEmail(user, index, options))
.then((email) => email.headers);
});
/**
* Get an email verification link
*
* @param {string} user username or email
* @param {number} index email index
* @returns {promise} resolves with verification link
*/
const getVerificationLink = thenify(function(user, index) {
if (/@/.test(user)) {
user = TestHelpers.emailToUser(user);
}
return this.parent
.then(getEmailHeaders(user, index))
.then(function (headers) {
const link = headers['x-link'];
if (! link) {
throw new Error('Email does not contain verification link: ' + headers['x-template-name']);
}
return link;
});
});
/**
* Get the code, uid and reportSignInLink from the unblock email.
*
* @param {string} user or email
* @param {number} index
* @returns {promise} that resolves with object containing
* `code`, `uid`, and `reportSignInLink`
*/
const getUnblockInfo = thenify(function (user, index) {
if (/@/.test(user)) {
user = TestHelpers.emailToUser(user);
}
return this.parent
.then(getEmailHeaders(user, index))
.then(function (headers) {
const unblockCode = headers['x-unblock-code'];
if (! unblockCode) {
throw new Error('Email does not contain unblock code: ' + headers['x-template-name']);
}
return {
reportSignInLink: headers['x-report-signin-link'],
uid: headers['x-uid'],
unblockCode: unblockCode
};
});
});
/**
* Get the token code from the verify sign-in email.
*
* @param {string} user or email
* @param {number} index
* @returns {promise} that resolves with token code
*/
const getTokenCode = thenify(function (user, index) {
if (/@/.test(user)) {
user = TestHelpers.emailToUser(user);
}
return this.parent
.then(getEmailHeaders(user, index))
.then((headers) => {
const code = headers['x-signin-verify-code'];
if (! code) {
throw new Error('Email does not contain token code: ' + headers['x-template-name']);
}
return code;
});
});
/**
* Test to ensure an expected email arrives
*
* @param {string} user - username or email address
* @param {number} index - email index.
* @param {object} [options]
* @param {number} [options.maxAttempts] - number of email fetch attempts to make.
* Defaults to 10.
* Defaults to 10.
*/
const testEmailExpected = thenify(function (user, index, options) {
return this.parent
.then(getEmailHeaders(user, index, options))
.then(function () {
return true;
}, function (err) {
if (/EmailTimeout/.test(String(err))) {
throw new Error('EmailExpected');
}
throw err;
});
});
/**
* Test to ensure an unexpected email does not arrive
*
* @param {string} user - username or email address
* @param {number} index - email index.
* @param {object} [options]
* @param {number} [options.maxAttempts] - number of email fetch attempts
* to make. Defaults to 10.
*/
const noEmailExpected = thenify(function (user, index, options) {
return this.parent
.then(getEmailHeaders(user, index, options))
.then(function () {
throw new Error('NoEmailExpected');
}, function (err) {
if (/EmailTimeout/.test(String(err))) {
return true;
}
throw err;
});
});
/**
* Open an external site.
*
* @returns {promise} resolves when complete
*/
const openExternalSite = thenify(function () {
return this.parent
.get(EXTERNAL_SITE_URL)
.findByPartialLinkText(EXTERNAL_SITE_LINK_TEXT)
.end();
});
/**
* Open a verification link in a new tab of the same browser.
* @param {string} email user's email
* @param {number} index verification email index
* @param {object} [options] options
* @param {object} [options.query] extra query parameters to add to the verification link
* @returns {promise} resolves when complete
*/
const openVerificationLinkInNewTab = thenify(function (email, index, options = {}) {
var user = TestHelpers.emailToUser(email);
return this.parent
.then(getVerificationLink(user, index))
.then(function (verificationLink) {
const verificationLinkWithParams = addQueryParamsToLink(verificationLink, options.query);
return this.parent
.execute(openWindow, [ verificationLinkWithParams ]);
});
});
const openVerificationLinkInSameTab = thenify(function (email, index, options = {}) {
var user = TestHelpers.emailToUser(email);
return this.parent
.then(getVerificationLink(user, index))
.then(function (verificationLink) {
const verificationLinkWithParams = addQueryParamsToLink(verificationLink, options.query);
return this.parent.get(verificationLinkWithParams);
});
});
/**
* Open a new tab to `url`
*
* @param {String} url to open
* @returns {Promise}
*/
const openTab = thenify(function (url) {
return this.parent.execute(openWindow, [ url ]);
});
/**
* Switch to a new window/tab
*
* @param {Number} which - tab index to switch to
* @returns {Promise}
*/
const switchToWindow = thenify(function (which) {
if (typeof which !== 'number') {
throw new Error('`which` must be a number');
}
return this.parent
.getAllWindowHandles()
.then(function (handles) {
if (handles.length >= which && handles[which]) {
return this.parent.switchToWindow(handles[which]);
} else {
// give a little time to open the browser tab, otherwise
// geckodriver sometimes attempts to switch to the tab
// before it's open. See #4740
return this.parent
.sleep(1000)
.then(switchToWindow(which));
}
});
});
/**
* Respond to a web channel message.
*
* @param {string} expectedCommand command to respond to
* @param {object} response response
* @returns {promise} resolves when complete
*/
const respondToWebChannelMessage = thenify(function (expectedCommand, response) {
var attachedId = Math.floor(Math.random() * 10000);
return this.parent
.execute(function (expectedCommand, response, attachedId) {
function listener(e) {
var command = e.detail.message.command;
var messageId = e.detail.message.messageId;
if (command === expectedCommand) {
removeEventListener('WebChannelMessageToChrome', listener);
var event = new CustomEvent('WebChannelMessageToContent', {
detail: {
id: 'account_updates',
message: {
command: command,
data: response,
messageId: messageId
}
}
});
dispatchEvent(event);
}
}
function startListening() {
try {
addEventListener('WebChannelMessageToChrome', listener);
} catch (e) {
// problem adding the listener, window may not be
// ready, try again.
setTimeout(startListening, 0);
}
const el = document.createElement('div');
el.classList.add(`attached${attachedId}`);
document.body.appendChild(el);
}
startListening();
}, [ expectedCommand, response, attachedId ])
// once the event is attached it adds a div with an attachedId.
.then(testElementExists('.attached' + attachedId));
});
/**
* Store the data sent for a WebChannel event into sessionStorage.
*