-
Notifications
You must be signed in to change notification settings - Fork 54
/
reftest.jsm
1865 lines (1654 loc) · 65.2 KB
/
reftest.jsm
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
/* -*- indent-tabs-mode: nil; js-indent-level: 4 -*- /
/* vim: set shiftwidth=4 tabstop=8 autoindent cindent expandtab: */
/* 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/. */
"use strict";
var EXPORTED_SYMBOLS = [
"OnRefTestLoad",
"OnRefTestUnload",
"getTestPlugin"
];
Cu.import("resource://gre/modules/FileUtils.jsm");
Cu.import("resource://reftest/globals.jsm", this);
Cu.import("resource://reftest/httpd.jsm", this);
Cu.import("resource://reftest/manifest.jsm", this);
Cu.import("resource://reftest/StructuredLog.jsm", this);
Cu.import("resource://reftest/PerTestCoverageUtils.jsm", this);
Cu.import("resource://gre/modules/Services.jsm");
Cu.import('resource://gre/modules/XPCOMUtils.jsm');
const { E10SUtils } = ChromeUtils.import(
"resource://gre/modules/E10SUtils.jsm"
);
XPCOMUtils.defineLazyGetter(this, "OS", function() {
const { OS } = Cu.import("resource://gre/modules/osfile.jsm");
return OS;
});
XPCOMUtils.defineLazyGetter(this, "PDFJS", function() {
const { require } = Cu.import("resource://gre/modules/commonjs/toolkit/require.js", {});
return {
main: require('resource://pdf.js/build/pdf.js'),
worker: require('resource://pdf.js/build/pdf.worker.js')
};
});
function HasUnexpectedResult()
{
return g.testResults.Exception > 0 ||
g.testResults.FailedLoad > 0 ||
g.testResults.UnexpectedFail > 0 ||
g.testResults.UnexpectedPass > 0 ||
g.testResults.AssertionUnexpected > 0 ||
g.testResults.AssertionUnexpectedFixed > 0;
}
// By default we just log to stdout
var gDumpFn = function(line) {
dump(line);
if (g.logFile) {
g.logFile.writeString(line);
}
}
var gDumpRawLog = function(record) {
// Dump JSON representation of data on a single line
var line = "\n" + JSON.stringify(record) + "\n";
dump(line);
if (g.logFile) {
g.logFile.writeString(line);
}
}
g.logger = new StructuredLogger('reftest', gDumpRawLog);
var logger = g.logger;
function TestBuffer(str)
{
logger.debug(str);
g.testLog.push(str);
}
function isWebRenderOnAndroidDevice() {
var xr = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime);
// This is the best we can do for now; maybe in the future we'll have
// more correct detection of this case.
return xr.OS == "Android" &&
g.browserIsRemote &&
g.windowUtils.layerManagerType == "WebRender";
}
function FlushTestBuffer()
{
// In debug mode, we've dumped all these messages already.
if (g.logLevel !== 'debug') {
for (var i = 0; i < g.testLog.length; ++i) {
logger.info("Saved log: " + g.testLog[i]);
}
}
g.testLog = [];
}
function LogWidgetLayersFailure()
{
logger.error(
"Screen resolution is too low - USE_WIDGET_LAYERS was disabled. " +
(g.browserIsRemote ?
"Since E10s is enabled, there is no fallback rendering path!" :
"The fallback rendering path is not reliably consistent with on-screen rendering."));
logger.error(
"If you cannot increase your screen resolution you can try reducing " +
"gecko's pixel scaling by adding something like '--setpref " +
"layout.css.devPixelsPerPx=1.0' to your './mach reftest' command " +
"(possibly as an alias in ~/.mozbuild/machrc). Note that this is " +
"inconsistent with CI testing, and may interfere with HighDPI/" +
"reftest-zoom tests.");
}
function AllocateCanvas()
{
if (g.recycledCanvases.length > 0) {
return g.recycledCanvases.shift();
}
var canvas = g.containingWindow.document.createElementNS(XHTML_NS, "canvas");
var r = g.browser.getBoundingClientRect();
canvas.setAttribute("width", Math.ceil(r.width));
canvas.setAttribute("height", Math.ceil(r.height));
return canvas;
}
function ReleaseCanvas(canvas)
{
// store a maximum of 2 canvases, if we're not caching
if (!g.noCanvasCache || g.recycledCanvases.length < 2) {
g.recycledCanvases.push(canvas);
}
}
function IDForEventTarget(event)
{
try {
return "'" + event.target.getAttribute('id') + "'";
} catch (ex) {
return "<unknown>";
}
}
function getTestPlugin(aName) {
var ph = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost);
var tags = ph.getPluginTags();
// Find the test plugin
for (var i = 0; i < tags.length; i++) {
if (tags[i].name == aName)
return tags[i];
}
logger.warning("Failed to find the test-plugin.");
return null;
}
function OnRefTestLoad(win)
{
g.crashDumpDir = Cc[NS_DIRECTORY_SERVICE_CONTRACTID]
.getService(Ci.nsIProperties)
.get("ProfD", Ci.nsIFile);
g.crashDumpDir.append("minidumps");
g.pendingCrashDumpDir = Cc[NS_DIRECTORY_SERVICE_CONTRACTID]
.getService(Ci.nsIProperties)
.get("UAppData", Ci.nsIFile);
g.pendingCrashDumpDir.append("Crash Reports");
g.pendingCrashDumpDir.append("pending");
var env = Cc["@mozilla.org/process/environment;1"].
getService(Ci.nsIEnvironment);
var prefs = Cc["@mozilla.org/preferences-service;1"].
getService(Ci.nsIPrefBranch);
g.browserIsRemote = prefs.getBoolPref("browser.tabs.remote.autostart", false);
g.browserIsFission = prefs.getBoolPref("fission.autostart", false);
g.browserIsIframe = prefs.getBoolPref("reftest.browser.iframe.enabled", false);
g.logLevel = prefs.getStringPref("reftest.logLevel", "info");
if (win === undefined || win == null) {
win = window;
}
if (g.containingWindow == null && win != null) {
g.containingWindow = win;
}
if (g.browserIsIframe) {
g.browser = g.containingWindow.document.createElementNS(XHTML_NS, "iframe");
g.browser.setAttribute("mozbrowser", "");
} else {
g.browser = g.containingWindow.document.createElementNS(XUL_NS, "xul:browser");
}
g.browser.setAttribute("id", "browser");
g.browser.setAttribute("type", "content");
g.browser.setAttribute("primary", "true");
g.browser.setAttribute("remote", g.browserIsRemote ? "true" : "false");
// Make sure the browser element is exactly 800x1000, no matter
// what size our window is
g.browser.setAttribute("style", "padding: 0px; margin: 0px; border:none; min-width: 800px; min-height: 1000px; max-width: 800px; max-height: 1000px");
if (Services.appinfo.OS == "Android") {
let doc = g.containingWindow.document.getElementById('main-window');
while (doc.hasChildNodes()) {
doc.firstChild.remove();
}
doc.appendChild(g.browser);
// TODO Bug 1156817: reftests don't have most of GeckoView infra so we
// can't register this actor
ChromeUtils.unregisterWindowActor("LoadURIDelegate");
ChromeUtils.unregisterWindowActor("WebBrowserChrome");
} else {
document.getElementById("reftest-window").appendChild(g.browser);
}
// reftests should have the test plugins enabled, not click-to-play
let plugin1 = getTestPlugin("Test Plug-in");
let plugin2 = getTestPlugin("Second Test Plug-in");
if (plugin1 && plugin2) {
g.testPluginEnabledStates = [plugin1.enabledState, plugin2.enabledState];
plugin1.enabledState = Ci.nsIPluginTag.STATE_ENABLED;
plugin2.enabledState = Ci.nsIPluginTag.STATE_ENABLED;
} else {
logger.warning("Could not get test plugin tags.");
}
g.browserMessageManager = g.browser.frameLoader.messageManager;
// The content script waits for the initial onload, then notifies
// us.
RegisterMessageListenersAndLoadContentScript(false);
}
function InitAndStartRefTests()
{
/* These prefs are optional, so we don't need to spit an error to the log */
try {
var prefs = Cc["@mozilla.org/preferences-service;1"].
getService(Ci.nsIPrefBranch);
} catch(e) {
logger.error("EXCEPTION: " + e);
}
try {
prefs.setBoolPref("android.widget_paints_background", false);
} catch (e) {}
// If fission is enabled, then also put data: URIs in the default web process,
// since most reftests run in the file process, and this will make data:
// <iframe>s OOP.
if (g.browserIsFission) {
prefs.setBoolPref("browser.tabs.remote.dataUriInDefaultWebProcess", true);
}
/* set the g.loadTimeout */
try {
g.loadTimeout = prefs.getIntPref("reftest.timeout");
} catch(e) {
g.loadTimeout = 5 * 60 * 1000; //5 minutes as per bug 479518
}
/* Get the logfile for android tests */
try {
var logFile = prefs.getStringPref("reftest.logFile");
if (logFile) {
var f = FileUtils.File(logFile);
var out = FileUtils.openFileOutputStream(f, FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE);
g.logFile = Cc["@mozilla.org/intl/converter-output-stream;1"]
.createInstance(Ci.nsIConverterOutputStream);
g.logFile.init(out, null);
}
} catch(e) {}
g.remote = prefs.getBoolPref("reftest.remote", false);
g.ignoreWindowSize = prefs.getBoolPref("reftest.ignoreWindowSize", false);
/* Support for running a chunk (subset) of tests. In separate try as this is optional */
try {
g.totalChunks = prefs.getIntPref("reftest.totalChunks");
g.thisChunk = prefs.getIntPref("reftest.thisChunk");
}
catch(e) {
g.totalChunks = 0;
g.thisChunk = 0;
}
try {
g.focusFilterMode = prefs.getStringPref("reftest.focusFilterMode");
} catch(e) {}
try {
g.compareRetainedDisplayLists = prefs.getBoolPref("reftest.compareRetainedDisplayLists");
} catch (e) {}
#ifdef MOZ_ENABLE_SKIA_PDF
try {
// We have to disable printing via parent or else silent print operations
// (the type that we use here) would be treated as non-silent -- in other
// words, a print dialog would appear for each print operation, which
// would interrupt the test run.
// See http://searchfox.org/mozilla-central/rev/bd39b6170f04afeefc751a23bb04e18bbd10352b/layout/printing/nsPrintEngine.cpp#617
prefs.setBoolPref("print.print_via_parent", false);
} catch (e) {
/* uh oh, print reftests may not work... */
}
#endif
g.windowUtils = g.containingWindow.windowUtils;
if (!g.windowUtils || !g.windowUtils.compareCanvases)
throw "nsIDOMWindowUtils inteface missing";
g.ioService = Cc[IO_SERVICE_CONTRACTID].getService(Ci.nsIIOService);
g.debug = Cc[DEBUG_CONTRACTID].getService(Ci.nsIDebug2);
RegisterProcessCrashObservers();
if (g.remote) {
g.server = null;
} else {
g.server = new HttpServer();
}
try {
if (g.server)
StartHTTPServer();
} catch (ex) {
//g.browser.loadURI('data:text/plain,' + ex);
++g.testResults.Exception;
logger.error("EXCEPTION: " + ex);
DoneTests();
}
// Focus the content browser.
if (g.focusFilterMode != FOCUS_FILTER_NON_NEEDS_FOCUS_TESTS) {
var fm = Cc["@mozilla.org/focus-manager;1"].getService(Ci.nsIFocusManager);
if (fm.activeWindow != g.containingWindow) {
Focus();
}
g.browser.addEventListener("focus", ReadTests, true);
g.browser.focus();
} else {
ReadTests();
}
}
function StartHTTPServer()
{
g.server.registerContentType("sjs", "sjs");
g.server.start(-1);
g.httpServerPort = g.server.identity.primaryPort;
}
// Perform a Fisher-Yates shuffle of the array.
function Shuffle(array)
{
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
function ReadTests() {
try {
if (g.focusFilterMode != FOCUS_FILTER_NON_NEEDS_FOCUS_TESTS) {
g.browser.removeEventListener("focus", ReadTests, true);
}
g.urls = [];
var prefs = Cc["@mozilla.org/preferences-service;1"].
getService(Ci.nsIPrefBranch);
/* There are three modes implemented here:
* 1) reftest.manifests
* 2) reftest.manifests and reftest.manifests.dumpTests
* 3) reftest.tests
*
* The first will parse the specified manifests, then immediately
* run the tests. The second will parse the manifests, save the test
* objects to a file and exit. The third will load a file of test
* objects and run them.
*
* The latter two modes are used to pass test data back and forth
* with python harness.
*/
let manifests = prefs.getStringPref("reftest.manifests", null);
let dumpTests = prefs.getStringPref("reftest.manifests.dumpTests", null);
let testList = prefs.getStringPref("reftest.tests", null);
if ((testList && manifests) || !(testList || manifests)) {
logger.error("Exactly one of reftest.manifests or reftest.tests must be specified.");
logger.debug("reftest.manifests is: " + manifests);
logger.error("reftest.tests is: " + testList);
DoneTests();
}
if (testList) {
logger.debug("Reading test objects from: " + testList);
let promise = OS.File.read(testList).then(function onSuccess(array) {
let decoder = new TextDecoder();
g.urls = JSON.parse(decoder.decode(array)).map(CreateUrls);
StartTests();
}).catch(function onFailure(e) {
logger.error("Failed to load test objects: " + e);
DoneTests();
});
} else if (manifests) {
// Parse reftest manifests
logger.debug("Reading " + manifests.length + " manifests");
manifests = JSON.parse(manifests);
g.urlsFilterRegex = manifests[null];
var globalFilter = manifests.hasOwnProperty("") ? new RegExp(manifests[""]) : null;
delete manifests[""];
var manifestURLs = Object.keys(manifests);
// Ensure we read manifests from higher up the directory tree first so that we
// process includes before reading the included manifest again
manifestURLs.sort(function(a,b) {return a.length - b.length})
manifestURLs.forEach(function(manifestURL) {
logger.info("Reading manifest " + manifestURL);
var manifestInfo = manifests[manifestURL];
var filter = manifestInfo[0] ? new RegExp(manifestInfo[0]) : null;
var manifestID = manifestInfo[1];
ReadTopManifest(manifestURL, [globalFilter, filter, false], manifestID);
});
if (dumpTests) {
logger.debug("Dumping test objects to file: " + dumpTests);
let encoder = new TextEncoder();
let tests = encoder.encode(JSON.stringify(g.urls));
OS.File.writeAtomic(dumpTests, tests, {flush: true}).then(
function onSuccess() {
DoneTests();
},
function onFailure(reason) {
logger.error("failed to write test data: " + reason);
DoneTests();
}
)
} else {
logger.debug("Running " + g.urls.length + " test objects");
g.manageSuite = true;
g.urls = g.urls.map(CreateUrls);
StartTests();
}
}
} catch(e) {
++g.testResults.Exception;
logger.error("EXCEPTION: " + e);
DoneTests();
}
}
function StartTests()
{
/* These prefs are optional, so we don't need to spit an error to the log */
try {
var prefs = Cc["@mozilla.org/preferences-service;1"].
getService(Ci.nsIPrefBranch);
} catch(e) {
logger.error("EXCEPTION: " + e);
}
g.noCanvasCache = prefs.getIntPref("reftest.nocache", false);
g.shuffle = prefs.getBoolPref("reftest.shuffle", false);
g.runUntilFailure = prefs.getBoolPref("reftest.runUntilFailure", false);
g.verify = prefs.getBoolPref("reftest.verify", false);
g.cleanupPendingCrashes = prefs.getBoolPref("reftest.cleanupPendingCrashes", false);
// Check if there are any crash dump files from the startup procedure, before
// we start running the first test. Otherwise the first test might get
// blamed for producing a crash dump file when that was not the case.
CleanUpCrashDumpFiles();
// When we repeat this function is called again, so really only want to set
// g.repeat once.
if (g.repeat == null) {
g.repeat = prefs.getIntPref("reftest.repeat", 0);
}
g.runSlowTests = prefs.getIntPref("reftest.skipslowtests", false);
if (g.shuffle) {
g.noCanvasCache = true;
}
try {
BuildUseCounts();
// Filter tests which will be skipped to get a more even distribution when chunking
// tURLs is a temporary array containing all active tests
var tURLs = new Array();
for (var i = 0; i < g.urls.length; ++i) {
if (g.urls[i].expected == EXPECTED_DEATH)
continue;
if (g.urls[i].needsFocus && !Focus())
continue;
if (g.urls[i].slow && !g.runSlowTests)
continue;
tURLs.push(g.urls[i]);
}
var numActiveTests = tURLs.length;
if (g.totalChunks > 0 && g.thisChunk > 0) {
// Calculate start and end indices of this chunk if tURLs array were
// divided evenly
var testsPerChunk = tURLs.length / g.totalChunks;
var start = Math.round((g.thisChunk-1) * testsPerChunk);
var end = Math.round(g.thisChunk * testsPerChunk);
numActiveTests = end - start;
// Map these indices onto the g.urls array. This avoids modifying the
// g.urls array which prevents skipped tests from showing up in the log
start = g.thisChunk == 1 ? 0 : g.urls.indexOf(tURLs[start]);
end = g.thisChunk == g.totalChunks ? g.urls.length : g.urls.indexOf(tURLs[end + 1]) - 1;
logger.info("Running chunk " + g.thisChunk + " out of " + g.totalChunks + " chunks. " +
"tests " + (start+1) + "-" + end + "/" + g.urls.length);
g.urls = g.urls.slice(start, end);
}
if (g.manageSuite && !g.suiteStarted) {
var ids = {};
g.urls.forEach(function(test) {
if (!(test.manifestID in ids)) {
ids[test.manifestID] = [];
}
ids[test.manifestID].push(test.identifier);
});
var suite = prefs.getStringPref('reftest.suite', 'reftest');
logger.suiteStart(ids, suite, {"skipped": g.urls.length - numActiveTests});
g.suiteStarted = true
}
if (g.shuffle) {
Shuffle(g.urls);
}
g.totalTests = g.urls.length;
if (!g.totalTests && !g.verify && !g.repeat)
throw "No tests to run";
g.uriCanvases = {};
PerTestCoverageUtils.beforeTest()
.then(StartCurrentTest)
.catch(e => {
logger.error("EXCEPTION: " + e);
DoneTests();
});
} catch (ex) {
//g.browser.loadURI('data:text/plain,' + ex);
++g.testResults.Exception;
logger.error("EXCEPTION: " + ex);
DoneTests();
}
}
function OnRefTestUnload()
{
let plugin1 = getTestPlugin("Test Plug-in");
let plugin2 = getTestPlugin("Second Test Plug-in");
if (plugin1 && plugin2) {
plugin1.enabledState = g.testPluginEnabledStates[0];
plugin2.enabledState = g.testPluginEnabledStates[1];
} else {
logger.warning("Failed to get test plugin tags.");
}
}
function AddURIUseCount(uri)
{
if (uri == null)
return;
var spec = uri.spec;
if (spec in g.uriUseCounts) {
g.uriUseCounts[spec]++;
} else {
g.uriUseCounts[spec] = 1;
}
}
function BuildUseCounts()
{
if (g.noCanvasCache) {
return;
}
g.uriUseCounts = {};
for (var i = 0; i < g.urls.length; ++i) {
var url = g.urls[i];
if (url.expected != EXPECTED_DEATH &&
(url.type == TYPE_REFTEST_EQUAL ||
url.type == TYPE_REFTEST_NOTEQUAL)) {
if (url.prefSettings1.length == 0) {
AddURIUseCount(g.urls[i].url1);
}
if (url.prefSettings2.length == 0) {
AddURIUseCount(g.urls[i].url2);
}
}
}
}
// Return true iff this window is focused when this function returns.
function Focus()
{
var fm = Cc["@mozilla.org/focus-manager;1"].getService(Ci.nsIFocusManager);
fm.focusedWindow = g.containingWindow;
#ifdef XP_MACOSX
try {
var dock = Cc["@mozilla.org/widget/macdocksupport;1"].getService(Ci.nsIMacDockSupport);
dock.activateApplication(true);
} catch(ex) {
}
#endif // XP_MACOSX
return true;
}
function Blur()
{
// On non-remote reftests, this will transfer focus to the dummy window
// we created to hold focus for non-needs-focus tests. Buggy tests
// (ones which require focus but don't request needs-focus) will then
// fail.
g.containingWindow.blur();
}
function StartCurrentTest()
{
g.testLog = [];
// make sure we don't run tests that are expected to kill the browser
while (g.urls.length > 0) {
var test = g.urls[0];
logger.testStart(test.identifier);
if (test.expected == EXPECTED_DEATH) {
++g.testResults.Skip;
logger.testEnd(test.identifier, "SKIP");
g.urls.shift();
} else if (test.needsFocus && !Focus()) {
// FIXME: Marking this as a known fail is dangerous! What
// if it starts failing all the time?
++g.testResults.Skip;
logger.testEnd(test.identifier, "SKIP", null, "(COULDN'T GET FOCUS)");
g.urls.shift();
} else if (test.slow && !g.runSlowTests) {
++g.testResults.Slow;
logger.testEnd(test.identifier, "SKIP", null, "(SLOW)");
g.urls.shift();
} else {
break;
}
}
if ((g.urls.length == 0 && g.repeat == 0) ||
(g.runUntilFailure && HasUnexpectedResult())) {
RestoreChangedPreferences();
DoneTests();
} else if (g.urls.length == 0 && g.repeat > 0) {
// Repeat
g.repeat--;
ReadTests();
} else {
if (g.urls[0].chaosMode) {
g.windowUtils.enterChaosMode();
}
if (!g.urls[0].needsFocus) {
Blur();
}
var currentTest = g.totalTests - g.urls.length;
g.containingWindow.document.title = "reftest: " + currentTest + " / " + g.totalTests +
" (" + Math.floor(100 * (currentTest / g.totalTests)) + "%)";
StartCurrentURI(URL_TARGET_TYPE_TEST);
}
}
// A simplified version of the function with the same name in tabbrowser.js.
function updateBrowserRemotenessByURL(aBrowser, aURL) {
let remoteType = E10SUtils.getRemoteTypeForURI(
aURL,
aBrowser.ownerGlobal.docShell.nsILoadContext.useRemoteTabs,
aBrowser.ownerGlobal.docShell.nsILoadContext.useRemoteSubframes,
aBrowser.remoteType,
aBrowser.currentURI
);
// Things get confused if we switch to not-remote
// for chrome:// URIs, so lets not for now.
if (remoteType == E10SUtils.NOT_REMOTE &&
g.browserIsRemote) {
remoteType = aBrowser.remoteType;
}
if (aBrowser.remoteType != remoteType) {
if (remoteType == E10SUtils.NOT_REMOTE) {
aBrowser.removeAttribute("remote");
aBrowser.removeAttribute("remoteType");
} else {
aBrowser.setAttribute("remote", "true");
aBrowser.setAttribute("remoteType", remoteType);
}
aBrowser.changeRemoteness({ remoteType });
aBrowser.construct();
g.browserMessageManager = aBrowser.frameLoader.messageManager;
RegisterMessageListenersAndLoadContentScript(true);
return new Promise(resolve => { g.resolveContentReady = resolve; });
}
return Promise.resolve();
}
async function StartCurrentURI(aURLTargetType)
{
const isStartingRef = (aURLTargetType == URL_TARGET_TYPE_REFERENCE);
g.currentURL = g.urls[0][isStartingRef ? "url2" : "url1"].spec;
g.currentURLTargetType = aURLTargetType;
RestoreChangedPreferences();
var prefs = Cc["@mozilla.org/preferences-service;1"].
getService(Ci.nsIPrefBranch);
const prefSettings =
g.urls[0][isStartingRef ? "prefSettings2" : "prefSettings1"];
if (prefSettings.length > 0) {
var badPref = undefined;
try {
prefSettings.forEach(function(ps) {
var oldVal;
if (ps.type == PREF_BOOLEAN) {
try {
oldVal = prefs.getBoolPref(ps.name);
} catch (e) {
badPref = "boolean preference '" + ps.name + "'";
throw "bad pref";
}
} else if (ps.type == PREF_STRING) {
try {
oldVal = prefs.getStringPref(ps.name);
} catch (e) {
badPref = "string preference '" + ps.name + "'";
throw "bad pref";
}
} else if (ps.type == PREF_INTEGER) {
try {
oldVal = prefs.getIntPref(ps.name);
} catch (e) {
badPref = "integer preference '" + ps.name + "'";
throw "bad pref";
}
} else {
throw "internal error - unknown preference type";
}
if (oldVal != ps.value) {
g.prefsToRestore.push( { name: ps.name,
type: ps.type,
value: oldVal } );
var value = ps.value;
if (ps.type == PREF_BOOLEAN) {
prefs.setBoolPref(ps.name, value);
} else if (ps.type == PREF_STRING) {
prefs.setStringPref(ps.name, value);
value = '"' + value + '"';
} else if (ps.type == PREF_INTEGER) {
prefs.setIntPref(ps.name, value);
}
logger.info("SET PREFERENCE pref(" + ps.name + "," + value + ")");
}
});
} catch (e) {
if (e == "bad pref") {
var test = g.urls[0];
if (test.expected == EXPECTED_FAIL) {
logger.testEnd(test.identifier, "FAIL", "FAIL",
"(SKIPPED; " + badPref + " not known or wrong type)");
++g.testResults.Skip;
} else {
logger.testEnd(test.identifier, "FAIL", "PASS",
badPref + " not known or wrong type");
++g.testResults.UnexpectedFail;
}
// skip the test that had a bad preference
g.urls.shift();
StartCurrentTest();
return;
} else {
throw e;
}
}
}
if (prefSettings.length == 0 &&
g.uriCanvases[g.currentURL] &&
(g.urls[0].type == TYPE_REFTEST_EQUAL ||
g.urls[0].type == TYPE_REFTEST_NOTEQUAL) &&
g.urls[0].maxAsserts == 0) {
// Pretend the document loaded --- RecordResult will notice
// there's already a canvas for this URL
g.containingWindow.setTimeout(RecordResult, 0);
} else {
var currentTest = g.totalTests - g.urls.length;
// Log this to preserve the same overall log format,
// should be removed if the format is updated
gDumpFn("REFTEST TEST-LOAD | " + g.currentURL + " | " + currentTest + " / " + g.totalTests +
" (" + Math.floor(100 * (currentTest / g.totalTests)) + "%)\n");
TestBuffer("START " + g.currentURL);
await updateBrowserRemotenessByURL(g.browser, g.currentURL);
var type = g.urls[0].type
if (TYPE_SCRIPT == type) {
SendLoadScriptTest(g.currentURL, g.loadTimeout);
} else if (TYPE_PRINT == type) {
SendLoadPrintTest(g.currentURL, g.loadTimeout);
} else {
SendLoadTest(type, g.currentURL, g.currentURLTargetType, g.loadTimeout);
}
}
}
function DoneTests()
{
PerTestCoverageUtils.afterTest()
.catch(e => logger.error("EXCEPTION: " + e))
.then(() => {
if (g.manageSuite) {
g.suiteStarted = false
logger.suiteEnd({'results': g.testResults});
} else {
logger._logData('results', {results: g.testResults});
}
logger.info("Slowest test took " + g.slowestTestTime + "ms (" + g.slowestTestURL + ")");
logger.info("Total canvas count = " + g.recycledCanvases.length);
if (g.failedUseWidgetLayers) {
LogWidgetLayersFailure();
}
function onStopped() {
if (g.logFile) {
g.logFile.close();
g.logFile = null;
}
let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"].getService(Ci.nsIAppStartup);
appStartup.quit(Ci.nsIAppStartup.eForceQuit);
}
if (g.server) {
g.server.stop(onStopped);
}
else {
onStopped();
}
});
}
function UpdateCanvasCache(url, canvas)
{
var spec = url.spec;
--g.uriUseCounts[spec];
if (g.uriUseCounts[spec] == 0) {
ReleaseCanvas(canvas);
delete g.uriCanvases[spec];
} else if (g.uriUseCounts[spec] > 0) {
g.uriCanvases[spec] = canvas;
} else {
throw "Use counts were computed incorrectly";
}
}
// Recompute drawWindow flags for every drawWindow operation.
// We have to do this every time since our window can be
// asynchronously resized (e.g. by the window manager, to make
// it fit on screen) at unpredictable times.
// Fortunately this is pretty cheap.
function DoDrawWindow(ctx, x, y, w, h)
{
var flags = ctx.DRAWWINDOW_DRAW_CARET | ctx.DRAWWINDOW_DRAW_VIEW;
var testRect = g.browser.getBoundingClientRect();
if (g.ignoreWindowSize ||
(0 <= testRect.left &&
0 <= testRect.top &&
g.containingWindow.innerWidth >= testRect.right &&
g.containingWindow.innerHeight >= testRect.bottom)) {
// We can use the window's retained layer manager
// because the window is big enough to display the entire
// browser element
flags |= ctx.DRAWWINDOW_USE_WIDGET_LAYERS;
} else if (g.browserIsRemote) {
logger.error(g.currentURL + " | can't drawWindow remote content");
++g.testResults.Exception;
}
if (g.drawWindowFlags != flags) {
// Every time the flags change, dump the new state.
g.drawWindowFlags = flags;
var flagsStr = "DRAWWINDOW_DRAW_CARET | DRAWWINDOW_DRAW_VIEW";
if (flags & ctx.DRAWWINDOW_USE_WIDGET_LAYERS) {
flagsStr += " | DRAWWINDOW_USE_WIDGET_LAYERS";
} else {
// Output a special warning because we need to be able to detect
// this whenever it happens.
LogWidgetLayersFailure();
g.failedUseWidgetLayers = true;
}
logger.info("drawWindow flags = " + flagsStr +
"; window size = " + g.containingWindow.innerWidth + "," + g.containingWindow.innerHeight +
"; test browser size = " + testRect.width + "," + testRect.height);
}
TestBuffer("DoDrawWindow " + x + "," + y + "," + w + "," + h);
ctx.drawWindow(g.containingWindow, x, y, w, h, "rgb(255,255,255)",
g.drawWindowFlags);
}
function InitCurrentCanvasWithSnapshot()
{
TestBuffer("Initializing canvas snapshot");
if (g.urls[0].type == TYPE_LOAD || g.urls[0].type == TYPE_SCRIPT || g.urls[0].type == TYPE_PRINT) {
// We don't want to snapshot this kind of test
return false;
}
if (!g.currentCanvas) {
g.currentCanvas = AllocateCanvas();
}
var ctx = g.currentCanvas.getContext("2d");
DoDrawWindow(ctx, 0, 0, g.currentCanvas.width, g.currentCanvas.height);
return true;
}
function UpdateCurrentCanvasForInvalidation(rects)
{
TestBuffer("Updating canvas for invalidation");
if (!g.currentCanvas) {
return;
}
var ctx = g.currentCanvas.getContext("2d");
for (var i = 0; i < rects.length; ++i) {
var r = rects[i];
// Set left/top/right/bottom to pixel boundaries
var left = Math.floor(r.left);
var top = Math.floor(r.top);
var right = Math.ceil(r.right);
var bottom = Math.ceil(r.bottom);
// Clamp the values to the canvas size
left = Math.max(0, Math.min(left, g.currentCanvas.width));
top = Math.max(0, Math.min(top, g.currentCanvas.height));
right = Math.max(0, Math.min(right, g.currentCanvas.width));
bottom = Math.max(0, Math.min(bottom, g.currentCanvas.height));
ctx.save();
ctx.translate(left, top);
DoDrawWindow(ctx, left, top, right - left, bottom - top);
ctx.restore();
}
}
function UpdateWholeCurrentCanvasForInvalidation()
{
TestBuffer("Updating entire canvas for invalidation");
if (!g.currentCanvas) {
return;
}
var ctx = g.currentCanvas.getContext("2d");
DoDrawWindow(ctx, 0, 0, g.currentCanvas.width, g.currentCanvas.height);
}
function RecordResult(testRunTime, errorMsg, typeSpecificResults)
{
TestBuffer("RecordResult fired");
// Keep track of which test was slowest, and how long it took.
if (testRunTime > g.slowestTestTime) {
g.slowestTestTime = testRunTime;
g.slowestTestURL = g.currentURL;
}
// Not 'const ...' because of 'EXPECTED_*' value dependency.