This repository was archived by the owner on Jul 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathbrowser-test.js
More file actions
1599 lines (1446 loc) · 48.8 KB
/
Copy pathbrowser-test.js
File metadata and controls
1599 lines (1446 loc) · 48.8 KB
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
/* -*- js-indent-level: 2; tab-width: 2; indent-tabs-mode: nil -*- */
/* eslint-env mozilla/browser-window */
/* import-globals-from chrome-harness.js */
/* import-globals-from mochitest-e10s-utils.js */
// Test timeout (seconds)
var gTimeoutSeconds = 45;
var gConfig;
var { AppConstants } = ChromeUtils.import(
"resource://gre/modules/AppConstants.jsm"
);
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
ChromeUtils.defineModuleGetter(
this,
"AddonManager",
"resource://gre/modules/AddonManager.jsm"
);
const SIMPLETEST_OVERRIDES = [
"ok",
"record",
"is",
"isnot",
"todo",
"todo_is",
"todo_isnot",
"info",
"expectAssertions",
"requestCompleteLog",
];
setTimeout(testInit, 0);
var TabDestroyObserver = {
outstanding: new Set(),
promiseResolver: null,
init() {
Services.obs.addObserver(this, "message-manager-close");
Services.obs.addObserver(this, "message-manager-disconnect");
},
destroy() {
Services.obs.removeObserver(this, "message-manager-close");
Services.obs.removeObserver(this, "message-manager-disconnect");
},
observe(subject, topic, data) {
if (topic == "message-manager-close") {
this.outstanding.add(subject);
} else if (topic == "message-manager-disconnect") {
this.outstanding.delete(subject);
if (!this.outstanding.size && this.promiseResolver) {
this.promiseResolver();
}
}
},
wait() {
if (!this.outstanding.size) {
return Promise.resolve();
}
return new Promise(resolve => {
this.promiseResolver = resolve;
});
},
};
function testInit() {
gConfig = readConfig();
if (gConfig.testRoot == "browser") {
// Make sure to launch the test harness for the first opened window only
var prefs = Services.prefs;
if (prefs.prefHasUserValue("testing.browserTestHarness.running")) {
return;
}
prefs.setBoolPref("testing.browserTestHarness.running", true);
if (prefs.prefHasUserValue("testing.browserTestHarness.timeout")) {
gTimeoutSeconds = prefs.getIntPref("testing.browserTestHarness.timeout");
}
var sstring = Cc["@mozilla.org/supports-string;1"].createInstance(
Ci.nsISupportsString
);
sstring.data = location.search;
Services.ww.openWindow(
window,
"chrome://mochikit/content/browser-harness.xhtml",
"browserTest",
"chrome,centerscreen,dialog=no,resizable,titlebar,toolbar=no,width=800,height=600",
sstring
);
} else {
// This code allows us to redirect without requiring specialpowers for chrome and a11y tests.
let messageHandler = function(m) {
// eslint-disable-next-line no-undef
messageManager.removeMessageListener("chromeEvent", messageHandler);
var url = m.json.data;
// Window is the [ChromeWindow] for messageManager, so we need content.window
// Currently chrome tests are run in a content window instead of a ChromeWindow
// eslint-disable-next-line no-undef
var webNav = content.window.docShell.QueryInterface(Ci.nsIWebNavigation);
let loadURIOptions = {
triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(),
};
webNav.loadURI(url, loadURIOptions);
};
var listener =
'data:,function doLoad(e) { var data=e.detail&&e.detail.data;removeEventListener("contentEvent", function (e) { doLoad(e); }, false, true);sendAsyncMessage("chromeEvent", {"data":data}); };addEventListener("contentEvent", function (e) { doLoad(e); }, false, true);';
// eslint-disable-next-line no-undef
messageManager.addMessageListener("chromeEvent", messageHandler);
// eslint-disable-next-line no-undef
messageManager.loadFrameScript(listener, true);
}
if (gConfig.e10s) {
e10s_init();
let processCount = prefs.getIntPref("dom.ipc.processCount", 1);
if (processCount > 1) {
// Currently starting a content process is slow, to aviod timeouts, let's
// keep alive content processes.
prefs.setIntPref("dom.ipc.keepProcessesAlive.web", processCount);
}
Services.mm.loadFrameScript(
"chrome://mochikit/content/shutdown-leaks-collector.js",
true
);
} else {
// In non-e10s, only run the ShutdownLeaksCollector in the parent process.
ChromeUtils.import("chrome://mochikit/content/ShutdownLeaksCollector.jsm");
}
}
function isGenerator(value) {
return value && typeof value === "object" && typeof value.next === "function";
}
function Tester(aTests, structuredLogger, aCallback) {
this.structuredLogger = structuredLogger;
this.tests = aTests;
this.callback = aCallback;
this._scriptLoader = Services.scriptloader;
this.EventUtils = {};
this._scriptLoader.loadSubScript(
"chrome://mochikit/content/tests/SimpleTest/EventUtils.js",
this.EventUtils
);
// Make sure our SpecialPowers actor is instantiated, in case it was
// registered after our DOMWindowCreated event was fired (which it
// most likely was).
void window.windowGlobalChild.getActor("SpecialPowers");
var simpleTestScope = {};
this._scriptLoader.loadSubScript(
"chrome://mochikit/content/tests/SimpleTest/SimpleTest.js",
simpleTestScope
);
this._scriptLoader.loadSubScript(
"chrome://mochikit/content/tests/SimpleTest/MemoryStats.js",
simpleTestScope
);
this._scriptLoader.loadSubScript(
"chrome://mochikit/content/chrome-harness.js",
simpleTestScope
);
this.SimpleTest = simpleTestScope.SimpleTest;
window.SpecialPowers.SimpleTest = this.SimpleTest;
window.SpecialPowers.setAsDefaultAssertHandler();
var extensionUtilsScope = {
registerCleanupFunction: fn => {
this.currentTest.scope.registerCleanupFunction(fn);
},
};
extensionUtilsScope.SimpleTest = this.SimpleTest;
this._scriptLoader.loadSubScript(
"chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js",
extensionUtilsScope
);
this.ExtensionTestUtils = extensionUtilsScope.ExtensionTestUtils;
this.SimpleTest.harnessParameters = gConfig;
this.MemoryStats = simpleTestScope.MemoryStats;
this.ContentTask = ChromeUtils.import(
"resource://testing-common/ContentTask.jsm"
).ContentTask;
this.BrowserTestUtils = ChromeUtils.import(
"resource://testing-common/BrowserTestUtils.jsm"
).BrowserTestUtils;
this.TestUtils = ChromeUtils.import(
"resource://testing-common/TestUtils.jsm"
).TestUtils;
this.Promise = ChromeUtils.import(
"resource://gre/modules/Promise.jsm"
).Promise;
this.PromiseTestUtils = ChromeUtils.import(
"resource://testing-common/PromiseTestUtils.jsm"
).PromiseTestUtils;
this.Assert = ChromeUtils.import(
"resource://testing-common/Assert.jsm"
).Assert;
this.PerTestCoverageUtils = ChromeUtils.import(
"resource://testing-common/PerTestCoverageUtils.jsm"
).PerTestCoverageUtils;
this.PromiseTestUtils.init();
this.SimpleTestOriginal = {};
SIMPLETEST_OVERRIDES.forEach(m => {
this.SimpleTestOriginal[m] = this.SimpleTest[m];
});
this._coverageCollector = null;
const XPCOMUtilsMod = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm",
null
);
// Avoid failing tests when XPCOMUtils.defineLazyScriptGetter is used.
XPCOMUtilsMod.Services = Object.create(Services, {
scriptloader: {
configurable: true,
writable: true,
value: {
loadSubScript: (url, obj) => {
let before = Object.keys(window);
try {
return this._scriptLoader.loadSubScript(url, obj);
} finally {
for (let property of Object.keys(window)) {
if (
!before.includes(property) &&
!this._globalProperties.includes(property)
) {
this._globalProperties.push(property);
this.SimpleTest.info(
"Global property added while loading " + url + ": " + property
);
}
}
}
},
loadSubScriptWithOptions: this._scriptLoader.loadSubScriptWithOptions.bind(
this._scriptLoader
),
},
},
});
}
Tester.prototype = {
EventUtils: {},
SimpleTest: {},
ContentTask: null,
ExtensionTestUtils: null,
Assert: null,
repeat: 0,
runUntilFailure: false,
checker: null,
currentTestIndex: -1,
lastStartTime: null,
lastStartTimestamp: null,
lastAssertionCount: 0,
failuresFromInitialWindowState: 0,
get currentTest() {
return this.tests[this.currentTestIndex];
},
get done() {
return this.currentTestIndex == this.tests.length - 1 && this.repeat <= 0;
},
start: function Tester_start() {
TabDestroyObserver.init();
// if testOnLoad was not called, then gConfig is not defined
if (!gConfig) {
gConfig = readConfig();
}
if (gConfig.runUntilFailure) {
this.runUntilFailure = true;
}
if (gConfig.repeat) {
this.repeat = gConfig.repeat;
}
if (gConfig.jscovDirPrefix) {
let coveragePath = gConfig.jscovDirPrefix;
let { CoverageCollector } = ChromeUtils.import(
"resource://testing-common/CoverageUtils.jsm"
);
this._coverageCollector = new CoverageCollector(coveragePath);
}
this.structuredLogger.info("*** Start BrowserChrome Test Results ***");
Services.console.registerListener(this);
this._globalProperties = Object.keys(window);
this._globalPropertyWhitelist = [
"navigator",
"constructor",
"top",
"Application",
"__SS_tabsToRestore",
"__SSi",
"webConsoleCommandController",
// Thunderbird
"MailMigrator",
"SearchIntegration",
];
this.PerTestCoverageUtils.beforeTestSync();
if (this.tests.length) {
this.waitForWindowsReady().then(() => {
this.nextTest();
});
} else {
this.finish();
}
},
async waitForWindowsReady() {
await this.setupDefaultTheme();
await new Promise(resolve =>
this.waitForGraphicsTestWindowToBeGone(resolve)
);
await this.promiseMainWindowReady();
},
async promiseMainWindowReady() {
if (window.gBrowserInit) {
await window.gBrowserInit.idleTasksFinishedPromise;
}
},
async setupDefaultTheme() {
// Developer Edition enables the wrong theme by default. Make sure
// the ordinary default theme is enabled.
let theme = await AddonManager.getAddonByID("default-theme@mozilla.org");
await theme.enable();
},
waitForGraphicsTestWindowToBeGone(aCallback) {
for (let win of Services.wm.getEnumerator(null)) {
if (
win != window &&
!win.closed &&
win.document.documentURI ==
"chrome://gfxsanity/content/sanityparent.html"
) {
this.BrowserTestUtils.domWindowClosed(win).then(aCallback);
return;
}
}
// graphics test window is already gone, just call callback immediately
aCallback();
},
waitForWindowsState: function Tester_waitForWindowsState(aCallback) {
let timedOut = this.currentTest && this.currentTest.timedOut;
// eslint-disable-next-line no-nested-ternary
let baseMsg = timedOut
? "Found a {elt} after previous test timed out"
: this.currentTest
? "Found an unexpected {elt} at the end of test run"
: "Found an unexpected {elt}";
// Remove stale tabs
if (
this.currentTest &&
window.gBrowser &&
AppConstants.MOZ_APP_NAME != "thunderbird" &&
gBrowser.tabs.length > 1
) {
while (gBrowser.tabs.length > 1) {
let lastTab = gBrowser.tabs[gBrowser.tabs.length - 1];
if (!lastTab.closing) {
// Report the stale tab as an error only when they're not closing.
// Tests can finish without waiting for the closing tabs.
this.currentTest.addResult(
new testResult({
name:
baseMsg.replace("{elt}", "tab") +
": " +
lastTab.linkedBrowser.currentURI.spec,
allowFailure: this.currentTest.allowFailure,
})
);
}
gBrowser.removeTab(lastTab);
}
}
// Replace the last tab with a fresh one
if (window.gBrowser && AppConstants.MOZ_APP_NAME != "thunderbird") {
gBrowser.addTab("about:blank", {
skipAnimation: true,
triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(),
});
gBrowser.removeTab(gBrowser.selectedTab, { skipPermitUnload: true });
gBrowser.stop();
}
// Remove stale windows
this.structuredLogger.info("checking window state");
for (let win of Services.wm.getEnumerator(null)) {
let type = win.document.documentElement.getAttribute("windowtype");
if (
win != window &&
!win.closed &&
win.document.documentElement.getAttribute("id") !=
"browserTestHarness" &&
type != "devtools:webconsole"
) {
switch (type) {
case "navigator:browser":
type = "browser window";
break;
case "mail:3pane":
type = "mail window";
break;
case null:
type =
"unknown window with document URI: " +
win.document.documentURI +
" and title: " +
win.document.title;
break;
}
let msg = baseMsg.replace("{elt}", type);
if (this.currentTest) {
this.currentTest.addResult(
new testResult({
name: msg,
allowFailure: this.currentTest.allowFailure,
})
);
} else {
this.failuresFromInitialWindowState++;
this.structuredLogger.error("browser-test.js | " + msg);
}
win.close();
}
}
// Make sure the window is raised before each test.
this.SimpleTest.waitForFocus(aCallback);
},
finish: function Tester_finish(aSkipSummary) {
var passCount = this.tests.reduce((a, f) => a + f.passCount, 0);
var failCount = this.tests.reduce((a, f) => a + f.failCount, 0);
var todoCount = this.tests.reduce((a, f) => a + f.todoCount, 0);
// Include failures from window state checking prior to running the first test
failCount += this.failuresFromInitialWindowState;
TabDestroyObserver.destroy();
Services.console.unregisterListener(this);
// It's important to terminate the module to avoid crashes on shutdown.
this.PromiseTestUtils.uninit();
// In the main process, we print the ShutdownLeaksCollector message here.
let pid = Services.appinfo.processID;
dump("Completed ShutdownLeaks collections in process " + pid + "\n");
this.structuredLogger.info("TEST-START | Shutdown");
if (this.tests.length) {
let e10sMode = window.gMultiProcessBrowser ? "e10s" : "non-e10s";
this.structuredLogger.info("Browser Chrome Test Summary");
this.structuredLogger.info("Passed: " + passCount);
this.structuredLogger.info("Failed: " + failCount);
this.structuredLogger.info("Todo: " + todoCount);
this.structuredLogger.info("Mode: " + e10sMode);
} else {
this.structuredLogger.error(
"browser-test.js | No tests to run. Did you pass invalid test_paths?"
);
}
this.structuredLogger.info("*** End BrowserChrome Test Results ***");
// Tests complete, notify the callback and return
this.callback(this.tests);
this.callback = null;
this.tests = null;
},
haltTests: function Tester_haltTests() {
// Do not run any further tests
this.currentTestIndex = this.tests.length - 1;
this.repeat = 0;
},
observe: function Tester_observe(aSubject, aTopic, aData) {
if (!aTopic) {
this.onConsoleMessage(aSubject);
}
},
onConsoleMessage: function Tester_onConsoleMessage(aConsoleMessage) {
// Ignore empty messages.
if (!aConsoleMessage.message) {
return;
}
try {
var msg = "Console message: " + aConsoleMessage.message;
if (this.currentTest) {
this.currentTest.addResult(new testMessage(msg));
} else {
this.structuredLogger.info(
"TEST-INFO | (browser-test.js) | " + msg.replace(/\n$/, "") + "\n"
);
}
} catch (ex) {
// Swallow exception so we don't lead to another error being reported,
// throwing us into an infinite loop
}
},
async nextTest() {
if (this.currentTest) {
if (this._coverageCollector) {
this._coverageCollector.recordTestCoverage(this.currentTest.path);
}
this.PerTestCoverageUtils.afterTestSync();
// Run cleanup functions for the current test before moving on to the
// next one.
let testScope = this.currentTest.scope;
while (testScope.__cleanupFunctions.length > 0) {
let func = testScope.__cleanupFunctions.shift();
try {
let result = await func.apply(testScope);
if (isGenerator(result)) {
this.SimpleTest.ok(false, "Cleanup function returned a generator");
}
} catch (ex) {
this.currentTest.addResult(
new testResult({
name: "Cleanup function threw an exception",
ex,
allowFailure: this.currentTest.allowFailure,
})
);
}
}
// Spare tests cleanup work.
// Reset gReduceMotionOverride in case the test set it.
if (typeof gReduceMotionOverride == "boolean") {
gReduceMotionOverride = null;
}
Services.obs.notifyObservers(null, "test-complete");
if (
this.currentTest.passCount === 0 &&
this.currentTest.failCount === 0 &&
this.currentTest.todoCount === 0
) {
this.currentTest.addResult(
new testResult({
name:
"This test contains no passes, no fails and no todos. Maybe" +
" it threw a silent exception? Make sure you use" +
" waitForExplicitFinish() if you need it.",
})
);
}
let winUtils = window.windowUtils;
if (winUtils.isTestControllingRefreshes) {
this.currentTest.addResult(
new testResult({
name: "test left refresh driver under test control",
})
);
winUtils.restoreNormalRefresh();
}
if (this.SimpleTest.isExpectingUncaughtException()) {
this.currentTest.addResult(
new testResult({
name:
"expectUncaughtException was called but no uncaught" +
" exception was detected!",
allowFailure: this.currentTest.allowFailure,
})
);
}
this.PromiseTestUtils.ensureDOMPromiseRejectionsProcessed();
this.PromiseTestUtils.assertNoUncaughtRejections();
this.PromiseTestUtils.assertNoMoreExpectedRejections();
Object.keys(window).forEach(function(prop) {
if (parseInt(prop) == prop) {
// This is a string which when parsed as an integer and then
// stringified gives the original string. As in, this is in fact a
// string representation of an integer, so an index into
// window.frames. Skip those.
return;
}
if (!this._globalProperties.includes(prop)) {
this._globalProperties.push(prop);
if (!this._globalPropertyWhitelist.includes(prop)) {
this.currentTest.addResult(
new testResult({
name: "test left unexpected property on window: " + prop,
allowFailure: this.currentTest.allowFailure,
})
);
}
}
}, this);
// Clear document.popupNode. The test could have set it to a custom value
// for its own purposes, nulling it out it will go back to the default
// behavior of returning the last opened popup.
document.popupNode = null;
// eslint-disable-next-line no-undef
await new Promise(resolve => SpecialPowers.flushPrefEnv(resolve));
if (gConfig.cleanupCrashes) {
let gdir = Services.dirsvc.get("UAppData", Ci.nsIFile);
gdir.append("Crash Reports");
gdir.append("pending");
if (gdir.exists()) {
let entries = gdir.directoryEntries;
while (entries.hasMoreElements()) {
let entry = entries.nextFile;
if (entry.isFile()) {
let msg = "this test left a pending crash report; ";
try {
entry.remove(false);
msg += "deleted " + entry.path;
} catch (e) {
msg += "could not delete " + entry.path;
}
this.structuredLogger.info(msg);
}
}
}
}
// Notify a long running test problem if it didn't end up in a timeout.
if (this.currentTest.unexpectedTimeouts && !this.currentTest.timedOut) {
this.currentTest.addResult(
new testResult({
name:
"This test exceeded the timeout threshold. It should be" +
" rewritten or split up. If that's not possible, use" +
" requestLongerTimeout(N), but only as a last resort.",
})
);
}
// If we're in a debug build, check assertion counts. This code
// is similar to the code in TestRunner.testUnloaded in
// TestRunner.js used for all other types of mochitests.
let debugsvc = Cc["@mozilla.org/xpcom/debug;1"].getService(Ci.nsIDebug2);
if (debugsvc.isDebugBuild) {
let newAssertionCount = debugsvc.assertionCount;
let numAsserts = newAssertionCount - this.lastAssertionCount;
this.lastAssertionCount = newAssertionCount;
let max = testScope.__expectedMaxAsserts;
let min = testScope.__expectedMinAsserts;
if (numAsserts > max) {
// TEST-UNEXPECTED-FAIL
this.currentTest.addResult(
new testResult({
name:
"Assertion count " +
numAsserts +
" is greater than expected range " +
min +
"-" +
max +
" assertions.",
pass: true, // TEMPORARILY TEST-KNOWN-FAIL
todo: true,
allowFailure: this.currentTest.allowFailure,
})
);
} else if (numAsserts < min) {
// TEST-UNEXPECTED-PASS
this.currentTest.addResult(
new testResult({
name:
"Assertion count " +
numAsserts +
" is less than expected range " +
min +
"-" +
max +
" assertions.",
todo: true,
allowFailure: this.currentTest.allowFailure,
})
);
} else if (numAsserts > 0) {
// TEST-KNOWN-FAIL
this.currentTest.addResult(
new testResult({
name:
"Assertion count " +
numAsserts +
" is within expected range " +
min +
"-" +
max +
" assertions.",
pass: true,
todo: true,
allowFailure: this.currentTest.allowFailure,
})
);
}
}
if (this.currentTest.allowFailure) {
if (this.currentTest.expectedAllowedFailureCount) {
this.currentTest.addResult(
new testResult({
name:
"Expected " +
this.currentTest.expectedAllowedFailureCount +
" failures in this file, got " +
this.currentTest.allowedFailureCount +
".",
pass:
this.currentTest.expectedAllowedFailureCount ==
this.currentTest.allowedFailureCount,
})
);
} else if (this.currentTest.allowedFailureCount == 0) {
this.currentTest.addResult(
new testResult({
name:
"We expect at least one assertion to fail because this" +
" test file is marked as fail-if in the manifest.",
todo: true,
})
);
}
}
// Dump memory stats for main thread.
if (
Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT
) {
this.MemoryStats.dump(
this.currentTestIndex,
this.currentTest.path,
gConfig.dumpOutputDirectory,
gConfig.dumpAboutMemoryAfterTest,
gConfig.dumpDMDAfterTest
);
}
// Note the test run time
let name = this.currentTest.path;
name = name.slice(name.lastIndexOf("/") + 1);
ChromeUtils.addProfilerMarker(
"browser-test",
this.lastStartTimestamp,
name
);
let time = Date.now() - this.lastStartTime;
this.structuredLogger.testEnd(
this.currentTest.path,
"OK",
undefined,
"finished in " + time + "ms"
);
this.currentTest.setDuration(time);
if (this.runUntilFailure && this.currentTest.failCount > 0) {
this.haltTests();
}
// Restore original SimpleTest methods to avoid leaks.
SIMPLETEST_OVERRIDES.forEach(m => {
this.SimpleTest[m] = this.SimpleTestOriginal[m];
});
this.ContentTask.setTestScope(null);
testScope.destroy();
this.currentTest.scope = null;
}
// Check the window state for the current test before moving to the next one.
// This also causes us to check before starting any tests, since nextTest()
// is invoked to start the tests.
this.waitForWindowsState(() => {
if (this.done) {
if (this._coverageCollector) {
this._coverageCollector.finalize();
} else if (
!AppConstants.RELEASE_OR_BETA &&
!AppConstants.DEBUG &&
!AppConstants.MOZ_CODE_COVERAGE &&
!AppConstants.ASAN &&
!AppConstants.TSAN
) {
this.finish();
return;
}
// Uninitialize a few things explicitly so that they can clean up
// frames and browser intentionally kept alive until shutdown to
// eliminate false positives.
if (gConfig.testRoot == "browser") {
// Skip if SeaMonkey
if (AppConstants.MOZ_APP_NAME != "seamonkey") {
// Replace the document currently loaded in the browser's sidebar.
// This will prevent false positives for tests that were the last
// to touch the sidebar. They will thus not be blamed for leaking
// a document.
let sidebar = document.getElementById("sidebar");
if (sidebar) {
sidebar.setAttribute("src", "data:text/html;charset=utf-8,");
sidebar.docShell.createAboutBlankContentViewer(null, null);
sidebar.setAttribute("src", "about:blank");
}
}
// Destroy BackgroundPageThumbs resources.
let { BackgroundPageThumbs } = ChromeUtils.import(
"resource://gre/modules/BackgroundPageThumbs.jsm"
);
BackgroundPageThumbs._destroy();
if (window.gBrowser) {
NewTabPagePreloading.removePreloadedBrowser(window);
}
}
// Schedule GC and CC runs before finishing in order to detect
// DOM windows leaked by our tests or the tested code. Note that we
// use a shrinking GC so that the JS engine will discard JIT code and
// JIT caches more aggressively.
let shutdownCleanup = aCallback => {
Cu.schedulePreciseShrinkingGC(() => {
// Run the GC and CC a few times to make sure that as much
// as possible is freed.
let numCycles = 3;
for (let i = 0; i < numCycles; i++) {
Cu.forceGC();
Cu.forceCC();
}
aCallback();
});
};
let { AsyncShutdown } = ChromeUtils.import(
"resource://gre/modules/AsyncShutdown.jsm"
);
let barrier = new AsyncShutdown.Barrier(
"ShutdownLeaks: Wait for cleanup to be finished before checking for leaks"
);
Services.obs.notifyObservers(
{ wrappedJSObject: barrier },
"shutdown-leaks-before-check"
);
barrier.client.addBlocker(
"ShutdownLeaks: Wait for tabs to finish closing",
TabDestroyObserver.wait()
);
barrier.wait().then(() => {
// Simulate memory pressure so that we're forced to free more resources
// and thus get rid of more false leaks like already terminated workers.
Services.obs.notifyObservers(
null,
"memory-pressure",
"heap-minimize"
);
Services.ppmm.broadcastAsyncMessage("browser-test:collect-request");
shutdownCleanup(() => {
setTimeout(() => {
shutdownCleanup(() => {
this.finish();
});
}, 1000);
});
});
return;
}
if (this.repeat > 0) {
--this.repeat;
if (this.currentTestIndex < 0) {
this.currentTestIndex = 0;
}
this.execTest();
} else {
this.currentTestIndex++;
if (gConfig.repeat) {
this.repeat = gConfig.repeat;
}
this.execTest();
}
});
},
execTest: function Tester_execTest() {
this.structuredLogger.testStart(this.currentTest.path);
this.SimpleTest.reset();
// Load the tests into a testscope
let currentScope = (this.currentTest.scope = new testScope(
this,
this.currentTest,
this.currentTest.expected
));
let currentTest = this.currentTest;
// Import utils in the test scope.
let { scope } = this.currentTest;
scope.EventUtils = this.EventUtils;
scope.SimpleTest = this.SimpleTest;
scope.gTestPath = this.currentTest.path;
scope.ContentTask = this.ContentTask;
scope.BrowserTestUtils = this.BrowserTestUtils;
scope.TestUtils = this.TestUtils;
scope.ExtensionTestUtils = this.ExtensionTestUtils;
// Pass a custom report function for mochitest style reporting.
scope.Assert = new this.Assert(function(err, message, stack) {
currentTest.addResult(
new testResult(
err
? {
name: err.message,
ex: err.stack,
stack: err.stack,
allowFailure: currentTest.allowFailure,
}
: {
name: message,
pass: true,
stack,
allowFailure: currentTest.allowFailure,
}
)
);
}, true);
this.ContentTask.setTestScope(currentScope);
// Allow Assert.jsm methods to be tacked to the current scope.
scope.export_assertions = function() {
for (let func in this.Assert) {
this[func] = this.Assert[func].bind(this.Assert);
}
};
// Override SimpleTest methods with ours.
SIMPLETEST_OVERRIDES.forEach(function(m) {
this.SimpleTest[m] = this[m];
}, scope);
// load the tools to work with chrome .jar and remote
try {
this._scriptLoader.loadSubScript(
"chrome://mochikit/content/chrome-harness.js",
scope
);
} catch (ex) {