testing/xpcshell/head.js

Wed, 31 Dec 2014 06:55:50 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:55:50 +0100
changeset 2
7e26c7da4463
permissions
-rw-r--r--

Added tag UPSTREAM_283F7C6 for changeset ca08bd8f51b2

michael@0 1 /* -*- Mode: JavaScript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
michael@0 2 /* vim:set ts=2 sw=2 sts=2 et: */
michael@0 3 /* This Source Code Form is subject to the terms of the Mozilla Public
michael@0 4 * License, v. 2.0. If a copy of the MPL was not distributed with this
michael@0 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
michael@0 6
michael@0 7 /*
michael@0 8 * This file contains common code that is loaded before each test file(s).
michael@0 9 * See http://developer.mozilla.org/en/docs/Writing_xpcshell-based_unit_tests
michael@0 10 * for more information.
michael@0 11 */
michael@0 12
michael@0 13 var _quit = false;
michael@0 14 var _passed = true;
michael@0 15 var _tests_pending = 0;
michael@0 16 var _passedChecks = 0, _falsePassedChecks = 0;
michael@0 17 var _todoChecks = 0;
michael@0 18 var _cleanupFunctions = [];
michael@0 19 var _pendingTimers = [];
michael@0 20 var _profileInitialized = false;
michael@0 21
michael@0 22 let _Promise = Components.utils.import("resource://gre/modules/Promise.jsm", this).Promise;
michael@0 23
michael@0 24 let _log = function (action, params) {
michael@0 25 if (typeof _XPCSHELL_PROCESS != "undefined") {
michael@0 26 params.process = _XPCSHELL_PROCESS;
michael@0 27 }
michael@0 28 params.action = action;
michael@0 29 params._time = Date.now();
michael@0 30 dump("\n" + JSON.stringify(params) + "\n");
michael@0 31 }
michael@0 32
michael@0 33 function _dump(str) {
michael@0 34 let start = /^TEST-/.test(str) ? "\n" : "";
michael@0 35 if (typeof _XPCSHELL_PROCESS == "undefined") {
michael@0 36 dump(start + str);
michael@0 37 } else {
michael@0 38 dump(start + _XPCSHELL_PROCESS + ": " + str);
michael@0 39 }
michael@0 40 }
michael@0 41
michael@0 42 // Disable automatic network detection, so tests work correctly when
michael@0 43 // not connected to a network.
michael@0 44 let (ios = Components.classes["@mozilla.org/network/io-service;1"]
michael@0 45 .getService(Components.interfaces.nsIIOService2)) {
michael@0 46 ios.manageOfflineStatus = false;
michael@0 47 ios.offline = false;
michael@0 48 }
michael@0 49
michael@0 50 // Determine if we're running on parent or child
michael@0 51 let runningInParent = true;
michael@0 52 try {
michael@0 53 runningInParent = Components.classes["@mozilla.org/xre/runtime;1"].
michael@0 54 getService(Components.interfaces.nsIXULRuntime).processType
michael@0 55 == Components.interfaces.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
michael@0 56 }
michael@0 57 catch (e) { }
michael@0 58
michael@0 59 // Only if building of places is enabled.
michael@0 60 if (runningInParent &&
michael@0 61 "mozIAsyncHistory" in Components.interfaces) {
michael@0 62 // Ensure places history is enabled for xpcshell-tests as some non-FF
michael@0 63 // apps disable it.
michael@0 64 let (prefs = Components.classes["@mozilla.org/preferences-service;1"]
michael@0 65 .getService(Components.interfaces.nsIPrefBranch)) {
michael@0 66 prefs.setBoolPref("places.history.enabled", true);
michael@0 67 };
michael@0 68 }
michael@0 69
michael@0 70 try {
michael@0 71 if (runningInParent) {
michael@0 72 let prefs = Components.classes["@mozilla.org/preferences-service;1"]
michael@0 73 .getService(Components.interfaces.nsIPrefBranch);
michael@0 74
michael@0 75 // disable necko IPC security checks for xpcshell, as they lack the
michael@0 76 // docshells needed to pass them
michael@0 77 prefs.setBoolPref("network.disable.ipc.security", true);
michael@0 78
michael@0 79 // Disable IPv6 lookups for 'localhost' on windows.
michael@0 80 if ("@mozilla.org/windows-registry-key;1" in Components.classes) {
michael@0 81 prefs.setCharPref("network.dns.ipv4OnlyDomains", "localhost");
michael@0 82 }
michael@0 83 }
michael@0 84 }
michael@0 85 catch (e) { }
michael@0 86
michael@0 87 // Configure crash reporting, if possible
michael@0 88 // We rely on the Python harness to set MOZ_CRASHREPORTER,
michael@0 89 // MOZ_CRASHREPORTER_NO_REPORT, and handle checking for minidumps.
michael@0 90 // Note that if we're in a child process, we don't want to init the
michael@0 91 // crashreporter component.
michael@0 92 try {
michael@0 93 if (runningInParent &&
michael@0 94 "@mozilla.org/toolkit/crash-reporter;1" in Components.classes) {
michael@0 95 let (crashReporter =
michael@0 96 Components.classes["@mozilla.org/toolkit/crash-reporter;1"]
michael@0 97 .getService(Components.interfaces.nsICrashReporter)) {
michael@0 98 crashReporter.UpdateCrashEventsDir();
michael@0 99 crashReporter.minidumpPath = do_get_minidumpdir();
michael@0 100 }
michael@0 101 }
michael@0 102 }
michael@0 103 catch (e) { }
michael@0 104
michael@0 105 /**
michael@0 106 * Date.now() is not necessarily monotonically increasing (insert sob story
michael@0 107 * about times not being the right tool to use for measuring intervals of time,
michael@0 108 * robarnold can tell all), so be wary of error by erring by at least
michael@0 109 * _timerFuzz ms.
michael@0 110 */
michael@0 111 const _timerFuzz = 15;
michael@0 112
michael@0 113 function _Timer(func, delay) {
michael@0 114 delay = Number(delay);
michael@0 115 if (delay < 0)
michael@0 116 do_throw("do_timeout() delay must be nonnegative");
michael@0 117
michael@0 118 if (typeof func !== "function")
michael@0 119 do_throw("string callbacks no longer accepted; use a function!");
michael@0 120
michael@0 121 this._func = func;
michael@0 122 this._start = Date.now();
michael@0 123 this._delay = delay;
michael@0 124
michael@0 125 var timer = Components.classes["@mozilla.org/timer;1"]
michael@0 126 .createInstance(Components.interfaces.nsITimer);
michael@0 127 timer.initWithCallback(this, delay + _timerFuzz, timer.TYPE_ONE_SHOT);
michael@0 128
michael@0 129 // Keep timer alive until it fires
michael@0 130 _pendingTimers.push(timer);
michael@0 131 }
michael@0 132 _Timer.prototype = {
michael@0 133 QueryInterface: function(iid) {
michael@0 134 if (iid.equals(Components.interfaces.nsITimerCallback) ||
michael@0 135 iid.equals(Components.interfaces.nsISupports))
michael@0 136 return this;
michael@0 137
michael@0 138 throw Components.results.NS_ERROR_NO_INTERFACE;
michael@0 139 },
michael@0 140
michael@0 141 notify: function(timer) {
michael@0 142 _pendingTimers.splice(_pendingTimers.indexOf(timer), 1);
michael@0 143
michael@0 144 // The current nsITimer implementation can undershoot, but even if it
michael@0 145 // couldn't, paranoia is probably a virtue here given the potential for
michael@0 146 // random orange on tinderboxen.
michael@0 147 var end = Date.now();
michael@0 148 var elapsed = end - this._start;
michael@0 149 if (elapsed >= this._delay) {
michael@0 150 try {
michael@0 151 this._func.call(null);
michael@0 152 } catch (e) {
michael@0 153 do_throw("exception thrown from do_timeout callback: " + e);
michael@0 154 }
michael@0 155 return;
michael@0 156 }
michael@0 157
michael@0 158 // Timer undershot, retry with a little overshoot to try to avoid more
michael@0 159 // undershoots.
michael@0 160 var newDelay = this._delay - elapsed;
michael@0 161 do_timeout(newDelay, this._func);
michael@0 162 }
michael@0 163 };
michael@0 164
michael@0 165 function _do_main() {
michael@0 166 if (_quit)
michael@0 167 return;
michael@0 168
michael@0 169 _log("test_info",
michael@0 170 {_message: "TEST-INFO | (xpcshell/head.js) | running event loop\n"});
michael@0 171
michael@0 172 var thr = Components.classes["@mozilla.org/thread-manager;1"]
michael@0 173 .getService().currentThread;
michael@0 174
michael@0 175 while (!_quit)
michael@0 176 thr.processNextEvent(true);
michael@0 177
michael@0 178 while (thr.hasPendingEvents())
michael@0 179 thr.processNextEvent(true);
michael@0 180 }
michael@0 181
michael@0 182 function _do_quit() {
michael@0 183 _log("test_info",
michael@0 184 {_message: "TEST-INFO | (xpcshell/head.js) | exiting test\n"});
michael@0 185 _Promise.Debugging.flushUncaughtErrors();
michael@0 186 _quit = true;
michael@0 187 }
michael@0 188
michael@0 189 function _format_exception_stack(stack) {
michael@0 190 if (typeof stack == "object" && stack.caller) {
michael@0 191 let frame = stack;
michael@0 192 let strStack = "";
michael@0 193 while (frame != null) {
michael@0 194 strStack += frame + "\n";
michael@0 195 frame = frame.caller;
michael@0 196 }
michael@0 197 stack = strStack;
michael@0 198 }
michael@0 199 // frame is of the form "fname@file:line"
michael@0 200 let frame_regexp = new RegExp("(.*)@(.*):(\\d*)", "g");
michael@0 201 return stack.split("\n").reduce(function(stack_msg, frame) {
michael@0 202 if (frame) {
michael@0 203 let parts = frame_regexp.exec(frame);
michael@0 204 if (parts) {
michael@0 205 let [ _, func, file, line ] = parts;
michael@0 206 return stack_msg + "JS frame :: " + file + " :: " +
michael@0 207 (func || "anonymous") + " :: line " + line + "\n";
michael@0 208 }
michael@0 209 else { /* Could be a -e (command line string) style location. */
michael@0 210 return stack_msg + "JS frame :: " + frame + "\n";
michael@0 211 }
michael@0 212 }
michael@0 213 return stack_msg;
michael@0 214 }, "");
michael@0 215 }
michael@0 216
michael@0 217 /**
michael@0 218 * Overrides idleService with a mock. Idle is commonly used for maintenance
michael@0 219 * tasks, thus if a test uses a service that requires the idle service, it will
michael@0 220 * start handling them.
michael@0 221 * This behaviour would cause random failures and slowdown tests execution,
michael@0 222 * for example by running database vacuum or cleanups for each test.
michael@0 223 *
michael@0 224 * @note Idle service is overridden by default. If a test requires it, it will
michael@0 225 * have to call do_get_idle() function at least once before use.
michael@0 226 */
michael@0 227 var _fakeIdleService = {
michael@0 228 get registrar() {
michael@0 229 delete this.registrar;
michael@0 230 return this.registrar =
michael@0 231 Components.manager.QueryInterface(Components.interfaces.nsIComponentRegistrar);
michael@0 232 },
michael@0 233 contractID: "@mozilla.org/widget/idleservice;1",
michael@0 234 get CID() this.registrar.contractIDToCID(this.contractID),
michael@0 235
michael@0 236 activate: function FIS_activate()
michael@0 237 {
michael@0 238 if (!this.originalFactory) {
michael@0 239 // Save original factory.
michael@0 240 this.originalFactory =
michael@0 241 Components.manager.getClassObject(Components.classes[this.contractID],
michael@0 242 Components.interfaces.nsIFactory);
michael@0 243 // Unregister original factory.
michael@0 244 this.registrar.unregisterFactory(this.CID, this.originalFactory);
michael@0 245 // Replace with the mock.
michael@0 246 this.registrar.registerFactory(this.CID, "Fake Idle Service",
michael@0 247 this.contractID, this.factory
michael@0 248 );
michael@0 249 }
michael@0 250 },
michael@0 251
michael@0 252 deactivate: function FIS_deactivate()
michael@0 253 {
michael@0 254 if (this.originalFactory) {
michael@0 255 // Unregister the mock.
michael@0 256 this.registrar.unregisterFactory(this.CID, this.factory);
michael@0 257 // Restore original factory.
michael@0 258 this.registrar.registerFactory(this.CID, "Idle Service",
michael@0 259 this.contractID, this.originalFactory);
michael@0 260 delete this.originalFactory;
michael@0 261 }
michael@0 262 },
michael@0 263
michael@0 264 factory: {
michael@0 265 // nsIFactory
michael@0 266 createInstance: function (aOuter, aIID)
michael@0 267 {
michael@0 268 if (aOuter) {
michael@0 269 throw Components.results.NS_ERROR_NO_AGGREGATION;
michael@0 270 }
michael@0 271 return _fakeIdleService.QueryInterface(aIID);
michael@0 272 },
michael@0 273 lockFactory: function (aLock) {
michael@0 274 throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
michael@0 275 },
michael@0 276 QueryInterface: function(aIID) {
michael@0 277 if (aIID.equals(Components.interfaces.nsIFactory) ||
michael@0 278 aIID.equals(Components.interfaces.nsISupports)) {
michael@0 279 return this;
michael@0 280 }
michael@0 281 throw Components.results.NS_ERROR_NO_INTERFACE;
michael@0 282 }
michael@0 283 },
michael@0 284
michael@0 285 // nsIIdleService
michael@0 286 get idleTime() 0,
michael@0 287 addIdleObserver: function () {},
michael@0 288 removeIdleObserver: function () {},
michael@0 289
michael@0 290 QueryInterface: function(aIID) {
michael@0 291 // Useful for testing purposes, see test_get_idle.js.
michael@0 292 if (aIID.equals(Components.interfaces.nsIFactory)) {
michael@0 293 return this.factory;
michael@0 294 }
michael@0 295 if (aIID.equals(Components.interfaces.nsIIdleService) ||
michael@0 296 aIID.equals(Components.interfaces.nsISupports)) {
michael@0 297 return this;
michael@0 298 }
michael@0 299 throw Components.results.NS_ERROR_NO_INTERFACE;
michael@0 300 }
michael@0 301 }
michael@0 302
michael@0 303 /**
michael@0 304 * Restores the idle service factory if needed and returns the service's handle.
michael@0 305 * @return A handle to the idle service.
michael@0 306 */
michael@0 307 function do_get_idle() {
michael@0 308 _fakeIdleService.deactivate();
michael@0 309 return Components.classes[_fakeIdleService.contractID]
michael@0 310 .getService(Components.interfaces.nsIIdleService);
michael@0 311 }
michael@0 312
michael@0 313 // Map resource://test/ to current working directory and
michael@0 314 // resource://testing-common/ to the shared test modules directory.
michael@0 315 function _register_protocol_handlers() {
michael@0 316 let (ios = Components.classes["@mozilla.org/network/io-service;1"]
michael@0 317 .getService(Components.interfaces.nsIIOService)) {
michael@0 318 let protocolHandler =
michael@0 319 ios.getProtocolHandler("resource")
michael@0 320 .QueryInterface(Components.interfaces.nsIResProtocolHandler);
michael@0 321 let curDirURI = ios.newFileURI(do_get_cwd());
michael@0 322 protocolHandler.setSubstitution("test", curDirURI);
michael@0 323
michael@0 324 if (this._TESTING_MODULES_DIR) {
michael@0 325 let modulesFile = Components.classes["@mozilla.org/file/local;1"].
michael@0 326 createInstance(Components.interfaces.nsILocalFile);
michael@0 327 modulesFile.initWithPath(_TESTING_MODULES_DIR);
michael@0 328
michael@0 329 if (!modulesFile.exists()) {
michael@0 330 throw new Error("Specified modules directory does not exist: " +
michael@0 331 _TESTING_MODULES_DIR);
michael@0 332 }
michael@0 333
michael@0 334 if (!modulesFile.isDirectory()) {
michael@0 335 throw new Error("Specified modules directory is not a directory: " +
michael@0 336 _TESTING_MODULES_DIR);
michael@0 337 }
michael@0 338
michael@0 339 let modulesURI = ios.newFileURI(modulesFile);
michael@0 340
michael@0 341 protocolHandler.setSubstitution("testing-common", modulesURI);
michael@0 342 }
michael@0 343 }
michael@0 344 }
michael@0 345
michael@0 346 function _execute_test() {
michael@0 347 _register_protocol_handlers();
michael@0 348
michael@0 349 // Override idle service by default.
michael@0 350 // Call do_get_idle() to restore the factory and get the service.
michael@0 351 _fakeIdleService.activate();
michael@0 352
michael@0 353 _Promise.Debugging.clearUncaughtErrorObservers();
michael@0 354 _Promise.Debugging.addUncaughtErrorObserver(function observer({message, date, fileName, stack, lineNumber}) {
michael@0 355 let text = "Once bug 976205 has landed, THIS ERROR WILL CAUSE A TEST FAILURE.\n" +
michael@0 356 " A promise chain failed to handle a rejection: " +
michael@0 357 message + " - rejection date: " + date;
michael@0 358 _log_message_with_stack("test_known_fail",
michael@0 359 text, stack, fileName);
michael@0 360 });
michael@0 361
michael@0 362 // _HEAD_FILES is dynamically defined by <runxpcshelltests.py>.
michael@0 363 _load_files(_HEAD_FILES);
michael@0 364 // _TEST_FILE is dynamically defined by <runxpcshelltests.py>.
michael@0 365 _load_files(_TEST_FILE);
michael@0 366
michael@0 367 // Support a common assertion library, Assert.jsm.
michael@0 368 let Assert = Components.utils.import("resource://testing-common/Assert.jsm", null).Assert;
michael@0 369 // Pass a custom report function for xpcshell-test style reporting.
michael@0 370 let assertImpl = new Assert(function(err, message, stack) {
michael@0 371 if (err) {
michael@0 372 do_report_result(false, err.message, err.stack);
michael@0 373 } else {
michael@0 374 do_report_result(true, message, stack);
michael@0 375 }
michael@0 376 });
michael@0 377 // Allow Assert.jsm methods to be tacked to the current scope.
michael@0 378 this.export_assertions = function() {
michael@0 379 for (let func in assertImpl) {
michael@0 380 this[func] = assertImpl[func].bind(assertImpl);
michael@0 381 }
michael@0 382 };
michael@0 383 this.Assert = assertImpl;
michael@0 384
michael@0 385 try {
michael@0 386 do_test_pending("MAIN run_test");
michael@0 387 run_test();
michael@0 388 do_test_finished("MAIN run_test");
michael@0 389 _do_main();
michael@0 390 } catch (e) {
michael@0 391 _passed = false;
michael@0 392 // do_check failures are already logged and set _quit to true and throw
michael@0 393 // NS_ERROR_ABORT. If both of those are true it is likely this exception
michael@0 394 // has already been logged so there is no need to log it again. It's
michael@0 395 // possible that this will mask an NS_ERROR_ABORT that happens after a
michael@0 396 // do_check failure though.
michael@0 397 if (!_quit || e != Components.results.NS_ERROR_ABORT) {
michael@0 398 let msgObject = {};
michael@0 399 if (e.fileName) {
michael@0 400 msgObject.source_file = e.fileName;
michael@0 401 if (e.lineNumber) {
michael@0 402 msgObject.line_number = e.lineNumber;
michael@0 403 }
michael@0 404 } else {
michael@0 405 msgObject.source_file = "xpcshell/head.js";
michael@0 406 }
michael@0 407 msgObject.diagnostic = _exception_message(e);
michael@0 408 if (e.stack) {
michael@0 409 msgObject.diagnostic += " - See following stack:\n";
michael@0 410 msgObject.stack = _format_exception_stack(e.stack);
michael@0 411 }
michael@0 412 _log("test_unexpected_fail", msgObject);
michael@0 413 }
michael@0 414 }
michael@0 415
michael@0 416 // _TAIL_FILES is dynamically defined by <runxpcshelltests.py>.
michael@0 417 _load_files(_TAIL_FILES);
michael@0 418
michael@0 419 // Execute all of our cleanup functions.
michael@0 420 let reportCleanupError = function(ex) {
michael@0 421 let stack, filename;
michael@0 422 if (ex && typeof ex == "object" && "stack" in ex) {
michael@0 423 stack = ex.stack;
michael@0 424 } else {
michael@0 425 stack = Components.stack.caller;
michael@0 426 }
michael@0 427 if (stack instanceof Components.interfaces.nsIStackFrame) {
michael@0 428 filename = stack.filename;
michael@0 429 } else if (ex.fileName) {
michael@0 430 filename = ex.fileName;
michael@0 431 }
michael@0 432 _log_message_with_stack("test_unexpected_fail",
michael@0 433 ex, stack, filename);
michael@0 434 };
michael@0 435
michael@0 436 let func;
michael@0 437 while ((func = _cleanupFunctions.pop())) {
michael@0 438 let result;
michael@0 439 try {
michael@0 440 result = func();
michael@0 441 } catch (ex) {
michael@0 442 reportCleanupError(ex);
michael@0 443 continue;
michael@0 444 }
michael@0 445 if (result && typeof result == "object"
michael@0 446 && "then" in result && typeof result.then == "function") {
michael@0 447 // This is a promise, wait until it is satisfied before proceeding
michael@0 448 let complete = false;
michael@0 449 let promise = result.then(null, reportCleanupError);
michael@0 450 promise = promise.then(() => complete = true);
michael@0 451 let thr = Components.classes["@mozilla.org/thread-manager;1"]
michael@0 452 .getService().currentThread;
michael@0 453 while (!complete) {
michael@0 454 thr.processNextEvent(true);
michael@0 455 }
michael@0 456 }
michael@0 457 }
michael@0 458
michael@0 459 // Restore idle service to avoid leaks.
michael@0 460 _fakeIdleService.deactivate();
michael@0 461
michael@0 462 if (!_passed)
michael@0 463 return;
michael@0 464
michael@0 465 var truePassedChecks = _passedChecks - _falsePassedChecks;
michael@0 466 if (truePassedChecks > 0) {
michael@0 467 _log("test_pass",
michael@0 468 {_message: "TEST-PASS | (xpcshell/head.js) | " + truePassedChecks + " (+ " +
michael@0 469 _falsePassedChecks + ") check(s) passed\n",
michael@0 470 source_file: _TEST_FILE,
michael@0 471 passed_checks: truePassedChecks});
michael@0 472 _log("test_info",
michael@0 473 {_message: "TEST-INFO | (xpcshell/head.js) | " + _todoChecks +
michael@0 474 " check(s) todo\n",
michael@0 475 source_file: _TEST_FILE,
michael@0 476 todo_checks: _todoChecks});
michael@0 477 } else {
michael@0 478 // ToDo: switch to TEST-UNEXPECTED-FAIL when all tests have been updated. (Bug 496443)
michael@0 479 _log("test_info",
michael@0 480 {_message: "TEST-INFO | (xpcshell/head.js) | No (+ " + _falsePassedChecks +
michael@0 481 ") checks actually run\n",
michael@0 482 source_file: _TEST_FILE});
michael@0 483 }
michael@0 484 }
michael@0 485
michael@0 486 /**
michael@0 487 * Loads files.
michael@0 488 *
michael@0 489 * @param aFiles Array of files to load.
michael@0 490 */
michael@0 491 function _load_files(aFiles) {
michael@0 492 function loadTailFile(element, index, array) {
michael@0 493 try {
michael@0 494 load(element);
michael@0 495 } catch (e if e instanceof SyntaxError) {
michael@0 496 _log("javascript_error",
michael@0 497 {_message: "TEST-UNEXPECTED-FAIL | (xpcshell/head.js) | Source file " + element + " contains SyntaxError",
michael@0 498 diagnostic: _exception_message(e),
michael@0 499 source_file: element,
michael@0 500 stack: _format_exception_stack(e.stack)});
michael@0 501 } catch (e) {
michael@0 502 _log("javascript_error",
michael@0 503 {_message: "TEST-UNEXPECTED-FAIL | (xpcshell/head.js) | Source file " + element + " contains an error",
michael@0 504 diagnostic: _exception_message(e),
michael@0 505 source_file: element,
michael@0 506 stack: _format_exception_stack(e.stack)});
michael@0 507 }
michael@0 508 }
michael@0 509
michael@0 510 aFiles.forEach(loadTailFile);
michael@0 511 }
michael@0 512
michael@0 513 function _wrap_with_quotes_if_necessary(val) {
michael@0 514 return typeof val == "string" ? '"' + val + '"' : val;
michael@0 515 }
michael@0 516
michael@0 517 /************** Functions to be used from the tests **************/
michael@0 518
michael@0 519 /**
michael@0 520 * Prints a message to the output log.
michael@0 521 */
michael@0 522 function do_print(msg) {
michael@0 523 var caller_stack = Components.stack.caller;
michael@0 524 msg = _wrap_with_quotes_if_necessary(msg);
michael@0 525 _log("test_info",
michael@0 526 {source_file: caller_stack.filename,
michael@0 527 diagnostic: msg});
michael@0 528
michael@0 529 }
michael@0 530
michael@0 531 /**
michael@0 532 * Calls the given function at least the specified number of milliseconds later.
michael@0 533 * The callback will not undershoot the given time, but it might overshoot --
michael@0 534 * don't expect precision!
michael@0 535 *
michael@0 536 * @param delay : uint
michael@0 537 * the number of milliseconds to delay
michael@0 538 * @param callback : function() : void
michael@0 539 * the function to call
michael@0 540 */
michael@0 541 function do_timeout(delay, func) {
michael@0 542 new _Timer(func, Number(delay));
michael@0 543 }
michael@0 544
michael@0 545 function do_execute_soon(callback, aName) {
michael@0 546 let funcName = (aName ? aName : callback.name);
michael@0 547 do_test_pending(funcName);
michael@0 548 var tm = Components.classes["@mozilla.org/thread-manager;1"]
michael@0 549 .getService(Components.interfaces.nsIThreadManager);
michael@0 550
michael@0 551 tm.mainThread.dispatch({
michael@0 552 run: function() {
michael@0 553 try {
michael@0 554 callback();
michael@0 555 } catch (e) {
michael@0 556 // do_check failures are already logged and set _quit to true and throw
michael@0 557 // NS_ERROR_ABORT. If both of those are true it is likely this exception
michael@0 558 // has already been logged so there is no need to log it again. It's
michael@0 559 // possible that this will mask an NS_ERROR_ABORT that happens after a
michael@0 560 // do_check failure though.
michael@0 561 if (!_quit || e != Components.results.NS_ERROR_ABORT) {
michael@0 562 if (e.stack) {
michael@0 563 _log("javascript_error",
michael@0 564 {source_file: "xpcshell/head.js",
michael@0 565 diagnostic: _exception_message(e) + " - See following stack:",
michael@0 566 stack: _format_exception_stack(e.stack)});
michael@0 567 } else {
michael@0 568 _log("javascript_error",
michael@0 569 {source_file: "xpcshell/head.js",
michael@0 570 diagnostic: _exception_message(e)});
michael@0 571 }
michael@0 572 _do_quit();
michael@0 573 }
michael@0 574 }
michael@0 575 finally {
michael@0 576 do_test_finished(funcName);
michael@0 577 }
michael@0 578 }
michael@0 579 }, Components.interfaces.nsIThread.DISPATCH_NORMAL);
michael@0 580 }
michael@0 581
michael@0 582 /**
michael@0 583 * Shows an error message and the current stack and aborts the test.
michael@0 584 *
michael@0 585 * @param error A message string or an Error object.
michael@0 586 * @param stack null or nsIStackFrame object or a string containing
michael@0 587 * \n separated stack lines (as in Error().stack).
michael@0 588 */
michael@0 589 function do_throw(error, stack) {
michael@0 590 let filename = "";
michael@0 591 // If we didn't get passed a stack, maybe the error has one
michael@0 592 // otherwise get it from our call context
michael@0 593 stack = stack || error.stack || Components.stack.caller;
michael@0 594
michael@0 595 if (stack instanceof Components.interfaces.nsIStackFrame)
michael@0 596 filename = stack.filename;
michael@0 597 else if (error.fileName)
michael@0 598 filename = error.fileName;
michael@0 599
michael@0 600 _log_message_with_stack("test_unexpected_fail",
michael@0 601 error, stack, filename);
michael@0 602
michael@0 603 _passed = false;
michael@0 604 _do_quit();
michael@0 605 throw Components.results.NS_ERROR_ABORT;
michael@0 606 }
michael@0 607
michael@0 608 function _format_stack(stack) {
michael@0 609 if (stack instanceof Components.interfaces.nsIStackFrame) {
michael@0 610 let stack_msg = "";
michael@0 611 let frame = stack;
michael@0 612 while (frame != null) {
michael@0 613 stack_msg += frame + "\n";
michael@0 614 frame = frame.caller;
michael@0 615 }
michael@0 616 return stack_msg;
michael@0 617 }
michael@0 618 return "" + stack;
michael@0 619 }
michael@0 620
michael@0 621 function do_throw_todo(text, stack) {
michael@0 622 if (!stack)
michael@0 623 stack = Components.stack.caller;
michael@0 624
michael@0 625 _passed = false;
michael@0 626 _log_message_with_stack("test_unexpected_pass",
michael@0 627 text, stack, stack.filename);
michael@0 628 _do_quit();
michael@0 629 throw Components.results.NS_ERROR_ABORT;
michael@0 630 }
michael@0 631
michael@0 632 // Make a nice display string from an object that behaves
michael@0 633 // like Error
michael@0 634 function _exception_message(ex) {
michael@0 635 let message = "";
michael@0 636 if (ex.name) {
michael@0 637 message = ex.name + ": ";
michael@0 638 }
michael@0 639 if (ex.message) {
michael@0 640 message += ex.message;
michael@0 641 }
michael@0 642 if (ex.fileName) {
michael@0 643 message += (" at " + ex.fileName);
michael@0 644 if (ex.lineNumber) {
michael@0 645 message += (":" + ex.lineNumber);
michael@0 646 }
michael@0 647 }
michael@0 648 if (message !== "") {
michael@0 649 return message;
michael@0 650 }
michael@0 651 // Force ex to be stringified
michael@0 652 return "" + ex;
michael@0 653 }
michael@0 654
michael@0 655 function _log_message_with_stack(action, ex, stack, filename, text) {
michael@0 656 if (stack) {
michael@0 657 _log(action,
michael@0 658 {diagnostic: (text ? text : "") +
michael@0 659 _exception_message(ex) +
michael@0 660 " - See following stack:",
michael@0 661 source_file: filename,
michael@0 662 stack: _format_stack(stack)});
michael@0 663 } else {
michael@0 664 _log(action,
michael@0 665 {diagnostic: (text ? text : "") +
michael@0 666 _exception_message(ex),
michael@0 667 source_file: filename});
michael@0 668 }
michael@0 669 }
michael@0 670
michael@0 671 function do_report_unexpected_exception(ex, text) {
michael@0 672 var caller_stack = Components.stack.caller;
michael@0 673 text = text ? text + " - " : "";
michael@0 674
michael@0 675 _passed = false;
michael@0 676 _log_message_with_stack("test_unexpected_fail", ex, ex.stack,
michael@0 677 caller_stack.filename, text + "Unexpected exception ");
michael@0 678 _do_quit();
michael@0 679 throw Components.results.NS_ERROR_ABORT;
michael@0 680 }
michael@0 681
michael@0 682 function do_note_exception(ex, text) {
michael@0 683 var caller_stack = Components.stack.caller;
michael@0 684 text = text ? text + " - " : "";
michael@0 685
michael@0 686 _log_message_with_stack("test_info", ex, ex.stack,
michael@0 687 caller_stack.filename, text + "Swallowed exception ");
michael@0 688 }
michael@0 689
michael@0 690 function _do_check_neq(left, right, stack, todo) {
michael@0 691 if (!stack)
michael@0 692 stack = Components.stack.caller;
michael@0 693
michael@0 694 var text = _wrap_with_quotes_if_necessary(left) + " != " +
michael@0 695 _wrap_with_quotes_if_necessary(right);
michael@0 696 do_report_result(left != right, text, stack, todo);
michael@0 697 }
michael@0 698
michael@0 699 function do_check_neq(left, right, stack) {
michael@0 700 if (!stack)
michael@0 701 stack = Components.stack.caller;
michael@0 702
michael@0 703 _do_check_neq(left, right, stack, false);
michael@0 704 }
michael@0 705
michael@0 706 function todo_check_neq(left, right, stack) {
michael@0 707 if (!stack)
michael@0 708 stack = Components.stack.caller;
michael@0 709
michael@0 710 _do_check_neq(left, right, stack, true);
michael@0 711 }
michael@0 712
michael@0 713 function do_report_result(passed, text, stack, todo) {
michael@0 714 if (passed) {
michael@0 715 if (todo) {
michael@0 716 do_throw_todo(text, stack);
michael@0 717 } else {
michael@0 718 ++_passedChecks;
michael@0 719 _log("test_pass",
michael@0 720 {source_file: stack.filename,
michael@0 721 test_name: stack.name,
michael@0 722 line_number: stack.lineNumber,
michael@0 723 diagnostic: "[" + stack.name + " : " + stack.lineNumber + "] " +
michael@0 724 text + "\n"});
michael@0 725 }
michael@0 726 } else {
michael@0 727 if (todo) {
michael@0 728 ++_todoChecks;
michael@0 729 _log("test_known_fail",
michael@0 730 {source_file: stack.filename,
michael@0 731 test_name: stack.name,
michael@0 732 line_number: stack.lineNumber,
michael@0 733 diagnostic: "[" + stack.name + " : " + stack.lineNumber + "] " +
michael@0 734 text + "\n"});
michael@0 735 } else {
michael@0 736 do_throw(text, stack);
michael@0 737 }
michael@0 738 }
michael@0 739 }
michael@0 740
michael@0 741 function _do_check_eq(left, right, stack, todo) {
michael@0 742 if (!stack)
michael@0 743 stack = Components.stack.caller;
michael@0 744
michael@0 745 var text = _wrap_with_quotes_if_necessary(left) + " == " +
michael@0 746 _wrap_with_quotes_if_necessary(right);
michael@0 747 do_report_result(left == right, text, stack, todo);
michael@0 748 }
michael@0 749
michael@0 750 function do_check_eq(left, right, stack) {
michael@0 751 if (!stack)
michael@0 752 stack = Components.stack.caller;
michael@0 753
michael@0 754 _do_check_eq(left, right, stack, false);
michael@0 755 }
michael@0 756
michael@0 757 function todo_check_eq(left, right, stack) {
michael@0 758 if (!stack)
michael@0 759 stack = Components.stack.caller;
michael@0 760
michael@0 761 _do_check_eq(left, right, stack, true);
michael@0 762 }
michael@0 763
michael@0 764 function do_check_true(condition, stack) {
michael@0 765 if (!stack)
michael@0 766 stack = Components.stack.caller;
michael@0 767
michael@0 768 do_check_eq(condition, true, stack);
michael@0 769 }
michael@0 770
michael@0 771 function todo_check_true(condition, stack) {
michael@0 772 if (!stack)
michael@0 773 stack = Components.stack.caller;
michael@0 774
michael@0 775 todo_check_eq(condition, true, stack);
michael@0 776 }
michael@0 777
michael@0 778 function do_check_false(condition, stack) {
michael@0 779 if (!stack)
michael@0 780 stack = Components.stack.caller;
michael@0 781
michael@0 782 do_check_eq(condition, false, stack);
michael@0 783 }
michael@0 784
michael@0 785 function todo_check_false(condition, stack) {
michael@0 786 if (!stack)
michael@0 787 stack = Components.stack.caller;
michael@0 788
michael@0 789 todo_check_eq(condition, false, stack);
michael@0 790 }
michael@0 791
michael@0 792 function do_check_null(condition, stack=Components.stack.caller) {
michael@0 793 do_check_eq(condition, null, stack);
michael@0 794 }
michael@0 795
michael@0 796 function todo_check_null(condition, stack=Components.stack.caller) {
michael@0 797 todo_check_eq(condition, null, stack);
michael@0 798 }
michael@0 799
michael@0 800 /**
michael@0 801 * Check that |value| matches |pattern|.
michael@0 802 *
michael@0 803 * A |value| matches a pattern |pattern| if any one of the following is true:
michael@0 804 *
michael@0 805 * - |value| and |pattern| are both objects; |pattern|'s enumerable
michael@0 806 * properties' values are valid patterns; and for each enumerable
michael@0 807 * property |p| of |pattern|, plus 'length' if present at all, |value|
michael@0 808 * has a property |p| whose value matches |pattern.p|. Note that if |j|
michael@0 809 * has other properties not present in |p|, |j| may still match |p|.
michael@0 810 *
michael@0 811 * - |value| and |pattern| are equal string, numeric, or boolean literals
michael@0 812 *
michael@0 813 * - |pattern| is |undefined| (this is a wildcard pattern)
michael@0 814 *
michael@0 815 * - typeof |pattern| == "function", and |pattern(value)| is true.
michael@0 816 *
michael@0 817 * For example:
michael@0 818 *
michael@0 819 * do_check_matches({x:1}, {x:1}) // pass
michael@0 820 * do_check_matches({x:1}, {}) // fail: all pattern props required
michael@0 821 * do_check_matches({x:1}, {x:2}) // fail: values must match
michael@0 822 * do_check_matches({x:1}, {x:1, y:2}) // pass: extra props tolerated
michael@0 823 *
michael@0 824 * // Property order is irrelevant.
michael@0 825 * do_check_matches({x:"foo", y:"bar"}, {y:"bar", x:"foo"}) // pass
michael@0 826 *
michael@0 827 * do_check_matches({x:undefined}, {x:1}) // pass: 'undefined' is wildcard
michael@0 828 * do_check_matches({x:undefined}, {x:2})
michael@0 829 * do_check_matches({x:undefined}, {y:2}) // fail: 'x' must still be there
michael@0 830 *
michael@0 831 * // Patterns nest.
michael@0 832 * do_check_matches({a:1, b:{c:2,d:undefined}}, {a:1, b:{c:2,d:3}})
michael@0 833 *
michael@0 834 * // 'length' property counts, even if non-enumerable.
michael@0 835 * do_check_matches([3,4,5], [3,4,5]) // pass
michael@0 836 * do_check_matches([3,4,5], [3,5,5]) // fail; value doesn't match
michael@0 837 * do_check_matches([3,4,5], [3,4,5,6]) // fail; length doesn't match
michael@0 838 *
michael@0 839 * // functions in patterns get applied.
michael@0 840 * do_check_matches({foo:function (v) v.length == 2}, {foo:"hi"}) // pass
michael@0 841 * do_check_matches({foo:function (v) v.length == 2}, {bar:"hi"}) // fail
michael@0 842 * do_check_matches({foo:function (v) v.length == 2}, {foo:"hello"}) // fail
michael@0 843 *
michael@0 844 * // We don't check constructors, prototypes, or classes. However, if
michael@0 845 * // pattern has a 'length' property, we require values to match that as
michael@0 846 * // well, even if 'length' is non-enumerable in the pattern. So arrays
michael@0 847 * // are useful as patterns.
michael@0 848 * do_check_matches({0:0, 1:1, length:2}, [0,1]) // pass
michael@0 849 * do_check_matches({0:1}, [1,2]) // pass
michael@0 850 * do_check_matches([0], {0:0, length:1}) // pass
michael@0 851 *
michael@0 852 * Notes:
michael@0 853 *
michael@0 854 * The 'length' hack gives us reasonably intuitive handling of arrays.
michael@0 855 *
michael@0 856 * This is not a tight pattern-matcher; it's only good for checking data
michael@0 857 * from well-behaved sources. For example:
michael@0 858 * - By default, we don't mind values having extra properties.
michael@0 859 * - We don't check for proxies or getters.
michael@0 860 * - We don't check the prototype chain.
michael@0 861 * However, if you know the values are, say, JSON, which is pretty
michael@0 862 * well-behaved, and if you want to tolerate additional properties
michael@0 863 * appearing on the JSON for backward-compatibility, then do_check_matches
michael@0 864 * is ideal. If you do want to be more careful, you can use function
michael@0 865 * patterns to implement more stringent checks.
michael@0 866 */
michael@0 867 function do_check_matches(pattern, value, stack=Components.stack.caller, todo=false) {
michael@0 868 var matcher = pattern_matcher(pattern);
michael@0 869 var text = "VALUE: " + uneval(value) + "\nPATTERN: " + uneval(pattern) + "\n";
michael@0 870 var diagnosis = []
michael@0 871 if (matcher(value, diagnosis)) {
michael@0 872 do_report_result(true, "value matches pattern:\n" + text, stack, todo);
michael@0 873 } else {
michael@0 874 text = ("value doesn't match pattern:\n" +
michael@0 875 text +
michael@0 876 "DIAGNOSIS: " +
michael@0 877 format_pattern_match_failure(diagnosis[0]) + "\n");
michael@0 878 do_report_result(false, text, stack, todo);
michael@0 879 }
michael@0 880 }
michael@0 881
michael@0 882 function todo_check_matches(pattern, value, stack=Components.stack.caller) {
michael@0 883 do_check_matches(pattern, value, stack, true);
michael@0 884 }
michael@0 885
michael@0 886 // Return a pattern-matching function of one argument, |value|, that
michael@0 887 // returns true if |value| matches |pattern|.
michael@0 888 //
michael@0 889 // If the pattern doesn't match, and the pattern-matching function was
michael@0 890 // passed its optional |diagnosis| argument, the pattern-matching function
michael@0 891 // sets |diagnosis|'s '0' property to a JSON-ish description of the portion
michael@0 892 // of the pattern that didn't match, which can be formatted legibly by
michael@0 893 // format_pattern_match_failure.
michael@0 894 function pattern_matcher(pattern) {
michael@0 895 function explain(diagnosis, reason) {
michael@0 896 if (diagnosis) {
michael@0 897 diagnosis[0] = reason;
michael@0 898 }
michael@0 899 return false;
michael@0 900 }
michael@0 901 if (typeof pattern == "function") {
michael@0 902 return pattern;
michael@0 903 } else if (typeof pattern == "object" && pattern) {
michael@0 904 var matchers = [[p, pattern_matcher(pattern[p])] for (p in pattern)];
michael@0 905 // Kludge: include 'length', if not enumerable. (If it is enumerable,
michael@0 906 // we picked it up in the array comprehension, above.
michael@0 907 ld = Object.getOwnPropertyDescriptor(pattern, 'length');
michael@0 908 if (ld && !ld.enumerable) {
michael@0 909 matchers.push(['length', pattern_matcher(pattern.length)])
michael@0 910 }
michael@0 911 return function (value, diagnosis) {
michael@0 912 if (!(value && typeof value == "object")) {
michael@0 913 return explain(diagnosis, "value not object");
michael@0 914 }
michael@0 915 for (let [p, m] of matchers) {
michael@0 916 var element_diagnosis = [];
michael@0 917 if (!(p in value && m(value[p], element_diagnosis))) {
michael@0 918 return explain(diagnosis, { property:p,
michael@0 919 diagnosis:element_diagnosis[0] });
michael@0 920 }
michael@0 921 }
michael@0 922 return true;
michael@0 923 };
michael@0 924 } else if (pattern === undefined) {
michael@0 925 return function(value) { return true; };
michael@0 926 } else {
michael@0 927 return function (value, diagnosis) {
michael@0 928 if (value !== pattern) {
michael@0 929 return explain(diagnosis, "pattern " + uneval(pattern) + " not === to value " + uneval(value));
michael@0 930 }
michael@0 931 return true;
michael@0 932 };
michael@0 933 }
michael@0 934 }
michael@0 935
michael@0 936 // Format an explanation for a pattern match failure, as stored in the
michael@0 937 // second argument to a matching function.
michael@0 938 function format_pattern_match_failure(diagnosis, indent="") {
michael@0 939 var a;
michael@0 940 if (!diagnosis) {
michael@0 941 a = "Matcher did not explain reason for mismatch.";
michael@0 942 } else if (typeof diagnosis == "string") {
michael@0 943 a = diagnosis;
michael@0 944 } else if (diagnosis.property) {
michael@0 945 a = "Property " + uneval(diagnosis.property) + " of object didn't match:\n";
michael@0 946 a += format_pattern_match_failure(diagnosis.diagnosis, indent + " ");
michael@0 947 }
michael@0 948 return indent + a;
michael@0 949 }
michael@0 950
michael@0 951 // Check that |func| throws an nsIException that has
michael@0 952 // |Components.results[resultName]| as the value of its 'result' property.
michael@0 953 function do_check_throws_nsIException(func, resultName,
michael@0 954 stack=Components.stack.caller, todo=false)
michael@0 955 {
michael@0 956 let expected = Components.results[resultName];
michael@0 957 if (typeof expected !== 'number') {
michael@0 958 do_throw("do_check_throws_nsIException requires a Components.results" +
michael@0 959 " property name, not " + uneval(resultName), stack);
michael@0 960 }
michael@0 961
michael@0 962 let msg = ("do_check_throws_nsIException: func should throw" +
michael@0 963 " an nsIException whose 'result' is Components.results." +
michael@0 964 resultName);
michael@0 965
michael@0 966 try {
michael@0 967 func();
michael@0 968 } catch (ex) {
michael@0 969 if (!(ex instanceof Components.interfaces.nsIException) ||
michael@0 970 ex.result !== expected) {
michael@0 971 do_report_result(false, msg + ", threw " + legible_exception(ex) +
michael@0 972 " instead", stack, todo);
michael@0 973 }
michael@0 974
michael@0 975 do_report_result(true, msg, stack, todo);
michael@0 976 return;
michael@0 977 }
michael@0 978
michael@0 979 // Call this here, not in the 'try' clause, so do_report_result's own
michael@0 980 // throw doesn't get caught by our 'catch' clause.
michael@0 981 do_report_result(false, msg + ", but returned normally", stack, todo);
michael@0 982 }
michael@0 983
michael@0 984 // Produce a human-readable form of |exception|. This looks up
michael@0 985 // Components.results values, tries toString methods, and so on.
michael@0 986 function legible_exception(exception)
michael@0 987 {
michael@0 988 switch (typeof exception) {
michael@0 989 case 'object':
michael@0 990 if (exception instanceof Components.interfaces.nsIException) {
michael@0 991 return "nsIException instance: " + uneval(exception.toString());
michael@0 992 }
michael@0 993 return exception.toString();
michael@0 994
michael@0 995 case 'number':
michael@0 996 for (let name in Components.results) {
michael@0 997 if (exception === Components.results[name]) {
michael@0 998 return "Components.results." + name;
michael@0 999 }
michael@0 1000 }
michael@0 1001
michael@0 1002 // Fall through.
michael@0 1003 default:
michael@0 1004 return uneval(exception);
michael@0 1005 }
michael@0 1006 }
michael@0 1007
michael@0 1008 function do_check_instanceof(value, constructor,
michael@0 1009 stack=Components.stack.caller, todo=false) {
michael@0 1010 do_report_result(value instanceof constructor,
michael@0 1011 "value should be an instance of " + constructor.name,
michael@0 1012 stack, todo);
michael@0 1013 }
michael@0 1014
michael@0 1015 function todo_check_instanceof(value, constructor,
michael@0 1016 stack=Components.stack.caller) {
michael@0 1017 do_check_instanceof(value, constructor, stack, true);
michael@0 1018 }
michael@0 1019
michael@0 1020 function do_test_pending(aName) {
michael@0 1021 ++_tests_pending;
michael@0 1022
michael@0 1023 _log("test_pending",
michael@0 1024 {_message: "TEST-INFO | (xpcshell/head.js) | test" +
michael@0 1025 (aName ? " " + aName : "") +
michael@0 1026 " pending (" + _tests_pending + ")\n"});
michael@0 1027 }
michael@0 1028
michael@0 1029 function do_test_finished(aName) {
michael@0 1030 _log("test_finish",
michael@0 1031 {_message: "TEST-INFO | (xpcshell/head.js) | test" +
michael@0 1032 (aName ? " " + aName : "") +
michael@0 1033 " finished (" + _tests_pending + ")\n"});
michael@0 1034 if (--_tests_pending == 0)
michael@0 1035 _do_quit();
michael@0 1036 }
michael@0 1037
michael@0 1038 function do_get_file(path, allowNonexistent) {
michael@0 1039 try {
michael@0 1040 let lf = Components.classes["@mozilla.org/file/directory_service;1"]
michael@0 1041 .getService(Components.interfaces.nsIProperties)
michael@0 1042 .get("CurWorkD", Components.interfaces.nsILocalFile);
michael@0 1043
michael@0 1044 let bits = path.split("/");
michael@0 1045 for (let i = 0; i < bits.length; i++) {
michael@0 1046 if (bits[i]) {
michael@0 1047 if (bits[i] == "..")
michael@0 1048 lf = lf.parent;
michael@0 1049 else
michael@0 1050 lf.append(bits[i]);
michael@0 1051 }
michael@0 1052 }
michael@0 1053
michael@0 1054 if (!allowNonexistent && !lf.exists()) {
michael@0 1055 // Not using do_throw(): caller will continue.
michael@0 1056 _passed = false;
michael@0 1057 var stack = Components.stack.caller;
michael@0 1058 _log("test_unexpected_fail",
michael@0 1059 {source_file: stack.filename,
michael@0 1060 test_name: stack.name,
michael@0 1061 line_number: stack.lineNumber,
michael@0 1062 diagnostic: "[" + stack.name + " : " + stack.lineNumber + "] " +
michael@0 1063 lf.path + " does not exist\n"});
michael@0 1064 }
michael@0 1065
michael@0 1066 return lf;
michael@0 1067 }
michael@0 1068 catch (ex) {
michael@0 1069 do_throw(ex.toString(), Components.stack.caller);
michael@0 1070 }
michael@0 1071
michael@0 1072 return null;
michael@0 1073 }
michael@0 1074
michael@0 1075 // do_get_cwd() isn't exactly self-explanatory, so provide a helper
michael@0 1076 function do_get_cwd() {
michael@0 1077 return do_get_file("");
michael@0 1078 }
michael@0 1079
michael@0 1080 function do_load_manifest(path) {
michael@0 1081 var lf = do_get_file(path);
michael@0 1082 const nsIComponentRegistrar = Components.interfaces.nsIComponentRegistrar;
michael@0 1083 do_check_true(Components.manager instanceof nsIComponentRegistrar);
michael@0 1084 // Previous do_check_true() is not a test check.
michael@0 1085 ++_falsePassedChecks;
michael@0 1086 Components.manager.autoRegister(lf);
michael@0 1087 }
michael@0 1088
michael@0 1089 /**
michael@0 1090 * Parse a DOM document.
michael@0 1091 *
michael@0 1092 * @param aPath File path to the document.
michael@0 1093 * @param aType Content type to use in DOMParser.
michael@0 1094 *
michael@0 1095 * @return nsIDOMDocument from the file.
michael@0 1096 */
michael@0 1097 function do_parse_document(aPath, aType) {
michael@0 1098 switch (aType) {
michael@0 1099 case "application/xhtml+xml":
michael@0 1100 case "application/xml":
michael@0 1101 case "text/xml":
michael@0 1102 break;
michael@0 1103
michael@0 1104 default:
michael@0 1105 do_throw("type: expected application/xhtml+xml, application/xml or text/xml," +
michael@0 1106 " got '" + aType + "'",
michael@0 1107 Components.stack.caller);
michael@0 1108 }
michael@0 1109
michael@0 1110 var lf = do_get_file(aPath);
michael@0 1111 const C_i = Components.interfaces;
michael@0 1112 const parserClass = "@mozilla.org/xmlextras/domparser;1";
michael@0 1113 const streamClass = "@mozilla.org/network/file-input-stream;1";
michael@0 1114 var stream = Components.classes[streamClass]
michael@0 1115 .createInstance(C_i.nsIFileInputStream);
michael@0 1116 stream.init(lf, -1, -1, C_i.nsIFileInputStream.CLOSE_ON_EOF);
michael@0 1117 var parser = Components.classes[parserClass]
michael@0 1118 .createInstance(C_i.nsIDOMParser);
michael@0 1119 var doc = parser.parseFromStream(stream, null, lf.fileSize, aType);
michael@0 1120 parser = null;
michael@0 1121 stream = null;
michael@0 1122 lf = null;
michael@0 1123 return doc;
michael@0 1124 }
michael@0 1125
michael@0 1126 /**
michael@0 1127 * Registers a function that will run when the test harness is done running all
michael@0 1128 * tests.
michael@0 1129 *
michael@0 1130 * @param aFunction
michael@0 1131 * The function to be called when the test harness has finished running.
michael@0 1132 */
michael@0 1133 function do_register_cleanup(aFunction)
michael@0 1134 {
michael@0 1135 _cleanupFunctions.push(aFunction);
michael@0 1136 }
michael@0 1137
michael@0 1138 /**
michael@0 1139 * Returns the directory for a temp dir, which is created by the
michael@0 1140 * test harness. Every test gets its own temp dir.
michael@0 1141 *
michael@0 1142 * @return nsILocalFile of the temporary directory
michael@0 1143 */
michael@0 1144 function do_get_tempdir() {
michael@0 1145 let env = Components.classes["@mozilla.org/process/environment;1"]
michael@0 1146 .getService(Components.interfaces.nsIEnvironment);
michael@0 1147 // the python harness sets this in the environment for us
michael@0 1148 let path = env.get("XPCSHELL_TEST_TEMP_DIR");
michael@0 1149 let file = Components.classes["@mozilla.org/file/local;1"]
michael@0 1150 .createInstance(Components.interfaces.nsILocalFile);
michael@0 1151 file.initWithPath(path);
michael@0 1152 return file;
michael@0 1153 }
michael@0 1154
michael@0 1155 /**
michael@0 1156 * Returns the directory for crashreporter minidumps.
michael@0 1157 *
michael@0 1158 * @return nsILocalFile of the minidump directory
michael@0 1159 */
michael@0 1160 function do_get_minidumpdir() {
michael@0 1161 let env = Components.classes["@mozilla.org/process/environment;1"]
michael@0 1162 .getService(Components.interfaces.nsIEnvironment);
michael@0 1163 // the python harness may set this in the environment for us
michael@0 1164 let path = env.get("XPCSHELL_MINIDUMP_DIR");
michael@0 1165 if (path) {
michael@0 1166 let file = Components.classes["@mozilla.org/file/local;1"]
michael@0 1167 .createInstance(Components.interfaces.nsILocalFile);
michael@0 1168 file.initWithPath(path);
michael@0 1169 return file;
michael@0 1170 } else {
michael@0 1171 return do_get_tempdir();
michael@0 1172 }
michael@0 1173 }
michael@0 1174
michael@0 1175 /**
michael@0 1176 * Registers a directory with the profile service,
michael@0 1177 * and return the directory as an nsILocalFile.
michael@0 1178 *
michael@0 1179 * @return nsILocalFile of the profile directory.
michael@0 1180 */
michael@0 1181 function do_get_profile() {
michael@0 1182 if (!runningInParent) {
michael@0 1183 _log("test_info",
michael@0 1184 {_message: "TEST-INFO | (xpcshell/head.js) | Ignoring profile creation from child process.\n"});
michael@0 1185
michael@0 1186 return null;
michael@0 1187 }
michael@0 1188
michael@0 1189 if (!_profileInitialized) {
michael@0 1190 // Since we have a profile, we will notify profile shutdown topics at
michael@0 1191 // the end of the current test, to ensure correct cleanup on shutdown.
michael@0 1192 do_register_cleanup(function() {
michael@0 1193 let obsSvc = Components.classes["@mozilla.org/observer-service;1"].
michael@0 1194 getService(Components.interfaces.nsIObserverService);
michael@0 1195 obsSvc.notifyObservers(null, "profile-change-net-teardown", null);
michael@0 1196 obsSvc.notifyObservers(null, "profile-change-teardown", null);
michael@0 1197 obsSvc.notifyObservers(null, "profile-before-change", null);
michael@0 1198 });
michael@0 1199 }
michael@0 1200
michael@0 1201 let env = Components.classes["@mozilla.org/process/environment;1"]
michael@0 1202 .getService(Components.interfaces.nsIEnvironment);
michael@0 1203 // the python harness sets this in the environment for us
michael@0 1204 let profd = env.get("XPCSHELL_TEST_PROFILE_DIR");
michael@0 1205 let file = Components.classes["@mozilla.org/file/local;1"]
michael@0 1206 .createInstance(Components.interfaces.nsILocalFile);
michael@0 1207 file.initWithPath(profd);
michael@0 1208
michael@0 1209 let dirSvc = Components.classes["@mozilla.org/file/directory_service;1"]
michael@0 1210 .getService(Components.interfaces.nsIProperties);
michael@0 1211 let provider = {
michael@0 1212 getFile: function(prop, persistent) {
michael@0 1213 persistent.value = true;
michael@0 1214 if (prop == "ProfD" || prop == "ProfLD" || prop == "ProfDS" ||
michael@0 1215 prop == "ProfLDS" || prop == "TmpD") {
michael@0 1216 return file.clone();
michael@0 1217 }
michael@0 1218 throw Components.results.NS_ERROR_FAILURE;
michael@0 1219 },
michael@0 1220 QueryInterface: function(iid) {
michael@0 1221 if (iid.equals(Components.interfaces.nsIDirectoryServiceProvider) ||
michael@0 1222 iid.equals(Components.interfaces.nsISupports)) {
michael@0 1223 return this;
michael@0 1224 }
michael@0 1225 throw Components.results.NS_ERROR_NO_INTERFACE;
michael@0 1226 }
michael@0 1227 };
michael@0 1228 dirSvc.QueryInterface(Components.interfaces.nsIDirectoryService)
michael@0 1229 .registerProvider(provider);
michael@0 1230
michael@0 1231 let obsSvc = Components.classes["@mozilla.org/observer-service;1"].
michael@0 1232 getService(Components.interfaces.nsIObserverService);
michael@0 1233
michael@0 1234 // We need to update the crash events directory when the profile changes.
michael@0 1235 if (runningInParent &&
michael@0 1236 "@mozilla.org/toolkit/crash-reporter;1" in Components.classes) {
michael@0 1237 let crashReporter =
michael@0 1238 Components.classes["@mozilla.org/toolkit/crash-reporter;1"]
michael@0 1239 .getService(Components.interfaces.nsICrashReporter);
michael@0 1240 crashReporter.UpdateCrashEventsDir();
michael@0 1241 }
michael@0 1242
michael@0 1243 if (!_profileInitialized) {
michael@0 1244 obsSvc.notifyObservers(null, "profile-do-change", "xpcshell-do-get-profile");
michael@0 1245 _profileInitialized = true;
michael@0 1246 }
michael@0 1247
michael@0 1248 // The methods of 'provider' will retain this scope so null out everything
michael@0 1249 // to avoid spurious leak reports.
michael@0 1250 env = null;
michael@0 1251 profd = null;
michael@0 1252 dirSvc = null;
michael@0 1253 provider = null;
michael@0 1254 obsSvc = null;
michael@0 1255 return file.clone();
michael@0 1256 }
michael@0 1257
michael@0 1258 /**
michael@0 1259 * This function loads head.js (this file) in the child process, so that all
michael@0 1260 * functions defined in this file (do_throw, etc) are available to subsequent
michael@0 1261 * sendCommand calls. It also sets various constants used by these functions.
michael@0 1262 *
michael@0 1263 * (Note that you may use sendCommand without calling this function first; you
michael@0 1264 * simply won't have any of the functions in this file available.)
michael@0 1265 */
michael@0 1266 function do_load_child_test_harness()
michael@0 1267 {
michael@0 1268 // Make sure this isn't called from child process
michael@0 1269 if (!runningInParent) {
michael@0 1270 do_throw("run_test_in_child cannot be called from child!");
michael@0 1271 }
michael@0 1272
michael@0 1273 // Allow to be called multiple times, but only run once
michael@0 1274 if (typeof do_load_child_test_harness.alreadyRun != "undefined")
michael@0 1275 return;
michael@0 1276 do_load_child_test_harness.alreadyRun = 1;
michael@0 1277
michael@0 1278 _XPCSHELL_PROCESS = "parent";
michael@0 1279
michael@0 1280 let command =
michael@0 1281 "const _HEAD_JS_PATH=" + uneval(_HEAD_JS_PATH) + "; "
michael@0 1282 + "const _HTTPD_JS_PATH=" + uneval(_HTTPD_JS_PATH) + "; "
michael@0 1283 + "const _HEAD_FILES=" + uneval(_HEAD_FILES) + "; "
michael@0 1284 + "const _TAIL_FILES=" + uneval(_TAIL_FILES) + "; "
michael@0 1285 + "const _XPCSHELL_PROCESS='child';";
michael@0 1286
michael@0 1287 if (this._TESTING_MODULES_DIR) {
michael@0 1288 command += " const _TESTING_MODULES_DIR=" + uneval(_TESTING_MODULES_DIR) + ";";
michael@0 1289 }
michael@0 1290
michael@0 1291 command += " load(_HEAD_JS_PATH);";
michael@0 1292 sendCommand(command);
michael@0 1293 }
michael@0 1294
michael@0 1295 /**
michael@0 1296 * Runs an entire xpcshell unit test in a child process (rather than in chrome,
michael@0 1297 * which is the default).
michael@0 1298 *
michael@0 1299 * This function returns immediately, before the test has completed.
michael@0 1300 *
michael@0 1301 * @param testFile
michael@0 1302 * The name of the script to run. Path format same as load().
michael@0 1303 * @param optionalCallback.
michael@0 1304 * Optional function to be called (in parent) when test on child is
michael@0 1305 * complete. If provided, the function must call do_test_finished();
michael@0 1306 */
michael@0 1307 function run_test_in_child(testFile, optionalCallback)
michael@0 1308 {
michael@0 1309 var callback = (typeof optionalCallback == 'undefined') ?
michael@0 1310 do_test_finished : optionalCallback;
michael@0 1311
michael@0 1312 do_load_child_test_harness();
michael@0 1313
michael@0 1314 var testPath = do_get_file(testFile).path.replace(/\\/g, "/");
michael@0 1315 do_test_pending("run in child");
michael@0 1316 sendCommand("_log('child_test_start', {_message: 'CHILD-TEST-STARTED'}); "
michael@0 1317 + "const _TEST_FILE=['" + testPath + "']; _execute_test(); "
michael@0 1318 + "_log('child_test_end', {_message: 'CHILD-TEST-COMPLETED'});",
michael@0 1319 callback);
michael@0 1320 }
michael@0 1321
michael@0 1322 /**
michael@0 1323 * Execute a given function as soon as a particular cross-process message is received.
michael@0 1324 * Must be paired with do_send_remote_message or equivalent ProcessMessageManager calls.
michael@0 1325 */
michael@0 1326 function do_await_remote_message(name, callback)
michael@0 1327 {
michael@0 1328 var listener = {
michael@0 1329 receiveMessage: function(message) {
michael@0 1330 if (message.name == name) {
michael@0 1331 mm.removeMessageListener(name, listener);
michael@0 1332 callback();
michael@0 1333 do_test_finished();
michael@0 1334 }
michael@0 1335 }
michael@0 1336 };
michael@0 1337
michael@0 1338 var mm;
michael@0 1339 if (runningInParent) {
michael@0 1340 mm = Cc["@mozilla.org/parentprocessmessagemanager;1"].getService(Ci.nsIMessageBroadcaster);
michael@0 1341 } else {
michael@0 1342 mm = Cc["@mozilla.org/childprocessmessagemanager;1"].getService(Ci.nsISyncMessageSender);
michael@0 1343 }
michael@0 1344 do_test_pending();
michael@0 1345 mm.addMessageListener(name, listener);
michael@0 1346 }
michael@0 1347
michael@0 1348 /**
michael@0 1349 * Asynchronously send a message to all remote processes. Pairs with do_await_remote_message
michael@0 1350 * or equivalent ProcessMessageManager listeners.
michael@0 1351 */
michael@0 1352 function do_send_remote_message(name) {
michael@0 1353 var mm;
michael@0 1354 var sender;
michael@0 1355 if (runningInParent) {
michael@0 1356 mm = Cc["@mozilla.org/parentprocessmessagemanager;1"].getService(Ci.nsIMessageBroadcaster);
michael@0 1357 sender = 'broadcastAsyncMessage';
michael@0 1358 } else {
michael@0 1359 mm = Cc["@mozilla.org/childprocessmessagemanager;1"].getService(Ci.nsISyncMessageSender);
michael@0 1360 sender = 'sendAsyncMessage';
michael@0 1361 }
michael@0 1362 mm[sender](name);
michael@0 1363 }
michael@0 1364
michael@0 1365 /**
michael@0 1366 * Add a test function to the list of tests that are to be run asynchronously.
michael@0 1367 *
michael@0 1368 * Each test function must call run_next_test() when it's done. Test files
michael@0 1369 * should call run_next_test() in their run_test function to execute all
michael@0 1370 * async tests.
michael@0 1371 *
michael@0 1372 * @return the test function that was passed in.
michael@0 1373 */
michael@0 1374 let _gTests = [];
michael@0 1375 function add_test(func) {
michael@0 1376 _gTests.push([false, func]);
michael@0 1377 return func;
michael@0 1378 }
michael@0 1379
michael@0 1380 // We lazy import Task.jsm so we don't incur a run-time penalty for all tests.
michael@0 1381 let _Task;
michael@0 1382
michael@0 1383 /**
michael@0 1384 * Add a test function which is a Task function.
michael@0 1385 *
michael@0 1386 * Task functions are functions fed into Task.jsm's Task.spawn(). They are
michael@0 1387 * generators that emit promises.
michael@0 1388 *
michael@0 1389 * If an exception is thrown, a do_check_* comparison fails, or if a rejected
michael@0 1390 * promise is yielded, the test function aborts immediately and the test is
michael@0 1391 * reported as a failure.
michael@0 1392 *
michael@0 1393 * Unlike add_test(), there is no need to call run_next_test(). The next test
michael@0 1394 * will run automatically as soon the task function is exhausted. To trigger
michael@0 1395 * premature (but successful) termination of the function, simply return or
michael@0 1396 * throw a Task.Result instance.
michael@0 1397 *
michael@0 1398 * Example usage:
michael@0 1399 *
michael@0 1400 * add_task(function test() {
michael@0 1401 * let result = yield Promise.resolve(true);
michael@0 1402 *
michael@0 1403 * do_check_true(result);
michael@0 1404 *
michael@0 1405 * let secondary = yield someFunctionThatReturnsAPromise(result);
michael@0 1406 * do_check_eq(secondary, "expected value");
michael@0 1407 * });
michael@0 1408 *
michael@0 1409 * add_task(function test_early_return() {
michael@0 1410 * let result = yield somethingThatReturnsAPromise();
michael@0 1411 *
michael@0 1412 * if (!result) {
michael@0 1413 * // Test is ended immediately, with success.
michael@0 1414 * return;
michael@0 1415 * }
michael@0 1416 *
michael@0 1417 * do_check_eq(result, "foo");
michael@0 1418 * });
michael@0 1419 */
michael@0 1420 function add_task(func) {
michael@0 1421 if (!_Task) {
michael@0 1422 let ns = {};
michael@0 1423 _Task = Components.utils.import("resource://gre/modules/Task.jsm", ns).Task;
michael@0 1424 }
michael@0 1425
michael@0 1426 _gTests.push([true, func]);
michael@0 1427 }
michael@0 1428
michael@0 1429 /**
michael@0 1430 * Runs the next test function from the list of async tests.
michael@0 1431 */
michael@0 1432 let _gRunningTest = null;
michael@0 1433 let _gTestIndex = 0; // The index of the currently running test.
michael@0 1434 let _gTaskRunning = false;
michael@0 1435 function run_next_test()
michael@0 1436 {
michael@0 1437 if (_gTaskRunning) {
michael@0 1438 throw new Error("run_next_test() called from an add_task() test function. " +
michael@0 1439 "run_next_test() should not be called from inside add_task() " +
michael@0 1440 "under any circumstances!");
michael@0 1441 }
michael@0 1442
michael@0 1443 function _run_next_test()
michael@0 1444 {
michael@0 1445 if (_gTestIndex < _gTests.length) {
michael@0 1446 // Flush uncaught errors as early and often as possible.
michael@0 1447 _Promise.Debugging.flushUncaughtErrors();
michael@0 1448 let _isTask;
michael@0 1449 [_isTask, _gRunningTest] = _gTests[_gTestIndex++];
michael@0 1450 print("TEST-INFO | " + _TEST_FILE + " | Starting " + _gRunningTest.name);
michael@0 1451 do_test_pending(_gRunningTest.name);
michael@0 1452
michael@0 1453 if (_isTask) {
michael@0 1454 _gTaskRunning = true;
michael@0 1455 _Task.spawn(_gRunningTest).then(
michael@0 1456 () => { _gTaskRunning = false; run_next_test(); },
michael@0 1457 (ex) => { _gTaskRunning = false; do_report_unexpected_exception(ex); }
michael@0 1458 );
michael@0 1459 } else {
michael@0 1460 // Exceptions do not kill asynchronous tests, so they'll time out.
michael@0 1461 try {
michael@0 1462 _gRunningTest();
michael@0 1463 } catch (e) {
michael@0 1464 do_throw(e);
michael@0 1465 }
michael@0 1466 }
michael@0 1467 }
michael@0 1468 }
michael@0 1469
michael@0 1470 // For sane stacks during failures, we execute this code soon, but not now.
michael@0 1471 // We do this now, before we call do_test_finished(), to ensure the pending
michael@0 1472 // counter (_tests_pending) never reaches 0 while we still have tests to run
michael@0 1473 // (do_execute_soon bumps that counter).
michael@0 1474 do_execute_soon(_run_next_test, "run_next_test " + _gTestIndex);
michael@0 1475
michael@0 1476 if (_gRunningTest !== null) {
michael@0 1477 // Close the previous test do_test_pending call.
michael@0 1478 do_test_finished(_gRunningTest.name);
michael@0 1479 }
michael@0 1480 }
michael@0 1481
michael@0 1482 try {
michael@0 1483 if (runningInParent) {
michael@0 1484 // Always use network provider for geolocation tests
michael@0 1485 // so we bypass the OSX dialog raised by the corelocation provider
michael@0 1486 let prefs = Components.classes["@mozilla.org/preferences-service;1"]
michael@0 1487 .getService(Components.interfaces.nsIPrefBranch);
michael@0 1488
michael@0 1489 prefs.setBoolPref("geo.provider.testing", true);
michael@0 1490 }
michael@0 1491 } catch (e) { }

mercurial