This repository has been archived by the owner on Aug 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhead.js
1663 lines (1476 loc) · 52.8 KB
/
head.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
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et: */
/* 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/. */
/*
* This file contains common code that is loaded before each test file(s).
* See http://developer.mozilla.org/en/docs/Writing_xpcshell-based_unit_tests
* for more information.
*/
var _quit = false;
var _passed = true;
var _tests_pending = 0;
var _cleanupFunctions = [];
var _pendingTimers = [];
var _profileInitialized = false;
// Register the testing-common resource protocol early, to have access to its
// modules.
_register_modules_protocol_handler();
var _Promise = Components.utils.import("resource://gre/modules/Promise.jsm", {}).Promise;
var _PromiseTestUtils = Components.utils.import("resource://testing-common/PromiseTestUtils.jsm", {}).PromiseTestUtils;
Components.utils.importGlobalProperties(["XMLHttpRequest"]);
// Support a common assertion library, Assert.jsm.
var AssertCls = Components.utils.import("resource://testing-common/Assert.jsm", null).Assert;
// Pass a custom report function for xpcshell-test style reporting.
var Assert = new AssertCls(function(err, message, stack) {
if (err) {
do_report_result(false, err.message, err.stack);
} else {
do_report_result(true, message, stack);
}
});
var _add_params = function (params) {
if (typeof _XPCSHELL_PROCESS != "undefined") {
params.xpcshell_process = _XPCSHELL_PROCESS;
}
};
var _dumpLog = function (raw_msg) {
dump("\n" + JSON.stringify(raw_msg) + "\n");
}
var _LoggerClass = Components.utils.import("resource://testing-common/StructuredLog.jsm", null).StructuredLogger;
var _testLogger = new _LoggerClass("xpcshell/head.js", _dumpLog, [_add_params]);
// Disable automatic network detection, so tests work correctly when
// not connected to a network.
{
let ios = Components.classes["@mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService2);
ios.manageOfflineStatus = false;
ios.offline = false;
}
// Determine if we're running on parent or child
var runningInParent = true;
try {
runningInParent = Components.classes["@mozilla.org/xre/runtime;1"].
getService(Components.interfaces.nsIXULRuntime).processType
== Components.interfaces.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
}
catch (e) { }
// Only if building of places is enabled.
if (runningInParent &&
"mozIAsyncHistory" in Components.interfaces) {
// Ensure places history is enabled for xpcshell-tests as some non-FF
// apps disable it.
let prefs = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
prefs.setBoolPref("places.history.enabled", true);
}
try {
if (runningInParent) {
let prefs = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
// disable necko IPC security checks for xpcshell, as they lack the
// docshells needed to pass them
prefs.setBoolPref("network.disable.ipc.security", true);
// Disable IPv6 lookups for 'localhost' on windows.
if ("@mozilla.org/windows-registry-key;1" in Components.classes) {
prefs.setCharPref("network.dns.ipv4OnlyDomains", "localhost");
}
}
}
catch (e) { }
// Configure crash reporting, if possible
// We rely on the Python harness to set MOZ_CRASHREPORTER,
// MOZ_CRASHREPORTER_NO_REPORT, and handle checking for minidumps.
// Note that if we're in a child process, we don't want to init the
// crashreporter component.
try {
if (runningInParent &&
"@mozilla.org/toolkit/crash-reporter;1" in Components.classes) {
let crashReporter =
Components.classes["@mozilla.org/toolkit/crash-reporter;1"]
.getService(Components.interfaces.nsICrashReporter);
crashReporter.UpdateCrashEventsDir();
crashReporter.minidumpPath = do_get_minidumpdir();
}
}
catch (e) { }
// Configure a console listener so messages sent to it are logged as part
// of the test.
try {
let levelNames = {}
for (let level of ["debug", "info", "warn", "error"]) {
levelNames[Components.interfaces.nsIConsoleMessage[level]] = level;
}
let listener = {
QueryInterface : function(iid) {
if (!iid.equals(Components.interfaces.nsISupports) &&
!iid.equals(Components.interfaces.nsIConsoleListener)) {
throw Components.results.NS_NOINTERFACE;
}
return this;
},
observe : function (msg) {
if (typeof do_print === "function")
do_print("CONSOLE_MESSAGE: (" + levelNames[msg.logLevel] + ") " + msg.toString());
}
};
Components.classes["@mozilla.org/consoleservice;1"]
.getService(Components.interfaces.nsIConsoleService)
.registerListener(listener);
} catch (e) {}
/**
* Date.now() is not necessarily monotonically increasing (insert sob story
* about times not being the right tool to use for measuring intervals of time,
* robarnold can tell all), so be wary of error by erring by at least
* _timerFuzz ms.
*/
const _timerFuzz = 15;
function _Timer(func, delay) {
delay = Number(delay);
if (delay < 0)
do_throw("do_timeout() delay must be nonnegative");
if (typeof func !== "function")
do_throw("string callbacks no longer accepted; use a function!");
this._func = func;
this._start = Date.now();
this._delay = delay;
var timer = Components.classes["@mozilla.org/timer;1"]
.createInstance(Components.interfaces.nsITimer);
timer.initWithCallback(this, delay + _timerFuzz, timer.TYPE_ONE_SHOT);
// Keep timer alive until it fires
_pendingTimers.push(timer);
}
_Timer.prototype = {
QueryInterface: function(iid) {
if (iid.equals(Components.interfaces.nsITimerCallback) ||
iid.equals(Components.interfaces.nsISupports))
return this;
throw Components.results.NS_ERROR_NO_INTERFACE;
},
notify: function(timer) {
_pendingTimers.splice(_pendingTimers.indexOf(timer), 1);
// The current nsITimer implementation can undershoot, but even if it
// couldn't, paranoia is probably a virtue here given the potential for
// random orange on tinderboxen.
var end = Date.now();
var elapsed = end - this._start;
if (elapsed >= this._delay) {
try {
this._func.call(null);
} catch (e) {
do_throw("exception thrown from do_timeout callback: " + e);
}
return;
}
// Timer undershot, retry with a little overshoot to try to avoid more
// undershoots.
var newDelay = this._delay - elapsed;
do_timeout(newDelay, this._func);
}
};
function _do_main() {
if (_quit)
return;
_testLogger.info("running event loop");
var thr = Components.classes["@mozilla.org/thread-manager;1"]
.getService().currentThread;
while (!_quit)
thr.processNextEvent(true);
while (thr.hasPendingEvents())
thr.processNextEvent(true);
}
function _do_quit() {
_testLogger.info("exiting test");
_quit = true;
}
/**
* Overrides idleService with a mock. Idle is commonly used for maintenance
* tasks, thus if a test uses a service that requires the idle service, it will
* start handling them.
* This behaviour would cause random failures and slowdown tests execution,
* for example by running database vacuum or cleanups for each test.
*
* @note Idle service is overridden by default. If a test requires it, it will
* have to call do_get_idle() function at least once before use.
*/
var _fakeIdleService = {
get registrar() {
delete this.registrar;
return this.registrar =
Components.manager.QueryInterface(Components.interfaces.nsIComponentRegistrar);
},
contractID: "@mozilla.org/widget/idleservice;1",
get CID() {
return this.registrar.contractIDToCID(this.contractID);
},
activate: function FIS_activate()
{
if (!this.originalFactory) {
// Save original factory.
this.originalFactory =
Components.manager.getClassObject(Components.classes[this.contractID],
Components.interfaces.nsIFactory);
// Unregister original factory.
this.registrar.unregisterFactory(this.CID, this.originalFactory);
// Replace with the mock.
this.registrar.registerFactory(this.CID, "Fake Idle Service",
this.contractID, this.factory
);
}
},
deactivate: function FIS_deactivate()
{
if (this.originalFactory) {
// Unregister the mock.
this.registrar.unregisterFactory(this.CID, this.factory);
// Restore original factory.
this.registrar.registerFactory(this.CID, "Idle Service",
this.contractID, this.originalFactory);
delete this.originalFactory;
}
},
factory: {
// nsIFactory
createInstance: function (aOuter, aIID)
{
if (aOuter) {
throw Components.results.NS_ERROR_NO_AGGREGATION;
}
return _fakeIdleService.QueryInterface(aIID);
},
lockFactory: function (aLock) {
throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
},
QueryInterface: function(aIID) {
if (aIID.equals(Components.interfaces.nsIFactory) ||
aIID.equals(Components.interfaces.nsISupports)) {
return this;
}
throw Components.results.NS_ERROR_NO_INTERFACE;
}
},
// nsIIdleService
get idleTime() {
return 0;
},
addIdleObserver: function () {},
removeIdleObserver: function () {},
QueryInterface: function(aIID) {
// Useful for testing purposes, see test_get_idle.js.
if (aIID.equals(Components.interfaces.nsIFactory)) {
return this.factory;
}
if (aIID.equals(Components.interfaces.nsIIdleService) ||
aIID.equals(Components.interfaces.nsISupports)) {
return this;
}
throw Components.results.NS_ERROR_NO_INTERFACE;
}
}
/**
* Restores the idle service factory if needed and returns the service's handle.
* @return A handle to the idle service.
*/
function do_get_idle() {
_fakeIdleService.deactivate();
return Components.classes[_fakeIdleService.contractID]
.getService(Components.interfaces.nsIIdleService);
}
// Map resource://test/ to current working directory and
// resource://testing-common/ to the shared test modules directory.
function _register_protocol_handlers() {
let ios = Components.classes["@mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
let protocolHandler =
ios.getProtocolHandler("resource")
.QueryInterface(Components.interfaces.nsIResProtocolHandler);
let curDirURI = ios.newFileURI(do_get_cwd());
protocolHandler.setSubstitution("test", curDirURI);
_register_modules_protocol_handler();
}
function _register_modules_protocol_handler() {
if (!_TESTING_MODULES_DIR) {
throw new Error("Please define a path where the testing modules can be " +
"found in a variable called '_TESTING_MODULES_DIR' before " +
"head.js is included.");
}
let ios = Components.classes["@mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
let protocolHandler =
ios.getProtocolHandler("resource")
.QueryInterface(Components.interfaces.nsIResProtocolHandler);
let modulesFile = Components.classes["@mozilla.org/file/local;1"].
createInstance(Components.interfaces.nsILocalFile);
modulesFile.initWithPath(_TESTING_MODULES_DIR);
if (!modulesFile.exists()) {
throw new Error("Specified modules directory does not exist: " +
_TESTING_MODULES_DIR);
}
if (!modulesFile.isDirectory()) {
throw new Error("Specified modules directory is not a directory: " +
_TESTING_MODULES_DIR);
}
let modulesURI = ios.newFileURI(modulesFile);
protocolHandler.setSubstitution("testing-common", modulesURI);
}
/* Debugging support */
// Used locally and by our self-tests.
function _setupDebuggerServer(breakpointFiles, callback) {
let prefs = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
// Always allow remote debugging.
prefs.setBoolPref("devtools.debugger.remote-enabled", true);
// for debugging-the-debugging, let an env var cause log spew.
let env = Components.classes["@mozilla.org/process/environment;1"]
.getService(Components.interfaces.nsIEnvironment);
if (env.get("DEVTOOLS_DEBUGGER_LOG")) {
prefs.setBoolPref("devtools.debugger.log", true);
}
if (env.get("DEVTOOLS_DEBUGGER_LOG_VERBOSE")) {
prefs.setBoolPref("devtools.debugger.log.verbose", true);
}
let require;
try {
({ require } = Components.utils.import("resource://devtools/shared/Loader.jsm", {}));
} catch (e) {
throw new Error("resource://devtools appears to be inaccessible from the " +
"xpcshell environment.\n" +
"This can usually be resolved by adding:\n" +
" firefox-appdir = browser\n" +
"to the xpcshell.ini manifest.\n" +
"It is possible for this to alter test behevior by " +
"triggering additional browser code to run, so check " +
"test behavior after making this change.\n" +
"See also https://bugzil.la/1215378.")
}
let { DebuggerServer } = require("devtools/server/main");
let { OriginalLocation } = require("devtools/server/actors/common");
DebuggerServer.init();
DebuggerServer.addBrowserActors();
DebuggerServer.addActors("resource://testing-common/dbg-actors.js");
DebuggerServer.allowChromeProcess = true;
// An observer notification that tells us when we can "resume" script
// execution.
let obsSvc = Components.classes["@mozilla.org/observer-service;1"].
getService(Components.interfaces.nsIObserverService);
const TOPICS = ["devtools-thread-resumed", "xpcshell-test-devtools-shutdown"];
let observe = function(subject, topic, data) {
switch (topic) {
case "devtools-thread-resumed":
// Exceptions in here aren't reported and block the debugger from
// resuming, so...
try {
// Add a breakpoint for the first line in our test files.
let threadActor = subject.wrappedJSObject;
for (let file of breakpointFiles) {
// Pass an empty `source` object to workaround `source` function assertion
let sourceActor = threadActor.sources.source({originalUrl: file, source: {}});
sourceActor._getOrCreateBreakpointActor(new OriginalLocation(sourceActor, 1));
}
} catch (ex) {
do_print("Failed to initialize breakpoints: " + ex + "\n" + ex.stack);
}
break;
case "xpcshell-test-devtools-shutdown":
// the debugger has shutdown before we got a resume event - nothing
// special to do here.
break;
}
for (let topicToRemove of TOPICS) {
obsSvc.removeObserver(observe, topicToRemove);
}
callback();
};
for (let topic of TOPICS) {
obsSvc.addObserver(observe, topic, false);
}
return DebuggerServer;
}
function _initDebugging(port) {
let initialized = false;
let DebuggerServer = _setupDebuggerServer(_TEST_FILE, () => {initialized = true;});
do_print("");
do_print("*******************************************************************");
do_print("Waiting for the debugger to connect on port " + port)
do_print("")
do_print("To connect the debugger, open a Firefox instance, select 'Connect'");
do_print("from the Developer menu and specify the port as " + port);
do_print("*******************************************************************");
do_print("")
let AuthenticatorType = DebuggerServer.Authenticators.get("PROMPT");
let authenticator = new AuthenticatorType.Server();
authenticator.allowConnection = () => {
return DebuggerServer.AuthenticationResult.ALLOW;
};
let listener = DebuggerServer.createListener();
listener.portOrPath = port;
listener.authenticator = authenticator;
listener.open();
// spin an event loop until the debugger connects.
let thr = Components.classes["@mozilla.org/thread-manager;1"]
.getService().currentThread;
while (!initialized) {
do_print("Still waiting for debugger to connect...");
thr.processNextEvent(true);
}
// NOTE: if you want to debug the harness itself, you can now add a 'debugger'
// statement anywhere and it will stop - but we've already added a breakpoint
// for the first line of the test scripts, so we just continue...
do_print("Debugger connected, starting test execution");
}
function _execute_test() {
// _JSDEBUGGER_PORT is dynamically defined by <runxpcshelltests.py>.
if (_JSDEBUGGER_PORT) {
try {
_initDebugging(_JSDEBUGGER_PORT);
} catch (ex) {
// Fail the test run immediately if debugging is requested but fails, so
// that the failure state is more obvious.
do_throw(`Failed to initialize debugging: ${ex}`, ex.stack);
}
}
_register_protocol_handlers();
// Override idle service by default.
// Call do_get_idle() to restore the factory and get the service.
_fakeIdleService.activate();
_PromiseTestUtils.init();
_PromiseTestUtils.Assert = Assert;
let coverageCollector = null;
if (typeof _JSCOV_DIR === 'string') {
let _CoverageCollector = Components.utils.import("resource://testing-common/CoverageUtils.jsm", {}).CoverageCollector;
coverageCollector = new _CoverageCollector(_JSCOV_DIR);
}
// _HEAD_FILES is dynamically defined by <runxpcshelltests.py>.
_load_files(_HEAD_FILES);
// _TEST_FILE is dynamically defined by <runxpcshelltests.py>.
_load_files(_TEST_FILE);
// Tack Assert.jsm methods to the current scope.
this.Assert = Assert;
for (let func in Assert) {
this[func] = Assert[func].bind(Assert);
}
if (_gTestHasOnly) {
_gTests = _gTests.filter(([props,]) => {
return ("_only" in props) && props._only;
});
}
try {
do_test_pending("MAIN run_test");
// Check if run_test() is defined. If defined, run it.
// Else, call run_next_test() directly to invoke tests
// added by add_test() and add_task().
if (typeof run_test === "function") {
run_test();
} else {
run_next_test();
}
if (coverageCollector != null) {
coverageCollector.recordTestCoverage(_TEST_FILE[0]);
}
do_test_finished("MAIN run_test");
_do_main();
_PromiseTestUtils.assertNoUncaughtRejections();
} catch (e) {
_passed = false;
// do_check failures are already logged and set _quit to true and throw
// NS_ERROR_ABORT. If both of those are true it is likely this exception
// has already been logged so there is no need to log it again. It's
// possible that this will mask an NS_ERROR_ABORT that happens after a
// do_check failure though.
if (coverageCollector != null) {
coverageCollector.recordTestCoverage(_TEST_FILE[0]);
}
if (!_quit || e != Components.results.NS_ERROR_ABORT) {
let extra = {};
if (e.fileName) {
extra.source_file = e.fileName;
if (e.lineNumber) {
extra.line_number = e.lineNumber;
}
} else {
extra.source_file = "xpcshell/head.js";
}
let message = _exception_message(e);
if (e.stack) {
extra.stack = _format_stack(e.stack);
}
_testLogger.error(message, extra);
}
}
if (coverageCollector != null) {
coverageCollector.finalize();
}
// _TAIL_FILES is dynamically defined by <runxpcshelltests.py>.
_load_files(_TAIL_FILES);
// Execute all of our cleanup functions.
let reportCleanupError = function(ex) {
let stack, filename;
if (ex && typeof ex == "object" && "stack" in ex) {
stack = ex.stack;
} else {
stack = Components.stack.caller;
}
if (stack instanceof Components.interfaces.nsIStackFrame) {
filename = stack.filename;
} else if (ex.fileName) {
filename = ex.fileName;
}
_testLogger.error(_exception_message(ex),
{
stack: _format_stack(stack),
source_file: filename
});
};
let func;
while ((func = _cleanupFunctions.pop())) {
let result;
try {
result = func();
} catch (ex) {
reportCleanupError(ex);
continue;
}
if (result && typeof result == "object"
&& "then" in result && typeof result.then == "function") {
// This is a promise, wait until it is satisfied before proceeding
let complete = false;
let promise = result.then(null, reportCleanupError);
promise = promise.then(() => complete = true);
let thr = Components.classes["@mozilla.org/thread-manager;1"]
.getService().currentThread;
while (!complete) {
thr.processNextEvent(true);
}
}
}
// Restore idle service to avoid leaks.
_fakeIdleService.deactivate();
if (_profileInitialized) {
// Since we have a profile, we will notify profile shutdown topics at
// the end of the current test, to ensure correct cleanup on shutdown.
let obs = Components.classes["@mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
obs.notifyObservers(null, "profile-change-net-teardown", null);
obs.notifyObservers(null, "profile-change-teardown", null);
obs.notifyObservers(null, "profile-before-change", null);
obs.notifyObservers(null, "profile-before-change-qm", null);
_profileInitialized = false;
}
try {
_PromiseTestUtils.ensureDOMPromiseRejectionsProcessed();
_PromiseTestUtils.assertNoUncaughtRejections();
_PromiseTestUtils.assertNoMoreExpectedRejections();
} finally {
// It's important to terminate the module to avoid crashes on shutdown.
_PromiseTestUtils.uninit();
}
}
/**
* Loads files.
*
* @param aFiles Array of files to load.
*/
function _load_files(aFiles) {
function load_file(element, index, array) {
try {
load(element);
} catch (e) {
let extra = {
source_file: element
}
if (e.stack) {
extra.stack = _format_stack(e.stack);
}
_testLogger.error(_exception_message(e), extra);
}
}
aFiles.forEach(load_file);
}
function _wrap_with_quotes_if_necessary(val) {
return typeof val == "string" ? '"' + val + '"' : val;
}
/************** Functions to be used from the tests **************/
/**
* Prints a message to the output log.
*/
function do_print(msg, data) {
msg = _wrap_with_quotes_if_necessary(msg);
data = data ? data : null;
_testLogger.info(msg, data);
}
/**
* Calls the given function at least the specified number of milliseconds later.
* The callback will not undershoot the given time, but it might overshoot --
* don't expect precision!
*
* @param delay : uint
* the number of milliseconds to delay
* @param callback : function() : void
* the function to call
*/
function do_timeout(delay, func) {
new _Timer(func, Number(delay));
}
function do_execute_soon(callback, aName) {
let funcName = (aName ? aName : callback.name);
do_test_pending(funcName);
var tm = Components.classes["@mozilla.org/thread-manager;1"]
.getService(Components.interfaces.nsIThreadManager);
tm.mainThread.dispatch({
run: function() {
try {
callback();
} catch (e) {
// do_check failures are already logged and set _quit to true and throw
// NS_ERROR_ABORT. If both of those are true it is likely this exception
// has already been logged so there is no need to log it again. It's
// possible that this will mask an NS_ERROR_ABORT that happens after a
// do_check failure though.
if (!_quit || e != Components.results.NS_ERROR_ABORT) {
let stack = e.stack ? _format_stack(e.stack) : null;
_testLogger.testStatus(_TEST_NAME,
funcName,
'FAIL',
'PASS',
_exception_message(e),
stack);
_do_quit();
}
}
finally {
do_test_finished(funcName);
}
}
}, Components.interfaces.nsIThread.DISPATCH_NORMAL);
}
/**
* Shows an error message and the current stack and aborts the test.
*
* @param error A message string or an Error object.
* @param stack null or nsIStackFrame object or a string containing
* \n separated stack lines (as in Error().stack).
*/
function do_throw(error, stack) {
let filename = "";
// If we didn't get passed a stack, maybe the error has one
// otherwise get it from our call context
stack = stack || error.stack || Components.stack.caller;
if (stack instanceof Components.interfaces.nsIStackFrame)
filename = stack.filename;
else if (error.fileName)
filename = error.fileName;
_testLogger.error(_exception_message(error),
{
source_file: filename,
stack: _format_stack(stack)
});
_abort_failed_test();
}
function _abort_failed_test() {
// Called to abort the test run after all failures are logged.
_passed = false;
_do_quit();
throw Components.results.NS_ERROR_ABORT;
}
function _format_stack(stack) {
let normalized;
if (stack instanceof Components.interfaces.nsIStackFrame) {
let frames = [];
for (let frame = stack; frame; frame = frame.caller) {
frames.push(frame.filename + ":" + frame.name + ":" + frame.lineNumber);
}
normalized = frames.join("\n");
} else {
normalized = "" + stack;
}
return _Task.Debugging.generateReadableStack(normalized, " ");
}
// Make a nice display string from an object that behaves
// like Error
function _exception_message(ex) {
let message = "";
if (ex.name) {
message = ex.name + ": ";
}
if (ex.message) {
message += ex.message;
}
if (ex.fileName) {
message += (" at " + ex.fileName);
if (ex.lineNumber) {
message += (":" + ex.lineNumber);
}
}
if (message !== "") {
return message;
}
// Force ex to be stringified
return "" + ex;
}
function do_report_unexpected_exception(ex, text) {
let filename = Components.stack.caller.filename;
text = text ? text + " - " : "";
_passed = false;
_testLogger.error(text + "Unexpected exception " + _exception_message(ex),
{
source_file: filename,
stack: _format_stack(ex.stack)
});
_do_quit();
throw Components.results.NS_ERROR_ABORT;
}
function do_note_exception(ex, text) {
let filename = Components.stack.caller.filename;
_testLogger.info(text + "Swallowed exception " + _exception_message(ex),
{
source_file: filename,
stack: _format_stack(ex.stack)
});
}
function _do_check_neq(left, right, stack, todo) {
Assert.notEqual(left, right);
}
function do_check_neq(left, right, stack) {
if (!stack)
stack = Components.stack.caller;
_do_check_neq(left, right, stack, false);
}
function todo_check_neq(left, right, stack) {
if (!stack)
stack = Components.stack.caller;
_do_check_neq(left, right, stack, true);
}
function do_report_result(passed, text, stack, todo) {
while (stack.filename.includes("head.js") && stack.caller) {
stack = stack.caller;
}
let name = _gRunningTest ? _gRunningTest.name : stack.name;
let message;
if (name) {
message = "[" + name + " : " + stack.lineNumber + "] " + text;
} else {
message = text;
}
if (passed) {
if (todo) {
_testLogger.testStatus(_TEST_NAME,
name,
"PASS",
"FAIL",
message,
_format_stack(stack));
_abort_failed_test();
} else {
_testLogger.testStatus(_TEST_NAME,
name,
"PASS",
"PASS",
message);
}
} else {
if (todo) {
_testLogger.testStatus(_TEST_NAME,
name,
"FAIL",
"FAIL",
message);
} else {
_testLogger.testStatus(_TEST_NAME,
name,
"FAIL",
"PASS",
message,
_format_stack(stack));
_abort_failed_test();
}
}
}
function _do_check_eq(left, right, stack, todo) {
if (!stack)
stack = Components.stack.caller;
var text = _wrap_with_quotes_if_necessary(left) + " == " +
_wrap_with_quotes_if_necessary(right);
do_report_result(left == right, text, stack, todo);
}
function do_check_eq(left, right, stack) {
Assert.equal(left, right);
}
function todo_check_eq(left, right, stack) {
if (!stack)
stack = Components.stack.caller;
_do_check_eq(left, right, stack, true);
}
function do_check_true(condition, stack) {
Assert.ok(condition, stack);
}
function todo_check_true(condition, stack) {
if (!stack)
stack = Components.stack.caller;
todo_check_eq(condition, true, stack);
}
function do_check_false(condition, stack) {
Assert.ok(!condition, stack);
}
function todo_check_false(condition, stack) {
if (!stack)
stack = Components.stack.caller;
todo_check_eq(condition, false, stack);
}
function do_check_null(condition, stack) {
Assert.equal(condition, null);
}
function todo_check_null(condition, stack=Components.stack.caller) {
todo_check_eq(condition, null, stack);
}
function do_check_matches(pattern, value) {
Assert.deepEqual(pattern, value);
}
// Check that |func| throws an nsIException that has
// |Components.results[resultName]| as the value of its 'result' property.
function do_check_throws_nsIException(func, resultName,
stack=Components.stack.caller, todo=false)
{
let expected = Components.results[resultName];
if (typeof expected !== 'number') {
do_throw("do_check_throws_nsIException requires a Components.results" +
" property name, not " + uneval(resultName), stack);
}
let msg = ("do_check_throws_nsIException: func should throw" +
" an nsIException whose 'result' is Components.results." +
resultName);
try {
func();
} catch (ex) {
if (!(ex instanceof Components.interfaces.nsIException) ||
ex.result !== expected) {
do_report_result(false, msg + ", threw " + legible_exception(ex) +
" instead", stack, todo);
}
do_report_result(true, msg, stack, todo);
return;
}
// Call this here, not in the 'try' clause, so do_report_result's own
// throw doesn't get caught by our 'catch' clause.
do_report_result(false, msg + ", but returned normally", stack, todo);
}
// Produce a human-readable form of |exception|. This looks up
// Components.results values, tries toString methods, and so on.
function legible_exception(exception)
{
switch (typeof exception) {
case 'object':
if (exception instanceof Components.interfaces.nsIException) {
return "nsIException instance: " + uneval(exception.toString());
}
return exception.toString();
case 'number':
for (let name in Components.results) {
if (exception === Components.results[name]) {
return "Components.results." + name;
}
}