-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tests.js
1654 lines (1433 loc) · 63 KB
/
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
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
/*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* eslint-disable indent */
/**
* @fileoverview This file contains small testing framework along with the
* test suite for the frontend. These tests are a part of the continues build
* and are executed by the devtools_browsertest.cc as a part of the
* Interactive UI Test suite.
* FIXME: change field naming style to use trailing underscore.
*/
(function createTestSuite(window) {
const TestSuite = class {
/**
* Test suite for interactive UI tests.
* @param {Object} domAutomationController DomAutomationController instance.
*/
constructor(domAutomationController) {
this.domAutomationController_ = domAutomationController;
this.controlTaken_ = false;
this.timerId_ = -1;
this._asyncInvocationId = 0;
}
/**
* Key event with given key identifier.
*/
static createKeyEvent(key) {
return new KeyboardEvent('keydown', {bubbles: true, cancelable: true, key: key});
}
};
/**
* Reports test failure.
* @param {string} message Failure description.
*/
TestSuite.prototype.fail = function(message) {
if (this.controlTaken_) {
this.reportFailure_(message);
} else {
throw message;
}
};
/**
* Equals assertion tests that expected === actual.
* @param {!Object|boolean} expected Expected object.
* @param {!Object|boolean} actual Actual object.
* @param {string} opt_message User message to print if the test fails.
*/
TestSuite.prototype.assertEquals = function(expected, actual, opt_message) {
if (expected !== actual) {
let message = 'Expected: \'' + expected + '\', but was \'' + actual + '\'';
if (opt_message) {
message = opt_message + '(' + message + ')';
}
this.fail(message);
}
};
/**
* True assertion tests that value == true.
* @param {!Object} value Actual object.
* @param {string} opt_message User message to print if the test fails.
*/
TestSuite.prototype.assertTrue = function(value, opt_message) {
this.assertEquals(true, Boolean(value), opt_message);
};
/**
* Takes control over execution.
* @param {{slownessFactor:number}=} options
*/
TestSuite.prototype.takeControl = function(options) {
const {slownessFactor} = {slownessFactor: 1, ...options};
this.controlTaken_ = true;
// Set up guard timer.
const self = this;
const timeoutInSec = 20 * slownessFactor;
this.timerId_ = setTimeout(function() {
self.reportFailure_(`Timeout exceeded: ${timeoutInSec} sec`);
}, timeoutInSec * 1000);
};
/**
* Releases control over execution.
*/
TestSuite.prototype.releaseControl = function() {
if (this.timerId_ !== -1) {
clearTimeout(this.timerId_);
this.timerId_ = -1;
}
this.controlTaken_ = false;
this.reportOk_();
};
/**
* Async tests use this one to report that they are completed.
*/
TestSuite.prototype.reportOk_ = function() {
this.domAutomationController_.send('[OK]');
};
/**
* Async tests use this one to report failures.
*/
TestSuite.prototype.reportFailure_ = function(error) {
if (this.timerId_ !== -1) {
clearTimeout(this.timerId_);
this.timerId_ = -1;
}
this.domAutomationController_.send('[FAILED] ' + error);
};
TestSuite.prototype.setupLegacyFilesForTest = async function() {
try {
await Promise.all([
self.runtime.loadLegacyModule('core/common/common-legacy.js'),
self.runtime.loadLegacyModule('core/sdk/sdk-legacy.js'),
self.runtime.loadLegacyModule('core/host/host-legacy.js'),
self.runtime.loadLegacyModule('ui/legacy/legacy-legacy.js'),
self.runtime.loadLegacyModule('models/workspace/workspace-legacy.js'),
]);
this.reportOk_();
} catch (e) {
this.reportFailure_(e);
}
};
/**
* Run specified test on a fresh instance of the test suite.
* @param {Array<string>} args method name followed by its parameters.
*/
TestSuite.prototype.dispatchOnTestSuite = async function(args) {
const methodName = args.shift();
try {
await this[methodName].apply(this, args);
if (!this.controlTaken_) {
this.reportOk_();
}
} catch (e) {
this.reportFailure_(e);
}
};
/**
* Wrap an async method with TestSuite.{takeControl(), releaseControl()}
* and invoke TestSuite.reportOk_ upon completion.
* @param {Array<string>} args method name followed by its parameters.
*/
TestSuite.prototype.waitForAsync = function(var_args) {
const args = Array.prototype.slice.call(arguments);
this.takeControl();
args.push(this.releaseControl.bind(this));
this.dispatchOnTestSuite(args);
};
/**
* Overrides the method with specified name until it's called first time.
* @param {!Object} receiver An object whose method to override.
* @param {string} methodName Name of the method to override.
* @param {!Function} override A function that should be called right after the
* overridden method returns.
* @param {?boolean} opt_sticky Whether restore original method after first run
* or not.
*/
TestSuite.prototype.addSniffer = function(receiver, methodName, override, opt_sticky) {
const orig = receiver[methodName];
if (typeof orig !== 'function') {
this.fail('Cannot find method to override: ' + methodName);
}
const test = this;
receiver[methodName] = function(var_args) {
let result;
try {
result = orig.apply(this, arguments);
} finally {
if (!opt_sticky) {
receiver[methodName] = orig;
}
}
// In case of exception the override won't be called.
try {
override.apply(this, arguments);
} catch (e) {
test.fail('Exception in overriden method \'' + methodName + '\': ' + e);
}
return result;
};
};
/**
* Waits for current throttler invocations, if any.
* @param {!Common.Throttler} throttler
* @param {function()} callback
*/
TestSuite.prototype.waitForThrottler = function(throttler, callback) {
const test = this;
let scheduleShouldFail = true;
test.addSniffer(throttler, 'schedule', onSchedule);
function hasSomethingScheduled() {
return throttler._isRunningProcess || throttler._process;
}
function checkState() {
if (!hasSomethingScheduled()) {
scheduleShouldFail = false;
callback();
return;
}
test.addSniffer(throttler, 'processCompletedForTests', checkState);
}
function onSchedule() {
if (scheduleShouldFail) {
test.fail('Unexpected Throttler.schedule');
}
}
checkState();
};
/**
* @param {string} panelName Name of the panel to show.
*/
TestSuite.prototype.showPanel = function(panelName) {
return self.UI.inspectorView.showPanel(panelName);
};
// UI Tests
/**
* Tests that scripts tab can be open and populated with inspected scripts.
*/
TestSuite.prototype.testShowScriptsTab = function() {
const test = this;
this.showPanel('sources').then(function() {
// There should be at least main page script.
this._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() {
test.releaseControl();
});
}.bind(this));
// Wait until all scripts are added to the debugger.
this.takeControl();
};
/**
* Tests that scripts list contains content scripts.
*/
TestSuite.prototype.testContentScriptIsPresent = function() {
const test = this;
this.showPanel('sources').then(function() {
test._waitUntilScriptsAreParsed(['page_with_content_script.html', 'simple_content_script.js'], function() {
test.releaseControl();
});
});
// Wait until all scripts are added to the debugger.
this.takeControl();
};
/**
* Tests that scripts are not duplicaed on Scripts tab switch.
*/
TestSuite.prototype.testNoScriptDuplicatesOnPanelSwitch = function() {
const test = this;
function switchToElementsTab() {
test.showPanel('elements').then(function() {
setTimeout(switchToScriptsTab, 0);
});
}
function switchToScriptsTab() {
test.showPanel('sources').then(function() {
setTimeout(checkScriptsPanel, 0);
});
}
function checkScriptsPanel() {
test.assertTrue(test._scriptsAreParsed(['debugger_test_page.html']), 'Some scripts are missing.');
checkNoDuplicates();
test.releaseControl();
}
function checkNoDuplicates() {
const uiSourceCodes = test.nonAnonymousUISourceCodes_();
for (let i = 0; i < uiSourceCodes.length; i++) {
for (let j = i + 1; j < uiSourceCodes.length; j++) {
test.assertTrue(
uiSourceCodes[i].url() !== uiSourceCodes[j].url(),
'Found script duplicates: ' + test.uiSourceCodesToString_(uiSourceCodes));
}
}
}
this.showPanel('sources').then(function() {
test._waitUntilScriptsAreParsed(['debugger_test_page.html'], function() {
checkNoDuplicates();
setTimeout(switchToElementsTab, 0);
});
});
// Wait until all scripts are added to the debugger.
this.takeControl({slownessFactor: 10});
};
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
TestSuite.prototype.testPauseWhenLoadingDevTools = function() {
const debuggerModel = self.SDK.targetManager.mainTarget().model(SDK.DebuggerModel);
if (debuggerModel.debuggerPausedDetails) {
return;
}
this.showPanel('sources').then(function() {
// Script execution can already be paused.
this._waitForScriptPause(this.releaseControl.bind(this));
}.bind(this));
this.takeControl();
};
/**
* Tests network size.
*/
TestSuite.prototype.testNetworkSize = function() {
const test = this;
function finishRequest(request, finishTime) {
test.assertEquals(25, request.resourceSize, 'Incorrect total data length');
test.releaseControl();
}
this.addSniffer(SDK.NetworkDispatcher.prototype, 'finishNetworkRequest', finishRequest);
// Reload inspected page to sniff network events
test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
this.takeControl({slownessFactor: 10});
};
/**
* Tests network sync size.
*/
TestSuite.prototype.testNetworkSyncSize = function() {
const test = this;
function finishRequest(request, finishTime) {
test.assertEquals(25, request.resourceSize, 'Incorrect total data length');
test.releaseControl();
}
this.addSniffer(SDK.NetworkDispatcher.prototype, 'finishNetworkRequest', finishRequest);
// Send synchronous XHR to sniff network events
test.evaluateInConsole_(
'let xhr = new XMLHttpRequest(); xhr.open("GET", "chunked", false); xhr.send(null);', function() {});
this.takeControl({slownessFactor: 10});
};
/**
* Tests network raw headers text.
*/
TestSuite.prototype.testNetworkRawHeadersText = function() {
const test = this;
function finishRequest(request, finishTime) {
if (!request.responseHeadersText) {
test.fail('Failure: resource does not have response headers text');
}
const index = request.responseHeadersText.indexOf('Date:');
test.assertEquals(
112, request.responseHeadersText.substring(index).length, 'Incorrect response headers text length');
test.releaseControl();
}
this.addSniffer(SDK.NetworkDispatcher.prototype, 'finishNetworkRequest', finishRequest);
// Reload inspected page to sniff network events
test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
this.takeControl({slownessFactor: 10});
};
/**
* Tests network timing.
*/
TestSuite.prototype.testNetworkTiming = function() {
const test = this;
function finishRequest(request, finishTime) {
// Setting relaxed expectations to reduce flakiness.
// Server sends headers after 100ms, then sends data during another 100ms.
// We expect these times to be measured at least as 70ms.
test.assertTrue(
request.timing.receiveHeadersEnd - request.timing.connectStart >= 70,
'Time between receiveHeadersEnd and connectStart should be >=70ms, but was ' +
'receiveHeadersEnd=' + request.timing.receiveHeadersEnd + ', connectStart=' +
request.timing.connectStart + '.');
test.assertTrue(
request.responseReceivedTime - request.startTime >= 0.07,
'Time between responseReceivedTime and startTime should be >=0.07s, but was ' +
'responseReceivedTime=' + request.responseReceivedTime + ', startTime=' + request.startTime + '.');
test.assertTrue(
request.endTime - request.startTime >= 0.14,
'Time between endTime and startTime should be >=0.14s, but was ' +
'endtime=' + request.endTime + ', startTime=' + request.startTime + '.');
test.releaseControl();
}
this.addSniffer(SDK.NetworkDispatcher.prototype, 'finishNetworkRequest', finishRequest);
// Reload inspected page to sniff network events
test.evaluateInConsole_('window.location.reload(true);', function(resultText) {});
this.takeControl({slownessFactor: 10});
};
TestSuite.prototype.testPushTimes = function(url) {
const test = this;
let pendingRequestCount = 2;
function finishRequest(request, finishTime) {
test.assertTrue(
typeof request.timing.pushStart === 'number' && request.timing.pushStart > 0,
`pushStart is invalid: ${request.timing.pushStart}`);
test.assertTrue(typeof request.timing.pushEnd === 'number', `pushEnd is invalid: ${request.timing.pushEnd}`);
test.assertTrue(request.timing.pushStart < request.startTime, 'pushStart should be before startTime');
if (request.url().endsWith('?pushUseNullEndTime')) {
test.assertTrue(request.timing.pushEnd === 0, `pushEnd should be 0 but is ${request.timing.pushEnd}`);
} else {
test.assertTrue(
request.timing.pushStart < request.timing.pushEnd,
`pushStart should be before pushEnd (${request.timing.pushStart} >= ${request.timing.pushEnd})`);
// The below assertion is just due to the way we generate times in the moch URLRequestJob and is not generally an invariant.
test.assertTrue(request.timing.pushEnd < request.endTime, 'pushEnd should be before endTime');
test.assertTrue(request.startTime < request.timing.pushEnd, 'pushEnd should be after startTime');
}
if (!--pendingRequestCount) {
test.releaseControl();
}
}
this.addSniffer(SDK.NetworkDispatcher.prototype, 'finishNetworkRequest', finishRequest, true);
test.evaluateInConsole_('addImage(\'' + url + '\')', function(resultText) {});
test.evaluateInConsole_('addImage(\'' + url + '?pushUseNullEndTime\')', function(resultText) {});
this.takeControl();
};
TestSuite.prototype.testConsoleOnNavigateBack = function() {
function filteredMessages() {
return self.SDK.consoleModel.messages().filter(a => a.source !== Protocol.Log.LogEntrySource.Violation);
}
if (filteredMessages().length === 1) {
firstConsoleMessageReceived.call(this, null);
} else {
self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this);
}
function firstConsoleMessageReceived(event) {
if (event && event.data.source === Protocol.Log.LogEntrySource.Violation) {
return;
}
self.SDK.consoleModel.removeEventListener(
SDK.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this);
this.evaluateInConsole_('clickLink();', didClickLink.bind(this));
}
function didClickLink() {
// Check that there are no new messages(command is not a message).
this.assertEquals(3, filteredMessages().length);
this.evaluateInConsole_('history.back();', didNavigateBack.bind(this));
}
function didNavigateBack() {
// Make sure navigation completed and possible console messages were pushed.
this.evaluateInConsole_('void 0;', didCompleteNavigation.bind(this));
}
function didCompleteNavigation() {
this.assertEquals(7, filteredMessages().length);
this.releaseControl();
}
this.takeControl();
};
TestSuite.prototype.testSharedWorker = function() {
function didEvaluateInConsole(resultText) {
this.assertEquals('2011', resultText);
this.releaseControl();
}
this.evaluateInConsole_('globalVar', didEvaluateInConsole.bind(this));
this.takeControl();
};
TestSuite.prototype.testPauseInSharedWorkerInitialization1 = function() {
// Make sure the worker is loaded.
this.takeControl();
this._waitForTargets(1, callback.bind(this));
function callback() {
ProtocolClient.test.deprecatedRunAfterPendingDispatches(this.releaseControl.bind(this));
}
};
TestSuite.prototype.testPauseInSharedWorkerInitialization2 = function() {
this.takeControl();
this._waitForTargets(1, callback.bind(this));
function callback() {
const debuggerModel = self.SDK.targetManager.models(SDK.DebuggerModel)[0];
if (debuggerModel.isPaused()) {
self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
debuggerModel.resume();
return;
}
this._waitForScriptPause(callback.bind(this));
}
function onConsoleMessage(event) {
const message = event.data.messageText;
if (message !== 'connected') {
this.fail('Unexpected message: ' + message);
}
this.releaseControl();
}
};
TestSuite.prototype.testSharedWorkerNetworkPanel = function() {
this.takeControl();
this.showPanel('network').then(() => {
if (!document.querySelector('#network-container')) {
this.fail('unable to find #network-container');
}
this.releaseControl();
});
};
TestSuite.prototype.enableTouchEmulation = function() {
const deviceModeModel = new Emulation.DeviceModeModel(function() {});
deviceModeModel._target = self.SDK.targetManager.mainTarget();
deviceModeModel._applyTouch(true, true);
};
TestSuite.prototype.waitForDebuggerPaused = function() {
const debuggerModel = self.SDK.targetManager.mainTarget().model(SDK.DebuggerModel);
if (debuggerModel.debuggerPausedDetails) {
return;
}
this.takeControl();
this._waitForScriptPause(this.releaseControl.bind(this));
};
TestSuite.prototype.switchToPanel = function(panelName) {
this.showPanel(panelName).then(this.releaseControl.bind(this));
this.takeControl();
};
// Regression test for crbug.com/370035.
TestSuite.prototype.testDeviceMetricsOverrides = function() {
function dumpPageMetrics() {
return JSON.stringify(
{width: window.innerWidth, height: window.innerHeight, deviceScaleFactor: window.devicePixelRatio});
}
const test = this;
async function testOverrides(params, metrics, callback) {
await self.SDK.targetManager.mainTarget().emulationAgent().invoke_setDeviceMetricsOverride(params);
test.evaluateInConsole_('(' + dumpPageMetrics.toString() + ')()', checkMetrics);
function checkMetrics(consoleResult) {
test.assertEquals(
`'${JSON.stringify(metrics)}'`, consoleResult, 'Wrong metrics for params: ' + JSON.stringify(params));
callback();
}
}
function step1() {
testOverrides(
{width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: true},
{width: 1200, height: 1000, deviceScaleFactor: 1}, step2);
}
function step2() {
testOverrides(
{width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: false},
{width: 1200, height: 1000, deviceScaleFactor: 1}, step3);
}
function step3() {
testOverrides(
{width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: true},
{width: 1200, height: 1000, deviceScaleFactor: 3}, step4);
}
function step4() {
testOverrides(
{width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: false},
{width: 1200, height: 1000, deviceScaleFactor: 3}, finish);
}
function finish() {
test.releaseControl();
}
test.takeControl();
step1();
};
TestSuite.prototype.testDispatchKeyEventShowsAutoFill = function() {
const test = this;
let receivedReady = false;
function signalToShowAutofill() {
self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
{type: 'rawKeyDown', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
{type: 'keyUp', key: 'Down', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40});
}
function selectTopAutoFill() {
self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
{type: 'rawKeyDown', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
{type: 'keyUp', key: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
test.evaluateInConsole_('document.getElementById("name").value', onResultOfInput);
}
function onResultOfInput(value) {
// Console adds '' around the response.
test.assertEquals('\'Abbf\'', value);
test.releaseControl();
}
function onConsoleMessage(event) {
const message = event.data.messageText;
if (message === 'ready' && !receivedReady) {
receivedReady = true;
signalToShowAutofill();
}
// This log comes from the browser unittest code.
if (message === 'didShowSuggestions') {
selectTopAutoFill();
}
}
this.takeControl({slownessFactor: 10});
// It is possible for the ready console messagage to be already received but not handled
// or received later. This ensures we can catch both cases.
self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
const messages = self.SDK.consoleModel.messages();
if (messages.length) {
const text = messages[0].messageText;
this.assertEquals('ready', text);
signalToShowAutofill();
}
};
TestSuite.prototype.testKeyEventUnhandled = function() {
function onKeyEventUnhandledKeyDown(event) {
this.assertEquals('keydown', event.data.type);
this.assertEquals('F8', event.data.key);
this.assertEquals(119, event.data.keyCode);
this.assertEquals(0, event.data.modifiers);
this.assertEquals('', event.data.code);
Host.InspectorFrontendHost.events.removeEventListener(
Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyDown, this);
Host.InspectorFrontendHost.events.addEventListener(
Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyUp, this);
self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
{type: 'keyUp', key: 'F8', code: 'F8', windowsVirtualKeyCode: 119, nativeVirtualKeyCode: 119});
}
function onKeyEventUnhandledKeyUp(event) {
this.assertEquals('keyup', event.data.type);
this.assertEquals('F8', event.data.key);
this.assertEquals(119, event.data.keyCode);
this.assertEquals(0, event.data.modifiers);
this.assertEquals('F8', event.data.code);
this.releaseControl();
}
this.takeControl();
Host.InspectorFrontendHost.events.addEventListener(
Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, onKeyEventUnhandledKeyDown, this);
self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
{type: 'rawKeyDown', key: 'F8', windowsVirtualKeyCode: 119, nativeVirtualKeyCode: 119});
};
// Tests that the keys that are forwarded from the browser update
// when their shortcuts change
TestSuite.prototype.testForwardedKeysChanged = function() {
this.takeControl();
this.addSniffer(self.UI.shortcutRegistry, 'registerBindings', () => {
self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
{type: 'rawKeyDown', key: 'F1', windowsVirtualKeyCode: 112, nativeVirtualKeyCode: 112});
});
this.addSniffer(self.UI.shortcutRegistry, 'handleKey', key => {
this.assertEquals(112, key);
this.releaseControl();
});
self.Common.settings.moduleSetting('activeKeybindSet').set('vsCode');
};
TestSuite.prototype.testDispatchKeyEventDoesNotCrash = function() {
self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
{type: 'rawKeyDown', windowsVirtualKeyCode: 0x23, key: 'End'});
self.SDK.targetManager.mainTarget().inputAgent().invoke_dispatchKeyEvent(
{type: 'keyUp', windowsVirtualKeyCode: 0x23, key: 'End'});
};
// Check that showing the certificate viewer does not crash, crbug.com/954874
TestSuite.prototype.testShowCertificate = function() {
Host.InspectorFrontendHost.showCertificateViewer([
'MIIFIDCCBAigAwIBAgIQE0TsEu6R8FUHQv+9fE7j8TANBgkqhkiG9w0BAQsF' +
'ADBUMQswCQYDVQQGEwJVUzEeMBwGA1UEChMVR29vZ2xlIFRydXN0IFNlcnZp' +
'Y2VzMSUwIwYDVQQDExxHb29nbGUgSW50ZXJuZXQgQXV0aG9yaXR5IEczMB4X' +
'DTE5MDMyNjEzNDEwMVoXDTE5MDYxODEzMjQwMFowZzELMAkGA1UEBhMCVVMx' +
'EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcx' +
'EzARBgNVBAoMCkdvb2dsZSBMTEMxFjAUBgNVBAMMDSouYXBwc3BvdC5jb20w' +
'ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCwca7hj0kyoJVxcvyA' +
'a8zNKMIXcoPM3aU1KVe7mxZITtwC6/D/D/q4Oe8fBQLeZ3c6qR5Sr3M+611k' +
'Ab15AcGUgh1Xi0jZqERvd/5+P0aVCFJYeoLrPBzwSMZBStkoiO2CwtV8x06e' +
'X7qUz7Hvr3oeG+Ma9OUMmIebl//zHtC82mE0mCRBQAW0MWEgT5nOWey74tJR' +
'GRqUEI8ftV9grAshD5gY8kxxUoMfqrreaXVqcRF58ZPiwUJ0+SbtC5q9cJ+K' +
'MuYM4TCetEuk/WQsa+1EnSa40dhGRtZjxbwEwQAJ1vLOc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eXSpkqBy+0Hne/ig+1' +
'AnwblrjFuTosvNYSuetZfeLQBoZfXklqtTleiDTsvHgMCJiEbKjNS7SgfQx5' +
'TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzdC9XZzPnqJworc5HGnRusyMvo' +
'4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pazq+r1feqCapgvdzZX99y' +
'qWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCBmTAOBgNVHQ8BAf8E' +
'BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IHV2ccHsBqBt5Z' +
'tJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5nbG9iYWxz' +
'aWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG3lm0' +
'mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4Gs' +
'J0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4' +
'h4hO291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRD' +
'LenVOavSot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG7' +
'9G+dwfCMNYxdAfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmg' +
'QWpzU/qlULRuJQ/7TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq' +
'/H5COEBkEveegeGTLg=='
]);
};
// Simple check to make sure network throttling is wired up
// See crbug.com/747724
TestSuite.prototype.testOfflineNetworkConditions = async function() {
const test = this;
self.SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions);
function finishRequest(request) {
test.assertEquals(
'net::ERR_INTERNET_DISCONNECTED', request.localizedFailDescription, 'Request should have failed');
test.releaseControl();
}
this.addSniffer(SDK.NetworkDispatcher.prototype, 'finishNetworkRequest', finishRequest);
test.takeControl();
test.evaluateInConsole_('await fetch("/");', function(resultText) {});
};
TestSuite.prototype.testEmulateNetworkConditions = function() {
const test = this;
function testPreset(preset, messages, next) {
function onConsoleMessage(event) {
const index = messages.indexOf(event.data.messageText);
if (index === -1) {
test.fail('Unexpected message: ' + event.data.messageText);
return;
}
messages.splice(index, 1);
if (!messages.length) {
self.SDK.consoleModel.removeEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
next();
}
}
self.SDK.consoleModel.addEventListener(SDK.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
self.SDK.multitargetNetworkManager.setNetworkConditions(preset);
}
test.takeControl();
step1();
function step1() {
testPreset(
MobileThrottling.networkPresets[2],
[
'offline event: online = false', 'connection change event: type = none; downlinkMax = 0; effectiveType = 4g'
],
step2);
}
function step2() {
testPreset(
MobileThrottling.networkPresets[1],
[
'online event: online = true',
'connection change event: type = cellular; downlinkMax = 0.3814697265625; effectiveType = 2g'
],
step3);
}
function step3() {
testPreset(
MobileThrottling.networkPresets[0],
['connection change event: type = cellular; downlinkMax = 1.373291015625; effectiveType = 3g'],
test.releaseControl.bind(test));
}
};
TestSuite.prototype.testScreenshotRecording = function() {
const test = this;
function performActionsInPage(callback) {
let count = 0;
const div = document.createElement('div');
div.setAttribute('style', 'left: 0px; top: 0px; width: 100px; height: 100px; position: absolute;');
document.body.appendChild(div);
requestAnimationFrame(frame);
function frame() {
const color = [0, 0, 0];
color[count % 3] = 255;
div.style.backgroundColor = 'rgb(' + color.join(',') + ')';
if (++count > 10) {
requestAnimationFrame(callback);
} else {
requestAnimationFrame(frame);
}
}
}
const captureFilmStripSetting = self.Common.settings.createSetting('timelineCaptureFilmStrip', false);
captureFilmStripSetting.set(true);
test.evaluateInConsole_(performActionsInPage.toString(), function() {});
test.invokeAsyncWithTimeline_('performActionsInPage', onTimelineDone);
function onTimelineDone() {
captureFilmStripSetting.set(false);
const filmStripModel = UI.panels.timeline._performanceModel.filmStripModel();
const frames = filmStripModel.frames();
test.assertTrue(frames.length > 4 && typeof frames.length === 'number');
loadFrameImages(frames);
}
function loadFrameImages(frames) {
const readyImages = [];
for (const frame of frames) {
frame.imageDataPromise().then(onGotImageData);
}
function onGotImageData(data) {
const image = new Image();
test.assertTrue(Boolean(data), 'No image data for frame');
image.addEventListener('load', onLoad);
image.src = 'data:image/jpg;base64,' + data;
}
function onLoad(event) {
readyImages.push(event.target);
if (readyImages.length === frames.length) {
validateImagesAndCompleteTest(readyImages);
}
}
}
function validateImagesAndCompleteTest(images) {
let redCount = 0;
let greenCount = 0;
let blueCount = 0;
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
for (const image of images) {
test.assertTrue(image.naturalWidth > 10);
test.assertTrue(image.naturalHeight > 10);
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
ctx.drawImage(image, 0, 0);
const data = ctx.getImageData(0, 0, 1, 1);
const color = Array.prototype.join.call(data.data, ',');
if (data.data[0] > 200) {
redCount++;
} else if (data.data[1] > 200) {
greenCount++;
} else if (data.data[2] > 200) {
blueCount++;
} else {
test.fail('Unexpected color: ' + color);
}
}
test.assertTrue(redCount && greenCount && blueCount, 'Color check failed');
test.releaseControl();
}
test.takeControl();
};
TestSuite.prototype.testSettings = function() {
const test = this;
createSettings();
test.takeControl();