-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy path_init_tests.js
583 lines (525 loc) · 16.3 KB
/
_init_tests.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
/**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This must load before all other tests.
import '../src/polyfills';
import * as describes from '../testing/describes';
import * as log from '../src/log';
import {Services} from '../src/services';
import {activateChunkingForTesting} from '../src/chunk';
import {adoptWithMultidocDeps} from '../src/runtime';
import {cancelTimersForTesting} from '../src/service/timer-impl';
import {
installAmpdocServices,
installRuntimeServices,
} from '../src/service/core-services';
import {installDocService} from '../src/service/ampdoc-impl';
import {installYieldIt} from '../testing/yield';
import {removeElement} from '../src/dom';
import {
reportError,
resetAccumulatedErrorMessagesForTesting,
} from '../src/error';
import {resetEvtListenerOptsSupportForTesting} from '../src/event-helper-listen';
import {resetExperimentTogglesForTesting} from '../src/experiments';
import {setDefaultBootstrapBaseUrlForTesting} from '../src/3p-frame';
import {setReportError} from '../src/log';
import sinon from /*OK*/ 'sinon';
import stringify from 'json-stable-stringify';
// Used to print warnings for unexpected console errors.
let that;
let consoleErrorSandbox;
let testName;
let expectedAsyncErrors;
let rethrowAsyncSandbox;
let consoleInfoLogWarnSandbox;
const originalConsoleError = console /*OK*/.error;
// Used to clean up global state between tests.
let initialGlobalState;
let initialWindowState;
// All exposed describes.
global.describes = describes;
// Increase the before/after each timeout since certain times they have timedout
// during the normal 2000 allowance.
const BEFORE_AFTER_TIMEOUT = 5000;
// Needs to be called before the custom elements are first made.
beforeTest();
adoptWithMultidocDeps(window);
// Override AMP.extension to buffer extension installers.
/**
* @param {string} name
* @param {string} version
* @param {function(!Object)} installer
* @const
*/
global.AMP.extension = function(name, version, installer) {
describes.bufferExtension(`${name}:${version}`, installer);
};
// Make amp section in karma config readable by tests.
window.ampTestRuntimeConfig = parent.karma ? parent.karma.config.amp : {};
/**
* Helper class to skip or retry tests under specific environment.
* Should be instantiated via describe.configure() or it.configure().
* Get permission before use!
*
* Example usages:
* describe.configure().skipFirefox().skipSafari().run('Bla bla ...', ... );
* it.configure().skipEdge().run('Should ...', ...);
*/
class TestConfig {
constructor(runner) {
this.runner = runner;
/**
* List of predicate functions that are called before running each test
* suite to check whether the suite should be skipped or not.
* If any of the functions return 'true', the suite will be skipped.
* @type {!Array<function():boolean>}
*/
this.skipMatchers = [];
/**
* List of predicate functions that are called before running each test
* suite to check whether the suite should be skipped or not.
* If any of the functions return 'false', the suite will be skipped.
* @type {!Array<function():boolean>}
*/
this.ifMatchers = [];
/**
* Called for each test suite (things created by `describe`).
* @type {!Array<function(!TestSuite)>}
*/
this.configTasks = [];
this.platform = Services.platformFor(window);
/**
* Predicate functions that determine whether to run tests on a platform.
*/
this.runOnChrome = this.platform.isChrome.bind(this.platform);
this.runOnEdge = this.platform.isEdge.bind(this.platform);
this.runOnFirefox = this.platform.isFirefox.bind(this.platform);
this.runOnSafari = this.platform.isSafari.bind(this.platform);
this.runOnIos = this.platform.isIos.bind(this.platform);
this.runOnIe = this.platform.isIe.bind(this.platform);
/**
* By default, IE is skipped. Individual tests may opt in.
*/
this.skip(this.runOnIe);
}
skipChrome() {
return this.skip(this.runOnChrome);
}
skipEdge() {
return this.skip(this.runOnEdge);
}
skipFirefox() {
return this.skip(this.runOnFirefox);
}
skipSafari() {
return this.skip(this.runOnSafari);
}
skipIos() {
return this.skip(this.runOnIos);
}
skipIfPropertiesObfuscated() {
return this.skip(function() {
return window.__karma__.config.amp.propertiesObfuscated;
});
}
skipSinglePass() {
return this.skip(function() {
return window.__karma__.config.amp.singlePass;
});
}
enableIe() {
this.skipMatchers.splice(this.skipMatchers.indexOf(this.runOnIe), 1);
return this;
}
/**
* @param {function():boolean} fn
*/
skip(fn) {
this.skipMatchers.push(fn);
return this;
}
ifChrome() {
return this.if(this.runOnChrome);
}
ifEdge() {
return this.if(this.runOnEdge);
}
ifFirefox() {
return this.if(this.runOnFirefox);
}
ifSafari() {
return this.if(this.runOnSafari);
}
ifIos() {
return this.if(this.runOnIos);
}
ifIe() {
// It's necessary to first enable IE because we skip it by default.
return this.enableIe().if(this.runOnIe);
}
/**
* @param {function():boolean} fn
*/
if(fn) {
this.ifMatchers.push(fn);
return this;
}
retryOnSaucelabs(times = 4) {
if (!window.ampTestRuntimeConfig.saucelabs) {
return this;
}
this.configTasks.push(mocha => {
mocha.retries(times);
});
return this;
}
/**
* @param {string} desc
* @param {function()} fn
*/
run(desc, fn) {
for (let i = 0; i < this.skipMatchers.length; i++) {
if (this.skipMatchers[i].call(this)) {
this.runner.skip(desc, fn);
return;
}
}
for (let i = 0; i < this.ifMatchers.length; i++) {
if (!this.ifMatchers[i].call(this)) {
this.runner.skip(desc, fn);
return;
}
}
const tasks = this.configTasks;
this.runner(desc, function() {
tasks.forEach(task => {
task(this);
});
return fn.apply(this, arguments);
});
}
}
describe.configure = function() {
return new TestConfig(describe);
};
installYieldIt(it);
it.configure = function() {
return new TestConfig(it);
};
/**
* Prints a warning when a console error is detected during a test.
* @param {*} messages One or more error messages
*/
function printWarning(...messages) {
const message = messages.join(' ');
// Match equal strings.
if (expectedAsyncErrors.includes(message)) {
expectedAsyncErrors.splice(expectedAsyncErrors.indexOf(message), 1);
return;
}
// Match regex.
for (let i = 0; i < expectedAsyncErrors.length; i++) {
const expectedError = expectedAsyncErrors[i];
if (typeof expectedError != 'string') {
if (expectedError.test(message)) {
expectedAsyncErrors.splice(i, 1);
return;
}
}
}
const errorMessage = message.split('\n', 1)[0]; // First line.
const helpMessage =
' The test "' +
testName +
'"' +
' resulted in a call to console.error. (See above line.)\n' +
' ⤷ If the error is not expected, fix the code that generated ' +
'the error.\n' +
' ⤷ If the error is expected (and synchronous), use the following ' +
'pattern to wrap the test code that generated the error:\n' +
" 'allowConsoleError(() => { <code that generated the " +
"error> });'\n" +
' ⤷ If the error is expected (and asynchronous), use the ' +
'following pattern at the top of the test:\n' +
" 'expectAsyncConsoleError(<string or regex>[, <number of" +
' times the error message repeats>]);';
originalConsoleError(errorMessage + "'\n" + helpMessage);
}
/**
* Used during normal test execution, to detect unexpected console errors.
*/
function warnForConsoleError() {
expectedAsyncErrors = [];
consoleErrorSandbox = sinon.createSandbox();
const consoleErrorStub = consoleErrorSandbox
.stub(console, 'error')
.callsFake(printWarning);
self.expectAsyncConsoleError = function(message, repeat = 1) {
expectedAsyncErrors.push.apply(
expectedAsyncErrors,
Array(repeat).fill(message)
);
};
self.allowConsoleError = function(func) {
consoleErrorStub.reset();
consoleErrorStub.callsFake(() => {});
const result = func();
try {
expect(consoleErrorStub).to.have.been.called;
} catch (e) {
const helpMessage =
'The test "' +
testName +
'" contains an "allowConsoleError" block ' +
"that didn't result in a call to console.error.";
originalConsoleError(helpMessage);
} finally {
consoleErrorStub.callsFake(printWarning);
}
return result;
};
}
/**
* Used to restore error level logging after each test.
*/
function restoreConsoleError() {
consoleErrorSandbox.restore();
if (expectedAsyncErrors.length > 0) {
const helpMessage =
'The test "' +
testName +
'" called "expectAsyncConsoleError", ' +
'but there were no call(s) to console.error with these message(s): ' +
'"' +
expectedAsyncErrors.join('", "') +
'"';
that.test.error(new Error(helpMessage));
}
expectedAsyncErrors = [];
}
/**
* Used to silence info, log, and warn level logging during each test, unless
* verbose mode is enabled.
*/
function maybeStubConsoleInfoLogWarn() {
const {verboseLogging} = window.__karma__.config;
if (!verboseLogging) {
consoleInfoLogWarnSandbox = sinon.createSandbox();
consoleInfoLogWarnSandbox.stub(console, 'info').callsFake(() => {});
consoleInfoLogWarnSandbox.stub(console, 'log').callsFake(() => {});
consoleInfoLogWarnSandbox.stub(console, 'warn').callsFake(() => {});
}
}
/**
* Used to precent asynchronous throwing of errors during each test.
*/
function preventAsyncErrorThrows() {
self.stubAsyncErrorThrows = function() {
rethrowAsyncSandbox = sinon.createSandbox();
rethrowAsyncSandbox.stub(log, 'rethrowAsync').callsFake((...args) => {
const error = log.createErrorVargs.apply(null, args);
self.__AMP_REPORT_ERROR(error);
throw error;
});
};
self.restoreAsyncErrorThrows = function() {
rethrowAsyncSandbox.restore();
};
setReportError(reportError);
stubAsyncErrorThrows();
}
before(function() {
// This is a more robust version of `this.skip()`. See #17245.
this.skipTest = function() {
if (this._runnable.title != '"before all" hook') {
throw new Error('skipTest() can only be called from within before()');
}
this.test.parent.pending = true; // Workaround for mochajs/mocha#2683.
this.skip();
};
});
beforeEach(function() {
this.timeout(BEFORE_AFTER_TIMEOUT);
beforeTest();
testName = this.currentTest.fullTitle();
window.sandbox = sinon.createSandbox();
maybeStubConsoleInfoLogWarn();
preventAsyncErrorThrows();
warnForConsoleError();
initialGlobalState = Object.keys(global);
initialWindowState = Object.keys(window);
});
function beforeTest() {
activateChunkingForTesting();
window.__AMP_MODE = undefined;
window.context = undefined;
window.AMP_CONFIG = {
canary: 'testSentinel',
};
window.__AMP_TEST = true;
installDocService(window, /* isSingleDoc */ true);
const ampdoc = Services.ampdocServiceFor(window).getSingleDoc();
installRuntimeServices(window);
installAmpdocServices(ampdoc);
Services.resourcesForDoc(ampdoc).ampInitComplete();
}
/**
* Global cleanup of tags added during tests. Cool to add more to selector.
*/
afterEach(function() {
that = this;
const globalState = Object.keys(global);
const windowState = Object.keys(window);
if (consoleInfoLogWarnSandbox) {
consoleInfoLogWarnSandbox.restore();
}
window.sandbox.restore();
restoreConsoleError();
restoreAsyncErrorThrows();
this.timeout(BEFORE_AFTER_TIMEOUT);
const cleanupTagNames = ['link', 'meta'];
if (!Services.platformFor(window).isSafari()) {
cleanupTagNames.push('iframe');
}
const cleanup = document.querySelectorAll(cleanupTagNames.join(','));
for (let i = 0; i < cleanup.length; i++) {
try {
const element = cleanup[i];
removeElement(element);
} catch (e) {
// This sometimes fails for unknown reasons.
console./*OK*/ log(e);
}
}
window.localStorage.clear();
window.ENABLE_LOG = false;
window.AMP_DEV_MODE = false;
window.context = undefined;
window.__AMP_MODE = undefined;
delete window.document['__AMPDOC'];
if (windowState.length != initialWindowState.length) {
for (let i = initialWindowState.length; i < windowState.length; ++i) {
if (window[windowState[i]]) {
delete window[windowState[i]];
}
}
}
if (initialGlobalState.length != globalState.length) {
for (let i = initialGlobalState.length; i < globalState.length; ++i) {
if (global[globalState[i]]) {
delete global[globalState[i]];
}
}
}
if (!/native/.test(window.setTimeout)) {
throw new Error(
'You likely forgot to restore sinon timers ' +
'(installed via sandbox.useFakeTimers).'
);
}
setDefaultBootstrapBaseUrlForTesting(null);
resetAccumulatedErrorMessagesForTesting();
resetExperimentTogglesForTesting(window);
resetEvtListenerOptsSupportForTesting();
cancelTimersForTesting();
});
chai.Assertion.addMethod('attribute', function(attr) {
const obj = this._obj;
const tagName = obj.tagName.toLowerCase();
this.assert(
obj.hasAttribute(attr),
"expected element '" + tagName + "' to have attribute #{exp}",
"expected element '" + tagName + "' to not have attribute #{act}",
attr,
attr
);
});
chai.Assertion.addMethod('class', function(className) {
const obj = this._obj;
const tagName = obj.tagName.toLowerCase();
this.assert(
obj.classList.contains(className),
"expected element '" + tagName + "' to have class #{exp}",
"expected element '" + tagName + "' to not have class #{act}",
className,
className
);
});
chai.Assertion.addProperty('visible', function() {
const obj = this._obj;
const computedStyle = window.getComputedStyle(obj);
const visibility = computedStyle.getPropertyValue('visibility');
const opacity = computedStyle.getPropertyValue('opacity');
const isOpaque = parseInt(opacity, 10) > 0;
const tagName = obj.tagName.toLowerCase();
this.assert(
visibility === 'visible' && isOpaque,
"expected element '" +
tagName +
"' to be #{exp}, got #{act}. with classes: " +
obj.className,
"expected element '" +
tagName +
"' not to be #{exp}, got #{act}. with classes: " +
obj.className,
'visible and opaque',
`visibility = ${visibility} and opacity = ${opacity}`
);
});
chai.Assertion.addProperty('hidden', function() {
const obj = this._obj;
const computedStyle = window.getComputedStyle(obj);
const visibility = computedStyle.getPropertyValue('visibility');
const opacity = computedStyle.getPropertyValue('opacity');
const tagName = obj.tagName.toLowerCase();
this.assert(
visibility === 'hidden' || parseInt(opacity, 10) == 0,
"expected element '" +
tagName +
"' to be #{exp}, got #{act}. with classes: " +
obj.className,
"expected element '" +
tagName +
"' not to be #{act}. with classes: " +
obj.className,
'hidden',
visibility
);
});
chai.Assertion.addMethod('display', function(display) {
const obj = this._obj;
const value = window.getComputedStyle(obj).getPropertyValue('display');
const tagName = obj.tagName.toLowerCase();
this.assert(
value === display,
"expected element '" + tagName + "' to be display #{exp}, got #{act}.",
"expected element '" + tagName + "' not to be display #{act}.",
display,
value
);
});
chai.Assertion.addMethod('jsonEqual', function(compare) {
const obj = this._obj;
const a = stringify(compare);
const b = stringify(obj);
this.assert(
a == b,
'expected JSON to be equal.\nExp: #{exp}\nAct: #{act}',
'expected JSON to not be equal.\nExp: #{exp}\nAct: #{act}',
a,
b
);
});