Merge m-c to fx-team.
[gecko.git] / testing / xpcshell / head.js
blob6da236eba5df19f1216a1076d2ae1c96b5e85875
1 /* -*- Mode: JavaScript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:set ts=2 sw=2 sts=2 et: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /*
8  * This file contains common code that is loaded before each test file(s).
9  * See http://developer.mozilla.org/en/docs/Writing_xpcshell-based_unit_tests
10  * for more information.
11  */
13 var _quit = false;
14 var _passed = true;
15 var _tests_pending = 0;
16 var _passedChecks = 0, _falsePassedChecks = 0;
17 var _todoChecks = 0;
18 var _cleanupFunctions = [];
19 var _pendingTimers = [];
20 var _profileInitialized = false;
22 let _log = function (action, params) {
23   if (typeof _XPCSHELL_PROCESS != "undefined") {
24     params.process = _XPCSHELL_PROCESS;
25   }
26   params.action = action;
27   params._time = Date.now();
28   dump("\n" + JSON.stringify(params) + "\n");
31 function _dump(str) {
32   let start = /^TEST-/.test(str) ? "\n" : "";
33   if (typeof _XPCSHELL_PROCESS == "undefined") {
34     dump(start + str);
35   } else {
36     dump(start + _XPCSHELL_PROCESS + ": " + str);
37   }
40 // Disable automatic network detection, so tests work correctly when
41 // not connected to a network.
42 let (ios = Components.classes["@mozilla.org/network/io-service;1"]
43            .getService(Components.interfaces.nsIIOService2)) {
44   ios.manageOfflineStatus = false;
45   ios.offline = false;
48 // Determine if we're running on parent or child
49 let runningInParent = true;
50 try {
51   runningInParent = Components.classes["@mozilla.org/xre/runtime;1"].
52                     getService(Components.interfaces.nsIXULRuntime).processType
53                     == Components.interfaces.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
54
55 catch (e) { }
57 // Only if building of places is enabled.
58 if (runningInParent &&
59     "mozIAsyncHistory" in Components.interfaces) {
60   // Ensure places history is enabled for xpcshell-tests as some non-FF
61   // apps disable it.
62   let (prefs = Components.classes["@mozilla.org/preferences-service;1"]
63                .getService(Components.interfaces.nsIPrefBranch)) {
64     prefs.setBoolPref("places.history.enabled", true);
65   };
68 try {
69   if (runningInParent) {
70     let prefs = Components.classes["@mozilla.org/preferences-service;1"]
71                 .getService(Components.interfaces.nsIPrefBranch);
73     // disable necko IPC security checks for xpcshell, as they lack the
74     // docshells needed to pass them
75     prefs.setBoolPref("network.disable.ipc.security", true);
77     // Disable IPv6 lookups for 'localhost' on windows.
78     if ("@mozilla.org/windows-registry-key;1" in Components.classes) {
79       prefs.setCharPref("network.dns.ipv4OnlyDomains", "localhost");
80     }
81   }
83 catch (e) { }
85 // Configure crash reporting, if possible
86 // We rely on the Python harness to set MOZ_CRASHREPORTER,
87 // MOZ_CRASHREPORTER_NO_REPORT, and handle checking for minidumps.
88 // Note that if we're in a child process, we don't want to init the
89 // crashreporter component.
90 try {
91   if (runningInParent &&
92       "@mozilla.org/toolkit/crash-reporter;1" in Components.classes) {
93     let (crashReporter =
94           Components.classes["@mozilla.org/toolkit/crash-reporter;1"]
95           .getService(Components.interfaces.nsICrashReporter)) {
96       crashReporter.minidumpPath = do_get_tempdir();
97     }
98   }
100 catch (e) { }
103  * Date.now() is not necessarily monotonically increasing (insert sob story
104  * about times not being the right tool to use for measuring intervals of time,
105  * robarnold can tell all), so be wary of error by erring by at least
106  * _timerFuzz ms.
107  */
108 const _timerFuzz = 15;
110 function _Timer(func, delay) {
111   delay = Number(delay);
112   if (delay < 0)
113     do_throw("do_timeout() delay must be nonnegative");
115   if (typeof func !== "function")
116     do_throw("string callbacks no longer accepted; use a function!");
118   this._func = func;
119   this._start = Date.now();
120   this._delay = delay;
122   var timer = Components.classes["@mozilla.org/timer;1"]
123                         .createInstance(Components.interfaces.nsITimer);
124   timer.initWithCallback(this, delay + _timerFuzz, timer.TYPE_ONE_SHOT);
126   // Keep timer alive until it fires
127   _pendingTimers.push(timer);
129 _Timer.prototype = {
130   QueryInterface: function(iid) {
131     if (iid.equals(Components.interfaces.nsITimerCallback) ||
132         iid.equals(Components.interfaces.nsISupports))
133       return this;
135     throw Components.results.NS_ERROR_NO_INTERFACE;
136   },
138   notify: function(timer) {
139     _pendingTimers.splice(_pendingTimers.indexOf(timer), 1);
141     // The current nsITimer implementation can undershoot, but even if it
142     // couldn't, paranoia is probably a virtue here given the potential for
143     // random orange on tinderboxen.
144     var end = Date.now();
145     var elapsed = end - this._start;
146     if (elapsed >= this._delay) {
147       try {
148         this._func.call(null);
149       } catch (e) {
150         do_throw("exception thrown from do_timeout callback: " + e);
151       }
152       return;
153     }
155     // Timer undershot, retry with a little overshoot to try to avoid more
156     // undershoots.
157     var newDelay = this._delay - elapsed;
158     do_timeout(newDelay, this._func);
159   }
162 function _do_main() {
163   if (_quit)
164     return;
166   _log("test_info",
167        {_message: "TEST-INFO | (xpcshell/head.js) | running event loop\n"});
169   var thr = Components.classes["@mozilla.org/thread-manager;1"]
170                       .getService().currentThread;
172   while (!_quit)
173     thr.processNextEvent(true);
175   while (thr.hasPendingEvents())
176     thr.processNextEvent(true);
179 function _do_quit() {
180   _log("test_info",
181        {_message: "TEST-INFO | (xpcshell/head.js) | exiting test\n"});
183   _quit = true;
186 function _format_exception_stack(stack) {
187   // frame is of the form "fname(args)@file:line"
188   let frame_regexp = new RegExp("(.*)\\(.*\\)@(.*):(\\d*)", "g");
189   return stack.split("\n").reduce(function(stack_msg, frame) {
190     if (frame) {
191       let parts = frame_regexp.exec(frame);
192       if (parts) {
193         return stack_msg + "JS frame :: " + parts[2] + " :: " +
194           (parts[1] ? parts[1] : "anonymous") +
195           " :: line " + parts[3] + "\n";
196       }
197       else { /* Could be a -e (command line string) style location. */
198         return stack_msg + "JS frame :: " + frame + "\n";
199       }
200     }
201     return stack_msg;
202   }, "");
206  * Overrides idleService with a mock.  Idle is commonly used for maintenance
207  * tasks, thus if a test uses a service that requires the idle service, it will
208  * start handling them.
209  * This behaviour would cause random failures and slowdown tests execution,
210  * for example by running database vacuum or cleanups for each test.
212  * @note Idle service is overridden by default.  If a test requires it, it will
213  *       have to call do_get_idle() function at least once before use.
214  */
215 var _fakeIdleService = {
216   get registrar() {
217     delete this.registrar;
218     return this.registrar =
219       Components.manager.QueryInterface(Components.interfaces.nsIComponentRegistrar);
220   },
221   contractID: "@mozilla.org/widget/idleservice;1",
222   get CID() this.registrar.contractIDToCID(this.contractID),
224   activate: function FIS_activate()
225   {
226     if (!this.originalFactory) {
227       // Save original factory.
228       this.originalFactory =
229         Components.manager.getClassObject(Components.classes[this.contractID],
230                                           Components.interfaces.nsIFactory);
231       // Unregister original factory.
232       this.registrar.unregisterFactory(this.CID, this.originalFactory);
233       // Replace with the mock.
234       this.registrar.registerFactory(this.CID, "Fake Idle Service",
235                                      this.contractID, this.factory
236       );
237     }
238   },
240   deactivate: function FIS_deactivate()
241   {
242     if (this.originalFactory) {
243       // Unregister the mock.
244       this.registrar.unregisterFactory(this.CID, this.factory);
245       // Restore original factory.
246       this.registrar.registerFactory(this.CID, "Idle Service",
247                                      this.contractID, this.originalFactory);
248       delete this.originalFactory;
249     }
250   },
252   factory: {
253     // nsIFactory
254     createInstance: function (aOuter, aIID)
255     {
256       if (aOuter) {
257         throw Components.results.NS_ERROR_NO_AGGREGATION;
258       }
259       return _fakeIdleService.QueryInterface(aIID);
260     },
261     lockFactory: function (aLock) {
262       throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
263     },
264     QueryInterface: function(aIID) {
265       if (aIID.equals(Components.interfaces.nsIFactory) ||
266           aIID.equals(Components.interfaces.nsISupports)) {
267         return this;
268       }
269       throw Components.results.NS_ERROR_NO_INTERFACE;
270     }
271   },
273   // nsIIdleService
274   get idleTime() 0,
275   addIdleObserver: function () {},
276   removeIdleObserver: function () {},
278   QueryInterface: function(aIID) {
279     // Useful for testing purposes, see test_get_idle.js.
280     if (aIID.equals(Components.interfaces.nsIFactory)) {
281       return this.factory;
282     }
283     if (aIID.equals(Components.interfaces.nsIIdleService) ||
284         aIID.equals(Components.interfaces.nsISupports)) {
285       return this;
286     }
287     throw Components.results.NS_ERROR_NO_INTERFACE;
288   }
292  * Restores the idle service factory if needed and returns the service's handle.
293  * @return A handle to the idle service.
294  */
295 function do_get_idle() {
296   _fakeIdleService.deactivate();
297   return Components.classes[_fakeIdleService.contractID]
298                    .getService(Components.interfaces.nsIIdleService);
301 // Map resource://test/ to current working directory and
302 // resource://testing-common/ to the shared test modules directory.
303 function _register_protocol_handlers() {
304   let (ios = Components.classes["@mozilla.org/network/io-service;1"]
305              .getService(Components.interfaces.nsIIOService)) {
306     let protocolHandler =
307       ios.getProtocolHandler("resource")
308          .QueryInterface(Components.interfaces.nsIResProtocolHandler);
309     let curDirURI = ios.newFileURI(do_get_cwd());
310     protocolHandler.setSubstitution("test", curDirURI);
312     if (this._TESTING_MODULES_DIR) {
313       let modulesFile = Components.classes["@mozilla.org/file/local;1"].
314                         createInstance(Components.interfaces.nsILocalFile);
315       modulesFile.initWithPath(_TESTING_MODULES_DIR);
317       if (!modulesFile.exists()) {
318         throw new Error("Specified modules directory does not exist: " +
319                         _TESTING_MODULES_DIR);
320       }
322       if (!modulesFile.isDirectory()) {
323         throw new Error("Specified modules directory is not a directory: " +
324                         _TESTING_MODULES_DIR);
325       }
327       let modulesURI = ios.newFileURI(modulesFile);
329       protocolHandler.setSubstitution("testing-common", modulesURI);
330     }
331   }
334 function _execute_test() {
335   _register_protocol_handlers();
337   // Override idle service by default.
338   // Call do_get_idle() to restore the factory and get the service.
339   _fakeIdleService.activate();
341   // _HEAD_FILES is dynamically defined by <runxpcshelltests.py>.
342   _load_files(_HEAD_FILES);
343   // _TEST_FILE is dynamically defined by <runxpcshelltests.py>.
344   _load_files(_TEST_FILE);
346   try {
347     do_test_pending("MAIN run_test");
348     run_test();
349     do_test_finished("MAIN run_test");
350     _do_main();
351   } catch (e) {
352     _passed = false;
353     // do_check failures are already logged and set _quit to true and throw
354     // NS_ERROR_ABORT. If both of those are true it is likely this exception
355     // has already been logged so there is no need to log it again. It's
356     // possible that this will mask an NS_ERROR_ABORT that happens after a
357     // do_check failure though.
358     if (!_quit || e != Components.results.NS_ERROR_ABORT) {
359       let msgObject = {};
360       if (e.fileName) {
361         msgObject.source_file = e.fileName;
362         if (e.lineNumber) {
363           msgObject.line_number = e.lineNumber;
364         }
365       } else {
366         msgObject.source_file = "xpcshell/head.js";
367       }
368       msgObject.diagnostic = _exception_message(e);
369       if (e.stack) {
370         msgObject.diagnostic += " - See following stack:\n";
371         msgObject.stack = _format_exception_stack(e.stack);
372       }
373       _log("test_unexpected_fail", msgObject);
374     }
375   }
377   // _TAIL_FILES is dynamically defined by <runxpcshelltests.py>.
378   _load_files(_TAIL_FILES);
380   // Execute all of our cleanup functions.
381   var func;
382   while ((func = _cleanupFunctions.pop()))
383     func();
385   // Restore idle service to avoid leaks.
386   _fakeIdleService.deactivate();
388   if (!_passed)
389     return;
391   var truePassedChecks = _passedChecks - _falsePassedChecks;
392   if (truePassedChecks > 0) {
393     _log("test_pass",
394          {_message: "TEST-PASS | (xpcshell/head.js) | " + truePassedChecks + " (+ " +
395                     _falsePassedChecks + ") check(s) passed\n",
396           source_file: _TEST_FILE,
397           passed_checks: truePassedChecks});
398     _log("test_info",
399          {_message: "TEST-INFO | (xpcshell/head.js) | " + _todoChecks +
400                     " check(s) todo\n",
401           source_file: _TEST_FILE,
402           todo_checks: _todoChecks});
403   } else {
404     // ToDo: switch to TEST-UNEXPECTED-FAIL when all tests have been updated. (Bug 496443)
405     _log("test_info",
406          {_message: "TEST-INFO | (xpcshell/head.js) | No (+ " + _falsePassedChecks +
407                     ") checks actually run\n",
408          source_file: _TEST_FILE});
409   }
413  * Loads files.
415  * @param aFiles Array of files to load.
416  */
417 function _load_files(aFiles) {
418   function loadTailFile(element, index, array) {
419     try {
420       load(element);
421     } catch (e if e instanceof SyntaxError) {
422       _log("javascript_error",
423            {_message: "TEST-UNEXPECTED-FAIL | (xpcshell/head.js) | Source file " + element + " contains SyntaxError",
424             diagnostic: _exception_message(e),
425             source_file: element,
426             stack: _format_exception_stack(e.stack)});
427     }
428   }
430   aFiles.forEach(loadTailFile);
433 function _wrap_with_quotes_if_necessary(val) {
434   return typeof val == "string" ? '"' + val + '"' : val;
437 /************** Functions to be used from the tests **************/
440  * Prints a message to the output log.
441  */
442 function do_print(msg) {
443   var caller_stack = Components.stack.caller;
444   msg = _wrap_with_quotes_if_necessary(msg);
445   _log("test_info",
446        {source_file: caller_stack.filename,
447         diagnostic: msg});
452  * Calls the given function at least the specified number of milliseconds later.
453  * The callback will not undershoot the given time, but it might overshoot --
454  * don't expect precision!
456  * @param delay : uint
457  *   the number of milliseconds to delay
458  * @param callback : function() : void
459  *   the function to call
460  */
461 function do_timeout(delay, func) {
462   new _Timer(func, Number(delay));
465 function do_execute_soon(callback, aName) {
466   let funcName = (aName ? aName : callback.name);
467   do_test_pending(funcName);
468   var tm = Components.classes["@mozilla.org/thread-manager;1"]
469                      .getService(Components.interfaces.nsIThreadManager);
471   tm.mainThread.dispatch({
472     run: function() {
473       try {
474         callback();
475       } catch (e) {
476         // do_check failures are already logged and set _quit to true and throw
477         // NS_ERROR_ABORT. If both of those are true it is likely this exception
478         // has already been logged so there is no need to log it again. It's
479         // possible that this will mask an NS_ERROR_ABORT that happens after a
480         // do_check failure though.
481         if (!_quit || e != Components.results.NS_ERROR_ABORT) {
482           if (e.stack) {
483             _log("javascript_error",
484                  {source_file: "xpcshell/head.js",
485                   diagnostic: _exception_message(e) + " - See following stack:",
486                   stack: _format_exception_stack(e.stack)});
487           } else {
488             _log("javascript_error",
489                  {source_file: "xpcshell/head.js",
490                   diagnostic: _exception_message(e)});
491           }
492           _do_quit();
493         }
494       }
495       finally {
496         do_test_finished(funcName);
497       }
498     }
499   }, Components.interfaces.nsIThread.DISPATCH_NORMAL);
503  * Shows an error message and the current stack and aborts the test.
505  * @param error  A message string or an Error object.
506  * @param stack  null or nsIStackFrame object or a string containing
507  *               \n separated stack lines (as in Error().stack).
508  */
509 function do_throw(error, stack) {
510   let filename = "";
511   // If we didn't get passed a stack, maybe the error has one
512   // otherwise get it from our call context
513   stack = stack || error.stack || Components.stack.caller;
515   if (stack instanceof Components.interfaces.nsIStackFrame)
516     filename = stack.filename;
517   else if (error.fileName)
518     filename = error.fileName;
520   _log_message_with_stack("test_unexpected_fail",
521                           error, stack, filename);
523   _passed = false;
524   _do_quit();
525   throw Components.results.NS_ERROR_ABORT;
528 function _format_stack(stack) {
529   if (stack instanceof Components.interfaces.nsIStackFrame) {
530     let stack_msg = "";
531     let frame = stack;
532     while (frame != null) {
533       stack_msg += frame + "\n";
534       frame = frame.caller;
535     }
536     return stack_msg;
537   }
538   return "" + stack;
541 function do_throw_todo(text, stack) {
542   if (!stack)
543     stack = Components.stack.caller;
545   _passed = false;
546   _log_message_with_stack("test_unexpected_pass",
547                           text, stack, stack.filename);
548   _do_quit();
549   throw Components.results.NS_ERROR_ABORT;
552 // Make a nice display string from an object that behaves
553 // like Error
554 function _exception_message(ex) {
555   let message = "";
556   if (ex.name) {
557     message = ex.name + ": ";
558   }
559   if (ex.message) {
560     message += ex.message;
561   }
562   if (ex.fileName) {
563     message += (" at " + ex.fileName);
564     if (ex.lineNumber) {
565       message += (":" + ex.lineNumber);
566     }
567   }
568   if (message !== "") {
569     return message;
570   }
571   // Force ex to be stringified
572   return "" + ex;
575 function _log_message_with_stack(action, ex, stack, filename, text) {
576   if (stack) {
577     _log(action,
578          {diagnostic: (text ? text : "") +
579                       _exception_message(ex) +
580                       " - See following stack:",
581           source_file: filename,
582           stack: _format_stack(stack)});
583   } else {
584     _log(action,
585          {diagnostic: (text ? text : "") +
586                       _exception_message(ex),
587           source_file: filename});
588   }
591 function do_report_unexpected_exception(ex, text) {
592   var caller_stack = Components.stack.caller;
593   text = text ? text + " - " : "";
595   _passed = false;
596   _log_message_with_stack("test_unexpected_fail", ex, ex.stack,
597                           caller_stack.filename, text + "Unexpected exception ");
598   _do_quit();
599   throw Components.results.NS_ERROR_ABORT;
602 function do_note_exception(ex, text) {
603   var caller_stack = Components.stack.caller;
604   text = text ? text + " - " : "";
606   _log_message_with_stack("test_info", ex, ex.stack,
607                           caller_stack.filename, text + "Swallowed exception ");
610 function _do_check_neq(left, right, stack, todo) {
611   if (!stack)
612     stack = Components.stack.caller;
614   var text = _wrap_with_quotes_if_necessary(left) + " != " +
615              _wrap_with_quotes_if_necessary(right);
616   do_report_result(left != right, text, stack, todo);
619 function do_check_neq(left, right, stack) {
620   if (!stack)
621     stack = Components.stack.caller;
623   _do_check_neq(left, right, stack, false);
626 function todo_check_neq(left, right, stack) {
627   if (!stack)
628       stack = Components.stack.caller;
630   _do_check_neq(left, right, stack, true);
633 function do_report_result(passed, text, stack, todo) {
634   if (passed) {
635     if (todo) {
636       do_throw_todo(text, stack);
637     } else {
638       ++_passedChecks;
639       _log("test_pass",
640            {source_file: stack.filename,
641             test_name: stack.name,
642             line_number: stack.lineNumber,
643             diagnostic: "[" + stack.name + " : " + stack.lineNumber + "] " +
644                         text + "\n"});
645     }
646   } else {
647     if (todo) {
648       ++_todoChecks;
649       _log("test_known_fail",
650            {source_file: stack.filename,
651             test_name: stack.name,
652             line_number: stack.lineNumber,
653             diagnostic: "[" + stack.name + " : " + stack.lineNumber + "] " +
654                         text + "\n"});
655     } else {
656       do_throw(text, stack);
657     }
658   }
661 function _do_check_eq(left, right, stack, todo) {
662   if (!stack)
663     stack = Components.stack.caller;
665   var text = _wrap_with_quotes_if_necessary(left) + " == " +
666              _wrap_with_quotes_if_necessary(right);
667   do_report_result(left == right, text, stack, todo);
670 function do_check_eq(left, right, stack) {
671   if (!stack)
672     stack = Components.stack.caller;
674   _do_check_eq(left, right, stack, false);
677 function todo_check_eq(left, right, stack) {
678   if (!stack)
679       stack = Components.stack.caller;
681   _do_check_eq(left, right, stack, true);
684 function do_check_true(condition, stack) {
685   if (!stack)
686     stack = Components.stack.caller;
688   do_check_eq(condition, true, stack);
691 function todo_check_true(condition, stack) {
692   if (!stack)
693     stack = Components.stack.caller;
695   todo_check_eq(condition, true, stack);
698 function do_check_false(condition, stack) {
699   if (!stack)
700     stack = Components.stack.caller;
702   do_check_eq(condition, false, stack);
705 function todo_check_false(condition, stack) {
706   if (!stack)
707     stack = Components.stack.caller;
709   todo_check_eq(condition, false, stack);
712 function do_check_null(condition, stack=Components.stack.caller) {
713   do_check_eq(condition, null, stack);
716 function todo_check_null(condition, stack=Components.stack.caller) {
717   todo_check_eq(condition, null, stack);
721  * Check that |value| matches |pattern|.
723  * A |value| matches a pattern |pattern| if any one of the following is true:
725  * - |value| and |pattern| are both objects; |pattern|'s enumerable
726  *   properties' values are valid patterns; and for each enumerable
727  *   property |p| of |pattern|, plus 'length' if present at all, |value|
728  *   has a property |p| whose value matches |pattern.p|. Note that if |j|
729  *   has other properties not present in |p|, |j| may still match |p|.
731  * - |value| and |pattern| are equal string, numeric, or boolean literals
733  * - |pattern| is |undefined| (this is a wildcard pattern)
735  * - typeof |pattern| == "function", and |pattern(value)| is true.
737  * For example:
739  * do_check_matches({x:1}, {x:1})       // pass
740  * do_check_matches({x:1}, {})          // fail: all pattern props required
741  * do_check_matches({x:1}, {x:2})       // fail: values must match
742  * do_check_matches({x:1}, {x:1, y:2})  // pass: extra props tolerated
744  * // Property order is irrelevant.
745  * do_check_matches({x:"foo", y:"bar"}, {y:"bar", x:"foo"}) // pass
747  * do_check_matches({x:undefined}, {x:1}) // pass: 'undefined' is wildcard
748  * do_check_matches({x:undefined}, {x:2})
749  * do_check_matches({x:undefined}, {y:2}) // fail: 'x' must still be there
751  * // Patterns nest.
752  * do_check_matches({a:1, b:{c:2,d:undefined}}, {a:1, b:{c:2,d:3}})
754  * // 'length' property counts, even if non-enumerable.
755  * do_check_matches([3,4,5], [3,4,5])     // pass
756  * do_check_matches([3,4,5], [3,5,5])     // fail; value doesn't match
757  * do_check_matches([3,4,5], [3,4,5,6])   // fail; length doesn't match
759  * // functions in patterns get applied.
760  * do_check_matches({foo:function (v) v.length == 2}, {foo:"hi"}) // pass
761  * do_check_matches({foo:function (v) v.length == 2}, {bar:"hi"}) // fail
762  * do_check_matches({foo:function (v) v.length == 2}, {foo:"hello"}) // fail
764  * // We don't check constructors, prototypes, or classes. However, if
765  * // pattern has a 'length' property, we require values to match that as
766  * // well, even if 'length' is non-enumerable in the pattern. So arrays
767  * // are useful as patterns.
768  * do_check_matches({0:0, 1:1, length:2}, [0,1])  // pass
769  * do_check_matches({0:1}, [1,2])                 // pass
770  * do_check_matches([0], {0:0, length:1})         // pass
772  * Notes:
774  * The 'length' hack gives us reasonably intuitive handling of arrays.
776  * This is not a tight pattern-matcher; it's only good for checking data
777  * from well-behaved sources. For example:
778  * - By default, we don't mind values having extra properties.
779  * - We don't check for proxies or getters.
780  * - We don't check the prototype chain.
781  * However, if you know the values are, say, JSON, which is pretty
782  * well-behaved, and if you want to tolerate additional properties
783  * appearing on the JSON for backward-compatibility, then do_check_matches
784  * is ideal. If you do want to be more careful, you can use function
785  * patterns to implement more stringent checks.
786  */
787 function do_check_matches(pattern, value, stack=Components.stack.caller, todo=false) {
788   var matcher = pattern_matcher(pattern);
789   var text = "VALUE: " + uneval(value) + "\nPATTERN: " + uneval(pattern) + "\n";
790   var diagnosis = []
791   if (matcher(value, diagnosis)) {
792     do_report_result(true, "value matches pattern:\n" + text, stack, todo);
793   } else {
794     text = ("value doesn't match pattern:\n" +
795             text +
796             "DIAGNOSIS: " +
797             format_pattern_match_failure(diagnosis[0]) + "\n");
798     do_report_result(false, text, stack, todo);
799   }
802 function todo_check_matches(pattern, value, stack=Components.stack.caller) {
803   do_check_matches(pattern, value, stack, true);
806 // Return a pattern-matching function of one argument, |value|, that
807 // returns true if |value| matches |pattern|.
809 // If the pattern doesn't match, and the pattern-matching function was
810 // passed its optional |diagnosis| argument, the pattern-matching function
811 // sets |diagnosis|'s '0' property to a JSON-ish description of the portion
812 // of the pattern that didn't match, which can be formatted legibly by
813 // format_pattern_match_failure.
814 function pattern_matcher(pattern) {
815   function explain(diagnosis, reason) {
816     if (diagnosis) {
817       diagnosis[0] = reason;
818     }
819     return false;
820   }
821   if (typeof pattern == "function") {
822     return pattern;
823   } else if (typeof pattern == "object" && pattern) {
824     var matchers = [[p, pattern_matcher(pattern[p])] for (p in pattern)];
825     // Kludge: include 'length', if not enumerable. (If it is enumerable,
826     // we picked it up in the array comprehension, above.
827     ld = Object.getOwnPropertyDescriptor(pattern, 'length');
828     if (ld && !ld.enumerable) {
829       matchers.push(['length', pattern_matcher(pattern.length)])
830     }
831     return function (value, diagnosis) {
832       if (!(value && typeof value == "object")) {
833         return explain(diagnosis, "value not object");
834       }
835       for (let [p, m] of matchers) {
836         var element_diagnosis = [];
837         if (!(p in value && m(value[p], element_diagnosis))) {
838           return explain(diagnosis, { property:p,
839                                       diagnosis:element_diagnosis[0] });
840         }
841       }
842       return true;
843     };
844   } else if (pattern === undefined) {
845     return function(value) { return true; };
846   } else {
847     return function (value, diagnosis) {
848       if (value !== pattern) {
849         return explain(diagnosis, "pattern " + uneval(pattern) + " not === to value " + uneval(value));
850       }
851       return true;
852     };
853   }
856 // Format an explanation for a pattern match failure, as stored in the
857 // second argument to a matching function.
858 function format_pattern_match_failure(diagnosis, indent="") {
859   var a;
860   if (!diagnosis) {
861     a = "Matcher did not explain reason for mismatch.";
862   } else if (typeof diagnosis == "string") {
863     a = diagnosis;
864   } else if (diagnosis.property) {
865     a = "Property " + uneval(diagnosis.property) + " of object didn't match:\n";
866     a += format_pattern_match_failure(diagnosis.diagnosis, indent + "  ");
867   }
868   return indent + a;
871 function do_test_pending(aName) {
872   ++_tests_pending;
874   _log("test_pending",
875        {_message: "TEST-INFO | (xpcshell/head.js) | test" +
876                   (aName ? " " + aName : "") +
877                   " pending (" + _tests_pending + ")\n"});
880 function do_test_finished(aName) {
881   _log("test_finish",
882        {_message: "TEST-INFO | (xpcshell/head.js) | test" +
883                   (aName ? " " + aName : "") +
884                   " finished (" + _tests_pending + ")\n"});
885   if (--_tests_pending == 0)
886     _do_quit();
889 function do_get_file(path, allowNonexistent) {
890   try {
891     let lf = Components.classes["@mozilla.org/file/directory_service;1"]
892       .getService(Components.interfaces.nsIProperties)
893       .get("CurWorkD", Components.interfaces.nsILocalFile);
895     let bits = path.split("/");
896     for (let i = 0; i < bits.length; i++) {
897       if (bits[i]) {
898         if (bits[i] == "..")
899           lf = lf.parent;
900         else
901           lf.append(bits[i]);
902       }
903     }
905     if (!allowNonexistent && !lf.exists()) {
906       // Not using do_throw(): caller will continue.
907       _passed = false;
908       var stack = Components.stack.caller;
909       _log("test_unexpected_fail",
910            {source_file: stack.filename,
911             test_name: stack.name,
912             line_number: stack.lineNumber,
913             diagnostic: "[" + stack.name + " : " + stack.lineNumber + "] " +
914                         lf.path + " does not exist\n"});
915     }
917     return lf;
918   }
919   catch (ex) {
920     do_throw(ex.toString(), Components.stack.caller);
921   }
923   return null;
926 // do_get_cwd() isn't exactly self-explanatory, so provide a helper
927 function do_get_cwd() {
928   return do_get_file("");
931 function do_load_manifest(path) {
932   var lf = do_get_file(path);
933   const nsIComponentRegistrar = Components.interfaces.nsIComponentRegistrar;
934   do_check_true(Components.manager instanceof nsIComponentRegistrar);
935   // Previous do_check_true() is not a test check.
936   ++_falsePassedChecks;
937   Components.manager.autoRegister(lf);
941  * Parse a DOM document.
943  * @param aPath File path to the document.
944  * @param aType Content type to use in DOMParser.
946  * @return nsIDOMDocument from the file.
947  */
948 function do_parse_document(aPath, aType) {
949   switch (aType) {
950     case "application/xhtml+xml":
951     case "application/xml":
952     case "text/xml":
953       break;
955     default:
956       do_throw("type: expected application/xhtml+xml, application/xml or text/xml," +
957                  " got '" + aType + "'",
958                Components.stack.caller);
959   }
961   var lf = do_get_file(aPath);
962   const C_i = Components.interfaces;
963   const parserClass = "@mozilla.org/xmlextras/domparser;1";
964   const streamClass = "@mozilla.org/network/file-input-stream;1";
965   var stream = Components.classes[streamClass]
966                          .createInstance(C_i.nsIFileInputStream);
967   stream.init(lf, -1, -1, C_i.nsIFileInputStream.CLOSE_ON_EOF);
968   var parser = Components.classes[parserClass]
969                          .createInstance(C_i.nsIDOMParser);
970   var doc = parser.parseFromStream(stream, null, lf.fileSize, aType);
971   parser = null;
972   stream = null;
973   lf = null;
974   return doc;
978  * Registers a function that will run when the test harness is done running all
979  * tests.
981  * @param aFunction
982  *        The function to be called when the test harness has finished running.
983  */
984 function do_register_cleanup(aFunction)
986   _cleanupFunctions.push(aFunction);
990  * Returns the directory for a temp dir, which is created by the
991  * test harness. Every test gets its own temp dir.
993  * @return nsILocalFile of the temporary directory
994  */
995 function do_get_tempdir() {
996   let env = Components.classes["@mozilla.org/process/environment;1"]
997                       .getService(Components.interfaces.nsIEnvironment);
998   // the python harness sets this in the environment for us
999   let path = env.get("XPCSHELL_TEST_TEMP_DIR");
1000   let file = Components.classes["@mozilla.org/file/local;1"]
1001                        .createInstance(Components.interfaces.nsILocalFile);
1002   file.initWithPath(path);
1003   return file;
1007  * Registers a directory with the profile service,
1008  * and return the directory as an nsILocalFile.
1010  * @return nsILocalFile of the profile directory.
1011  */
1012 function do_get_profile() {
1013   if (!runningInParent) {
1014     _log("test_info",
1015          {_message: "TEST-INFO | (xpcshell/head.js) | Ignoring profile creation from child process.\n"});
1017     return null;
1018   }
1020   if (!_profileInitialized) {
1021     // Since we have a profile, we will notify profile shutdown topics at
1022     // the end of the current test, to ensure correct cleanup on shutdown.
1023     do_register_cleanup(function() {
1024       let obsSvc = Components.classes["@mozilla.org/observer-service;1"].
1025                    getService(Components.interfaces.nsIObserverService);
1026       obsSvc.notifyObservers(null, "profile-change-net-teardown", null);
1027       obsSvc.notifyObservers(null, "profile-change-teardown", null);
1028       obsSvc.notifyObservers(null, "profile-before-change", null);
1029     });
1030   }
1032   let env = Components.classes["@mozilla.org/process/environment;1"]
1033                       .getService(Components.interfaces.nsIEnvironment);
1034   // the python harness sets this in the environment for us
1035   let profd = env.get("XPCSHELL_TEST_PROFILE_DIR");
1036   let file = Components.classes["@mozilla.org/file/local;1"]
1037                        .createInstance(Components.interfaces.nsILocalFile);
1038   file.initWithPath(profd);
1040   let dirSvc = Components.classes["@mozilla.org/file/directory_service;1"]
1041                          .getService(Components.interfaces.nsIProperties);
1042   let provider = {
1043     getFile: function(prop, persistent) {
1044       persistent.value = true;
1045       if (prop == "ProfD" || prop == "ProfLD" || prop == "ProfDS" ||
1046           prop == "ProfLDS" || prop == "TmpD") {
1047         return file.clone();
1048       }
1049       throw Components.results.NS_ERROR_FAILURE;
1050     },
1051     QueryInterface: function(iid) {
1052       if (iid.equals(Components.interfaces.nsIDirectoryServiceProvider) ||
1053           iid.equals(Components.interfaces.nsISupports)) {
1054         return this;
1055       }
1056       throw Components.results.NS_ERROR_NO_INTERFACE;
1057     }
1058   };
1059   dirSvc.QueryInterface(Components.interfaces.nsIDirectoryService)
1060         .registerProvider(provider);
1062   let obsSvc = Components.classes["@mozilla.org/observer-service;1"].
1063         getService(Components.interfaces.nsIObserverService);
1065   if (!_profileInitialized) {
1066     obsSvc.notifyObservers(null, "profile-do-change", "xpcshell-do-get-profile");
1067     _profileInitialized = true;
1068   }
1070   // The methods of 'provider' will retain this scope so null out everything
1071   // to avoid spurious leak reports.
1072   env = null;
1073   profd = null;
1074   dirSvc = null;
1075   provider = null;
1076   obsSvc = null;
1077   return file.clone();
1081  * This function loads head.js (this file) in the child process, so that all
1082  * functions defined in this file (do_throw, etc) are available to subsequent
1083  * sendCommand calls.  It also sets various constants used by these functions.
1085  * (Note that you may use sendCommand without calling this function first;  you
1086  * simply won't have any of the functions in this file available.)
1087  */
1088 function do_load_child_test_harness()
1090   // Make sure this isn't called from child process
1091   if (!runningInParent) {
1092     do_throw("run_test_in_child cannot be called from child!");
1093   }
1095   // Allow to be called multiple times, but only run once
1096   if (typeof do_load_child_test_harness.alreadyRun != "undefined")
1097     return;
1098   do_load_child_test_harness.alreadyRun = 1;
1100   _XPCSHELL_PROCESS = "parent";
1102   let command =
1103         "const _HEAD_JS_PATH=" + uneval(_HEAD_JS_PATH) + "; "
1104       + "const _HTTPD_JS_PATH=" + uneval(_HTTPD_JS_PATH) + "; "
1105       + "const _HEAD_FILES=" + uneval(_HEAD_FILES) + "; "
1106       + "const _TAIL_FILES=" + uneval(_TAIL_FILES) + "; "
1107       + "const _XPCSHELL_PROCESS='child';";
1109   if (this._TESTING_MODULES_DIR) {
1110     command += " const _TESTING_MODULES_DIR=" + uneval(_TESTING_MODULES_DIR) + ";";
1111   }
1113   command += " load(_HEAD_JS_PATH);";
1114   sendCommand(command);
1118  * Runs an entire xpcshell unit test in a child process (rather than in chrome,
1119  * which is the default).
1121  * This function returns immediately, before the test has completed.  
1123  * @param testFile
1124  *        The name of the script to run.  Path format same as load().
1125  * @param optionalCallback.
1126  *        Optional function to be called (in parent) when test on child is
1127  *        complete.  If provided, the function must call do_test_finished();
1128  */
1129 function run_test_in_child(testFile, optionalCallback) 
1131   var callback = (typeof optionalCallback == 'undefined') ? 
1132                     do_test_finished : optionalCallback;
1134   do_load_child_test_harness();
1136   var testPath = do_get_file(testFile).path.replace(/\\/g, "/");
1137   do_test_pending("run in child");
1138   sendCommand("_log('child_test_start', {_message: 'CHILD-TEST-STARTED'}); "
1139               + "const _TEST_FILE=['" + testPath + "']; _execute_test(); "
1140               + "_log('child_test_end', {_message: 'CHILD-TEST-COMPLETED'});",
1141               callback);
1146  * Add a test function to the list of tests that are to be run asynchronously.
1148  * Each test function must call run_next_test() when it's done. Test files
1149  * should call run_next_test() in their run_test function to execute all
1150  * async tests.
1152  * @return the test function that was passed in.
1153  */
1154 let _gTests = [];
1155 function add_test(func) {
1156   _gTests.push([false, func]);
1157   return func;
1160 // We lazy import Task.jsm so we don't incur a run-time penalty for all tests.
1161 let _Task;
1164  * Add a test function which is a Task function.
1166  * Task functions are functions fed into Task.jsm's Task.spawn(). They are
1167  * generators that emit promises.
1169  * If an exception is thrown, a do_check_* comparison fails, or if a rejected
1170  * promise is yielded, the test function aborts immediately and the test is
1171  * reported as a failure.
1173  * Unlike add_test(), there is no need to call run_next_test(). The next test
1174  * will run automatically as soon the task function is exhausted. To trigger
1175  * premature (but successful) termination of the function, simply return or
1176  * throw a Task.Result instance.
1178  * Example usage:
1180  * add_task(function test() {
1181  *   let result = yield Promise.resolve(true);
1183  *   do_check_true(result);
1185  *   let secondary = yield someFunctionThatReturnsAPromise(result);
1186  *   do_check_eq(secondary, "expected value");
1187  * });
1189  * add_task(function test_early_return() {
1190  *   let result = yield somethingThatReturnsAPromise();
1192  *   if (!result) {
1193  *     // Test is ended immediately, with success.
1194  *     return;
1195  *   }
1197  *   do_check_eq(result, "foo");
1198  * });
1199  */
1200 function add_task(func) {
1201   if (!_Task) {
1202     let ns = {};
1203     _Task = Components.utils.import("resource://gre/modules/Task.jsm", ns).Task;
1204   }
1206   _gTests.push([true, func]);
1210  * Runs the next test function from the list of async tests.
1211  */
1212 let _gRunningTest = null;
1213 let _gTestIndex = 0; // The index of the currently running test.
1214 function run_next_test()
1216   function _run_next_test()
1217   {
1218     if (_gTestIndex < _gTests.length) {
1219       let _isTask;
1220       [_isTask, _gRunningTest] = _gTests[_gTestIndex++];
1221       print("TEST-INFO | " + _TEST_FILE + " | Starting " + _gRunningTest.name);
1222       do_test_pending(_gRunningTest.name);
1224       if (_isTask) {
1225         _Task.spawn(_gRunningTest)
1226              .then(run_next_test, do_report_unexpected_exception);
1227       } else {
1228         // Exceptions do not kill asynchronous tests, so they'll time out.
1229         try {
1230           _gRunningTest();
1231         } catch (e) {
1232           do_throw(e);
1233         }
1234       }
1235     }
1236   }
1238   // For sane stacks during failures, we execute this code soon, but not now.
1239   // We do this now, before we call do_test_finished(), to ensure the pending
1240   // counter (_tests_pending) never reaches 0 while we still have tests to run
1241   // (do_execute_soon bumps that counter).
1242   do_execute_soon(_run_next_test, "run_next_test " + _gTestIndex);
1244   if (_gRunningTest !== null) {
1245     // Close the previous test do_test_pending call.
1246     do_test_finished(_gRunningTest.name);
1247   }
1250 try {
1251   if (runningInParent) {
1252     // Always use network provider for geolocation tests
1253     // so we bypass the OSX dialog raised by the corelocation provider
1254     let prefs = Components.classes["@mozilla.org/preferences-service;1"]
1255       .getService(Components.interfaces.nsIPrefBranch);
1257     prefs.setBoolPref("geo.provider.testing", true);
1258   }
1259 } catch (e) { }