mobile/android/base/tests/robocop_head.js

Thu, 22 Jan 2015 13:21:57 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Thu, 22 Jan 2015 13:21:57 +0100
branch
TOR_BUG_9701
changeset 15
b8a032363ba2
permissions
-rw-r--r--

Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6

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 const _XPCSHELL_TIMEOUT_MS = 5 * 60 * 1000;
michael@0 14
michael@0 15 var _quit = false;
michael@0 16 var _passed = true;
michael@0 17 var _tests_pending = 0;
michael@0 18 var _passedChecks = 0, _falsePassedChecks = 0;
michael@0 19 var _todoChecks = 0;
michael@0 20 var _cleanupFunctions = [];
michael@0 21 var _pendingTimers = [];
michael@0 22 var _profileInitialized = false;
michael@0 23
michael@0 24 function _dump(str) {
michael@0 25 let start = /^TEST-/.test(str) ? "\n" : "";
michael@0 26 if (typeof _XPCSHELL_PROCESS == "undefined") {
michael@0 27 dump(start + str);
michael@0 28 } else {
michael@0 29 dump(start + _XPCSHELL_PROCESS + ": " + str);
michael@0 30 }
michael@0 31 }
michael@0 32
michael@0 33 // Disable automatic network detection, so tests work correctly when
michael@0 34 // not connected to a network.
michael@0 35 let (ios = Components.classes["@mozilla.org/network/io-service;1"]
michael@0 36 .getService(Components.interfaces.nsIIOService2)) {
michael@0 37 ios.manageOfflineStatus = false;
michael@0 38 ios.offline = false;
michael@0 39 }
michael@0 40
michael@0 41 // Determine if we're running on parent or child
michael@0 42 let runningInParent = true;
michael@0 43 try {
michael@0 44 runningInParent = Components.classes["@mozilla.org/xre/runtime;1"].
michael@0 45 getService(Components.interfaces.nsIXULRuntime).processType
michael@0 46 == Components.interfaces.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
michael@0 47 }
michael@0 48 catch (e) { }
michael@0 49
michael@0 50 try {
michael@0 51 if (runningInParent) {
michael@0 52 let prefs = Components.classes["@mozilla.org/preferences-service;1"]
michael@0 53 .getService(Components.interfaces.nsIPrefBranch);
michael@0 54
michael@0 55 // disable necko IPC security checks for xpcshell, as they lack the
michael@0 56 // docshells needed to pass them
michael@0 57 prefs.setBoolPref("network.disable.ipc.security", true);
michael@0 58
michael@0 59 // Disable IPv6 lookups for 'localhost' on windows.
michael@0 60 if ("@mozilla.org/windows-registry-key;1" in Components.classes) {
michael@0 61 prefs.setCharPref("network.dns.ipv4OnlyDomains", "localhost");
michael@0 62 }
michael@0 63 }
michael@0 64 }
michael@0 65 catch (e) { }
michael@0 66
michael@0 67 // Enable crash reporting, if possible
michael@0 68 // We rely on the Python harness to set MOZ_CRASHREPORTER_NO_REPORT
michael@0 69 // and handle checking for minidumps.
michael@0 70 // Note that if we're in a child process, we don't want to init the
michael@0 71 // crashreporter component.
michael@0 72 try { // nsIXULRuntime is not available in some configurations.
michael@0 73 if (runningInParent &&
michael@0 74 "@mozilla.org/toolkit/crash-reporter;1" in Components.classes) {
michael@0 75 // Remember to update </toolkit/crashreporter/test/unit/test_crashreporter.js>
michael@0 76 // too if you change this initial setting.
michael@0 77 let (crashReporter =
michael@0 78 Components.classes["@mozilla.org/toolkit/crash-reporter;1"]
michael@0 79 .getService(Components.interfaces.nsICrashReporter)) {
michael@0 80 crashReporter.enabled = true;
michael@0 81 crashReporter.minidumpPath = do_get_cwd();
michael@0 82 }
michael@0 83 }
michael@0 84 }
michael@0 85 catch (e) { }
michael@0 86
michael@0 87 /**
michael@0 88 * Date.now() is not necessarily monotonically increasing (insert sob story
michael@0 89 * about times not being the right tool to use for measuring intervals of time,
michael@0 90 * robarnold can tell all), so be wary of error by erring by at least
michael@0 91 * _timerFuzz ms.
michael@0 92 */
michael@0 93 const _timerFuzz = 15;
michael@0 94
michael@0 95 function _Timer(func, delay) {
michael@0 96 delay = Number(delay);
michael@0 97 if (delay < 0)
michael@0 98 do_throw("do_timeout() delay must be nonnegative");
michael@0 99
michael@0 100 if (typeof func !== "function")
michael@0 101 do_throw("string callbacks no longer accepted; use a function!");
michael@0 102
michael@0 103 this._func = func;
michael@0 104 this._start = Date.now();
michael@0 105 this._delay = delay;
michael@0 106
michael@0 107 var timer = Components.classes["@mozilla.org/timer;1"]
michael@0 108 .createInstance(Components.interfaces.nsITimer);
michael@0 109 timer.initWithCallback(this, delay + _timerFuzz, timer.TYPE_ONE_SHOT);
michael@0 110
michael@0 111 // Keep timer alive until it fires
michael@0 112 _pendingTimers.push(timer);
michael@0 113 }
michael@0 114 _Timer.prototype = {
michael@0 115 QueryInterface: function(iid) {
michael@0 116 if (iid.equals(Components.interfaces.nsITimerCallback) ||
michael@0 117 iid.equals(Components.interfaces.nsISupports))
michael@0 118 return this;
michael@0 119
michael@0 120 throw Components.results.NS_ERROR_NO_INTERFACE;
michael@0 121 },
michael@0 122
michael@0 123 notify: function(timer) {
michael@0 124 _pendingTimers.splice(_pendingTimers.indexOf(timer), 1);
michael@0 125
michael@0 126 // The current nsITimer implementation can undershoot, but even if it
michael@0 127 // couldn't, paranoia is probably a virtue here given the potential for
michael@0 128 // random orange on tinderboxen.
michael@0 129 var end = Date.now();
michael@0 130 var elapsed = end - this._start;
michael@0 131 if (elapsed >= this._delay) {
michael@0 132 try {
michael@0 133 this._func.call(null);
michael@0 134 } catch (e) {
michael@0 135 do_throw("exception thrown from do_timeout callback: " + e);
michael@0 136 }
michael@0 137 return;
michael@0 138 }
michael@0 139
michael@0 140 // Timer undershot, retry with a little overshoot to try to avoid more
michael@0 141 // undershoots.
michael@0 142 var newDelay = this._delay - elapsed;
michael@0 143 do_timeout(newDelay, this._func);
michael@0 144 }
michael@0 145 };
michael@0 146
michael@0 147 function _do_main() {
michael@0 148 if (_quit)
michael@0 149 return;
michael@0 150
michael@0 151 _dump("TEST-INFO | (xpcshell/head.js) | running event loop\n");
michael@0 152
michael@0 153 var thr = Components.classes["@mozilla.org/thread-manager;1"]
michael@0 154 .getService().currentThread;
michael@0 155
michael@0 156 while (!_quit)
michael@0 157 thr.processNextEvent(true);
michael@0 158
michael@0 159 while (thr.hasPendingEvents())
michael@0 160 thr.processNextEvent(true);
michael@0 161 }
michael@0 162
michael@0 163 function _do_quit() {
michael@0 164 _dump("TEST-INFO | (xpcshell/head.js) | exiting test\n");
michael@0 165
michael@0 166 _quit = true;
michael@0 167 }
michael@0 168
michael@0 169 function _dump_exception_stack(stack) {
michael@0 170 stack.split("\n").forEach(function(frame) {
michael@0 171 if (!frame)
michael@0 172 return;
michael@0 173 // frame is of the form "fname(args)@file:line"
michael@0 174 let frame_regexp = new RegExp("(.*)\\(.*\\)@(.*):(\\d*)", "g");
michael@0 175 let parts = frame_regexp.exec(frame);
michael@0 176 if (parts)
michael@0 177 dump("JS frame :: " + parts[2] + " :: " + (parts[1] ? parts[1] : "anonymous")
michael@0 178 + " :: line " + parts[3] + "\n");
michael@0 179 else /* Could be a -e (command line string) style location. */
michael@0 180 dump("JS frame :: " + frame + "\n");
michael@0 181 });
michael@0 182 }
michael@0 183
michael@0 184 /**
michael@0 185 * Overrides idleService with a mock. Idle is commonly used for maintenance
michael@0 186 * tasks, thus if a test uses a service that requires the idle service, it will
michael@0 187 * start handling them.
michael@0 188 * This behaviour would cause random failures and slowdown tests execution,
michael@0 189 * for example by running database vacuum or cleanups for each test.
michael@0 190 *
michael@0 191 * @note Idle service is overridden by default. If a test requires it, it will
michael@0 192 * have to call do_get_idle() function at least once before use.
michael@0 193 */
michael@0 194 var _fakeIdleService = {
michael@0 195 get registrar() {
michael@0 196 delete this.registrar;
michael@0 197 return this.registrar =
michael@0 198 Components.manager.QueryInterface(Components.interfaces.nsIComponentRegistrar);
michael@0 199 },
michael@0 200 contractID: "@mozilla.org/widget/idleservice;1",
michael@0 201 get CID() this.registrar.contractIDToCID(this.contractID),
michael@0 202
michael@0 203 activate: function FIS_activate()
michael@0 204 {
michael@0 205 if (!this.originalFactory) {
michael@0 206 // Save original factory.
michael@0 207 this.originalFactory =
michael@0 208 Components.manager.getClassObject(Components.classes[this.contractID],
michael@0 209 Components.interfaces.nsIFactory);
michael@0 210 // Unregister original factory.
michael@0 211 this.registrar.unregisterFactory(this.CID, this.originalFactory);
michael@0 212 // Replace with the mock.
michael@0 213 this.registrar.registerFactory(this.CID, "Fake Idle Service",
michael@0 214 this.contractID, this.factory
michael@0 215 );
michael@0 216 }
michael@0 217 },
michael@0 218
michael@0 219 deactivate: function FIS_deactivate()
michael@0 220 {
michael@0 221 if (this.originalFactory) {
michael@0 222 // Unregister the mock.
michael@0 223 this.registrar.unregisterFactory(this.CID, this.factory);
michael@0 224 // Restore original factory.
michael@0 225 this.registrar.registerFactory(this.CID, "Idle Service",
michael@0 226 this.contractID, this.originalFactory);
michael@0 227 delete this.originalFactory;
michael@0 228 }
michael@0 229 },
michael@0 230
michael@0 231 factory: {
michael@0 232 // nsIFactory
michael@0 233 createInstance: function (aOuter, aIID)
michael@0 234 {
michael@0 235 if (aOuter) {
michael@0 236 throw Components.results.NS_ERROR_NO_AGGREGATION;
michael@0 237 }
michael@0 238 return _fakeIdleService.QueryInterface(aIID);
michael@0 239 },
michael@0 240 lockFactory: function (aLock) {
michael@0 241 throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
michael@0 242 },
michael@0 243 QueryInterface: function(aIID) {
michael@0 244 if (aIID.equals(Components.interfaces.nsIFactory) ||
michael@0 245 aIID.equals(Components.interfaces.nsISupports)) {
michael@0 246 return this;
michael@0 247 }
michael@0 248 throw Components.results.NS_ERROR_NO_INTERFACE;
michael@0 249 }
michael@0 250 },
michael@0 251
michael@0 252 // nsIIdleService
michael@0 253 get idleTime() 0,
michael@0 254 addIdleObserver: function () {},
michael@0 255 removeIdleObserver: function () {},
michael@0 256
michael@0 257 QueryInterface: function(aIID) {
michael@0 258 // Useful for testing purposes, see test_get_idle.js.
michael@0 259 if (aIID.equals(Components.interfaces.nsIFactory)) {
michael@0 260 return this.factory;
michael@0 261 }
michael@0 262 if (aIID.equals(Components.interfaces.nsIIdleService) ||
michael@0 263 aIID.equals(Components.interfaces.nsISupports)) {
michael@0 264 return this;
michael@0 265 }
michael@0 266 throw Components.results.NS_ERROR_NO_INTERFACE;
michael@0 267 }
michael@0 268 }
michael@0 269
michael@0 270 /**
michael@0 271 * Restores the idle service factory if needed and returns the service's handle.
michael@0 272 * @return A handle to the idle service.
michael@0 273 */
michael@0 274 function do_get_idle() {
michael@0 275 _fakeIdleService.deactivate();
michael@0 276 return Components.classes[_fakeIdleService.contractID]
michael@0 277 .getService(Components.interfaces.nsIIdleService);
michael@0 278 }
michael@0 279
michael@0 280 // Map resource://test/ to current working directory and
michael@0 281 // resource://testing-common/ to the shared test modules directory.
michael@0 282 function _register_protocol_handlers() {
michael@0 283 let (ios = Components.classes["@mozilla.org/network/io-service;1"]
michael@0 284 .getService(Components.interfaces.nsIIOService)) {
michael@0 285 let protocolHandler =
michael@0 286 ios.getProtocolHandler("resource")
michael@0 287 .QueryInterface(Components.interfaces.nsIResProtocolHandler);
michael@0 288 let curDirURI = ios.newFileURI(do_get_cwd());
michael@0 289 protocolHandler.setSubstitution("test", curDirURI);
michael@0 290
michael@0 291 if (this._TESTING_MODULES_DIR) {
michael@0 292 let modulesFile = Components.classes["@mozilla.org/file/local;1"].
michael@0 293 createInstance(Components.interfaces.nsILocalFile);
michael@0 294 modulesFile.initWithPath(_TESTING_MODULES_DIR);
michael@0 295
michael@0 296 if (!modulesFile.exists()) {
michael@0 297 throw new Error("Specified modules directory does not exist: " +
michael@0 298 _TESTING_MODULES_DIR);
michael@0 299 }
michael@0 300
michael@0 301 if (!modulesFile.isDirectory()) {
michael@0 302 throw new Error("Specified modules directory is not a directory: " +
michael@0 303 _TESTING_MODULES_DIR);
michael@0 304 }
michael@0 305
michael@0 306 let modulesURI = ios.newFileURI(modulesFile);
michael@0 307
michael@0 308 protocolHandler.setSubstitution("testing-common", modulesURI);
michael@0 309 }
michael@0 310 }
michael@0 311 }
michael@0 312
michael@0 313 function _execute_test() {
michael@0 314 _register_protocol_handlers();
michael@0 315
michael@0 316 // Override idle service by default.
michael@0 317 // Call do_get_idle() to restore the factory and get the service.
michael@0 318 _fakeIdleService.activate();
michael@0 319
michael@0 320 // Terminate asynchronous tests when a global timeout occurs.
michael@0 321 do_timeout(_XPCSHELL_TIMEOUT_MS, function _do_main_timeout() {
michael@0 322 try {
michael@0 323 do_throw("test timed out");
michael@0 324 } catch (e if e == Components.results.NS_ERROR_ABORT) {
michael@0 325 // We don't want do_timeout to report the do_throw exception again.
michael@0 326 }
michael@0 327 });
michael@0 328
michael@0 329 // _HEAD_FILES is dynamically defined by <runxpcshelltests.py>.
michael@0 330 _load_files(_HEAD_FILES);
michael@0 331 // _TEST_FILE is dynamically defined by <runxpcshelltests.py>.
michael@0 332 _load_files(_TEST_FILE);
michael@0 333
michael@0 334 try {
michael@0 335 do_test_pending();
michael@0 336 run_test();
michael@0 337 do_test_finished();
michael@0 338 _do_main();
michael@0 339 } catch (e) {
michael@0 340 _passed = false;
michael@0 341 // do_check failures are already logged and set _quit to true and throw
michael@0 342 // NS_ERROR_ABORT. If both of those are true it is likely this exception
michael@0 343 // has already been logged so there is no need to log it again. It's
michael@0 344 // possible that this will mask an NS_ERROR_ABORT that happens after a
michael@0 345 // do_check failure though.
michael@0 346 if (!_quit || e != Components.results.NS_ERROR_ABORT) {
michael@0 347 msg = "TEST-UNEXPECTED-FAIL | ";
michael@0 348 if (e.fileName) {
michael@0 349 msg += e.fileName;
michael@0 350 if (e.lineNumber) {
michael@0 351 msg += ":" + e.lineNumber;
michael@0 352 }
michael@0 353 } else {
michael@0 354 msg += "xpcshell/head.js";
michael@0 355 }
michael@0 356 msg += " | " + e;
michael@0 357 if (e.stack) {
michael@0 358 _dump(msg + " - See following stack:\n");
michael@0 359 _dump_exception_stack(e.stack);
michael@0 360 }
michael@0 361 else {
michael@0 362 _dump(msg + "\n");
michael@0 363 }
michael@0 364 }
michael@0 365 }
michael@0 366
michael@0 367 // _TAIL_FILES is dynamically defined by <runxpcshelltests.py>.
michael@0 368 _load_files(_TAIL_FILES);
michael@0 369
michael@0 370 // Execute all of our cleanup functions.
michael@0 371 var func;
michael@0 372 while ((func = _cleanupFunctions.pop()))
michael@0 373 func();
michael@0 374
michael@0 375 // Restore idle service to avoid leaks.
michael@0 376 _fakeIdleService.deactivate();
michael@0 377
michael@0 378 if (!_passed)
michael@0 379 return;
michael@0 380
michael@0 381 var truePassedChecks = _passedChecks - _falsePassedChecks;
michael@0 382 if (truePassedChecks > 0) {
michael@0 383 _dump("TEST-PASS | (xpcshell/head.js) | " + truePassedChecks + " (+ " +
michael@0 384 _falsePassedChecks + ") check(s) passed\n");
michael@0 385 _dump("TEST-INFO | (xpcshell/head.js) | " + _todoChecks +
michael@0 386 " check(s) todo\n");
michael@0 387 } else {
michael@0 388 // ToDo: switch to TEST-UNEXPECTED-FAIL when all tests have been updated. (Bug 496443)
michael@0 389 _dump("TEST-INFO | (xpcshell/head.js) | No (+ " + _falsePassedChecks + ") checks actually run\n");
michael@0 390 }
michael@0 391 }
michael@0 392
michael@0 393 /**
michael@0 394 * Loads files.
michael@0 395 *
michael@0 396 * @param aFiles Array of files to load.
michael@0 397 */
michael@0 398 function _load_files(aFiles) {
michael@0 399 function loadTailFile(element, index, array) {
michael@0 400 load(element);
michael@0 401 }
michael@0 402
michael@0 403 aFiles.forEach(loadTailFile);
michael@0 404 }
michael@0 405
michael@0 406
michael@0 407 /************** Functions to be used from the tests **************/
michael@0 408
michael@0 409 /**
michael@0 410 * Prints a message to the output log.
michael@0 411 */
michael@0 412 function do_print(msg) {
michael@0 413 var caller_stack = Components.stack.caller;
michael@0 414 _dump("TEST-INFO | " + caller_stack.filename + " | " + msg + "\n");
michael@0 415 }
michael@0 416
michael@0 417 /**
michael@0 418 * Calls the given function at least the specified number of milliseconds later.
michael@0 419 * The callback will not undershoot the given time, but it might overshoot --
michael@0 420 * don't expect precision!
michael@0 421 *
michael@0 422 * @param delay : uint
michael@0 423 * the number of milliseconds to delay
michael@0 424 * @param callback : function() : void
michael@0 425 * the function to call
michael@0 426 */
michael@0 427 function do_timeout(delay, func) {
michael@0 428 new _Timer(func, Number(delay));
michael@0 429 }
michael@0 430
michael@0 431 function do_execute_soon(callback) {
michael@0 432 do_test_pending();
michael@0 433 var tm = Components.classes["@mozilla.org/thread-manager;1"]
michael@0 434 .getService(Components.interfaces.nsIThreadManager);
michael@0 435
michael@0 436 tm.mainThread.dispatch({
michael@0 437 run: function() {
michael@0 438 try {
michael@0 439 callback();
michael@0 440 } catch (e) {
michael@0 441 // do_check failures are already logged and set _quit to true and throw
michael@0 442 // NS_ERROR_ABORT. If both of those are true it is likely this exception
michael@0 443 // has already been logged so there is no need to log it again. It's
michael@0 444 // possible that this will mask an NS_ERROR_ABORT that happens after a
michael@0 445 // do_check failure though.
michael@0 446 if (!_quit || e != Components.results.NS_ERROR_ABORT) {
michael@0 447 _dump("TEST-UNEXPECTED-FAIL | (xpcshell/head.js) | " + e);
michael@0 448 if (e.stack) {
michael@0 449 dump(" - See following stack:\n");
michael@0 450 _dump_exception_stack(e.stack);
michael@0 451 }
michael@0 452 else {
michael@0 453 dump("\n");
michael@0 454 }
michael@0 455 _do_quit();
michael@0 456 }
michael@0 457 }
michael@0 458 finally {
michael@0 459 do_test_finished();
michael@0 460 }
michael@0 461 }
michael@0 462 }, Components.interfaces.nsIThread.DISPATCH_NORMAL);
michael@0 463 }
michael@0 464
michael@0 465 function do_throw(text, stack) {
michael@0 466 if (!stack)
michael@0 467 stack = Components.stack.caller;
michael@0 468
michael@0 469 _passed = false;
michael@0 470 _dump("TEST-UNEXPECTED-FAIL | " + stack.filename + " | " + text +
michael@0 471 " - See following stack:\n");
michael@0 472 var frame = Components.stack;
michael@0 473 while (frame != null) {
michael@0 474 _dump(frame + "\n");
michael@0 475 frame = frame.caller;
michael@0 476 }
michael@0 477
michael@0 478 _do_quit();
michael@0 479 throw Components.results.NS_ERROR_ABORT;
michael@0 480 }
michael@0 481
michael@0 482 function do_throw_todo(text, stack) {
michael@0 483 if (!stack)
michael@0 484 stack = Components.stack.caller;
michael@0 485
michael@0 486 _passed = false;
michael@0 487 _dump("TEST-UNEXPECTED-PASS | " + stack.filename + " | " + text +
michael@0 488 " - See following stack:\n");
michael@0 489 var frame = Components.stack;
michael@0 490 while (frame != null) {
michael@0 491 _dump(frame + "\n");
michael@0 492 frame = frame.caller;
michael@0 493 }
michael@0 494
michael@0 495 _do_quit();
michael@0 496 throw Components.results.NS_ERROR_ABORT;
michael@0 497 }
michael@0 498
michael@0 499 function do_report_unexpected_exception(ex, text) {
michael@0 500 var caller_stack = Components.stack.caller;
michael@0 501 text = text ? text + " - " : "";
michael@0 502
michael@0 503 _passed = false;
michael@0 504 _dump("TEST-UNEXPECTED-FAIL | " + caller_stack.filename + " | " + text +
michael@0 505 "Unexpected exception " + ex + ", see following stack:\n" + ex.stack +
michael@0 506 "\n");
michael@0 507
michael@0 508 _do_quit();
michael@0 509 throw Components.results.NS_ERROR_ABORT;
michael@0 510 }
michael@0 511
michael@0 512 function do_note_exception(ex, text) {
michael@0 513 var caller_stack = Components.stack.caller;
michael@0 514 text = text ? text + " - " : "";
michael@0 515
michael@0 516 _dump("TEST-INFO | " + caller_stack.filename + " | " + text +
michael@0 517 "Swallowed exception " + ex + ", see following stack:\n" + ex.stack +
michael@0 518 "\n");
michael@0 519 }
michael@0 520
michael@0 521 function _do_check_neq(left, right, stack, todo) {
michael@0 522 if (!stack)
michael@0 523 stack = Components.stack.caller;
michael@0 524
michael@0 525 var text = left + " != " + right;
michael@0 526 if (left == right) {
michael@0 527 if (!todo) {
michael@0 528 do_throw(text, stack);
michael@0 529 } else {
michael@0 530 ++_todoChecks;
michael@0 531 _dump("TEST-KNOWN-FAIL | " + stack.filename + " | [" + stack.name +
michael@0 532 " : " + stack.lineNumber + "] " + text +"\n");
michael@0 533 }
michael@0 534 } else {
michael@0 535 if (!todo) {
michael@0 536 ++_passedChecks;
michael@0 537 _dump("TEST-PASS | " + stack.filename + " | [" + stack.name + " : " +
michael@0 538 stack.lineNumber + "] " + text + "\n");
michael@0 539 } else {
michael@0 540 do_throw_todo(text, stack);
michael@0 541 }
michael@0 542 }
michael@0 543 }
michael@0 544
michael@0 545 function do_check_neq(left, right, stack) {
michael@0 546 if (!stack)
michael@0 547 stack = Components.stack.caller;
michael@0 548
michael@0 549 _do_check_neq(left, right, stack, false);
michael@0 550 }
michael@0 551
michael@0 552 function todo_check_neq(left, right, stack) {
michael@0 553 if (!stack)
michael@0 554 stack = Components.stack.caller;
michael@0 555
michael@0 556 _do_check_neq(left, right, stack, true);
michael@0 557 }
michael@0 558
michael@0 559 function do_report_result(passed, text, stack, todo) {
michael@0 560 if (passed) {
michael@0 561 if (todo) {
michael@0 562 do_throw_todo(text, stack);
michael@0 563 } else {
michael@0 564 ++_passedChecks;
michael@0 565 _dump("TEST-PASS | " + stack.filename + " | [" + stack.name + " : " +
michael@0 566 stack.lineNumber + "] " + text + "\n");
michael@0 567 }
michael@0 568 } else {
michael@0 569 if (todo) {
michael@0 570 ++_todoChecks;
michael@0 571 _dump("TEST-KNOWN-FAIL | " + stack.filename + " | [" + stack.name +
michael@0 572 " : " + stack.lineNumber + "] " + text +"\n");
michael@0 573 } else {
michael@0 574 do_throw(text, stack);
michael@0 575 }
michael@0 576 }
michael@0 577 }
michael@0 578
michael@0 579 function _do_check_eq(left, right, stack, todo) {
michael@0 580 if (!stack)
michael@0 581 stack = Components.stack.caller;
michael@0 582
michael@0 583 var text = left + " == " + right;
michael@0 584 do_report_result(left == right, text, stack, todo);
michael@0 585 }
michael@0 586
michael@0 587 function do_check_eq(left, right, stack) {
michael@0 588 if (!stack)
michael@0 589 stack = Components.stack.caller;
michael@0 590
michael@0 591 _do_check_eq(left, right, stack, false);
michael@0 592 }
michael@0 593
michael@0 594 function todo_check_eq(left, right, stack) {
michael@0 595 if (!stack)
michael@0 596 stack = Components.stack.caller;
michael@0 597
michael@0 598 _do_check_eq(left, right, stack, true);
michael@0 599 }
michael@0 600
michael@0 601 function do_check_true(condition, stack) {
michael@0 602 if (!stack)
michael@0 603 stack = Components.stack.caller;
michael@0 604
michael@0 605 do_check_eq(condition, true, stack);
michael@0 606 }
michael@0 607
michael@0 608 function todo_check_true(condition, stack) {
michael@0 609 if (!stack)
michael@0 610 stack = Components.stack.caller;
michael@0 611
michael@0 612 todo_check_eq(condition, true, stack);
michael@0 613 }
michael@0 614
michael@0 615 function do_check_false(condition, stack) {
michael@0 616 if (!stack)
michael@0 617 stack = Components.stack.caller;
michael@0 618
michael@0 619 do_check_eq(condition, false, stack);
michael@0 620 }
michael@0 621
michael@0 622 function todo_check_false(condition, stack) {
michael@0 623 if (!stack)
michael@0 624 stack = Components.stack.caller;
michael@0 625
michael@0 626 todo_check_eq(condition, false, stack);
michael@0 627 }
michael@0 628
michael@0 629 function do_check_null(condition, stack=Components.stack.caller) {
michael@0 630 do_check_eq(condition, null, stack);
michael@0 631 }
michael@0 632
michael@0 633 function todo_check_null(condition, stack=Components.stack.caller) {
michael@0 634 todo_check_eq(condition, null, stack);
michael@0 635 }
michael@0 636
michael@0 637 /**
michael@0 638 * Check that |value| matches |pattern|.
michael@0 639 *
michael@0 640 * A |value| matches a pattern |pattern| if any one of the following is true:
michael@0 641 *
michael@0 642 * - |value| and |pattern| are both objects; |pattern|'s enumerable
michael@0 643 * properties' values are valid patterns; and for each enumerable
michael@0 644 * property |p| of |pattern|, plus 'length' if present at all, |value|
michael@0 645 * has a property |p| whose value matches |pattern.p|. Note that if |j|
michael@0 646 * has other properties not present in |p|, |j| may still match |p|.
michael@0 647 *
michael@0 648 * - |value| and |pattern| are equal string, numeric, or boolean literals
michael@0 649 *
michael@0 650 * - |pattern| is |undefined| (this is a wildcard pattern)
michael@0 651 *
michael@0 652 * - typeof |pattern| == "function", and |pattern(value)| is true.
michael@0 653 *
michael@0 654 * For example:
michael@0 655 *
michael@0 656 * do_check_matches({x:1}, {x:1}) // pass
michael@0 657 * do_check_matches({x:1}, {}) // fail: all pattern props required
michael@0 658 * do_check_matches({x:1}, {x:2}) // fail: values must match
michael@0 659 * do_check_matches({x:1}, {x:1, y:2}) // pass: extra props tolerated
michael@0 660 *
michael@0 661 * // Property order is irrelevant.
michael@0 662 * do_check_matches({x:"foo", y:"bar"}, {y:"bar", x:"foo"}) // pass
michael@0 663 *
michael@0 664 * do_check_matches({x:undefined}, {x:1}) // pass: 'undefined' is wildcard
michael@0 665 * do_check_matches({x:undefined}, {x:2})
michael@0 666 * do_check_matches({x:undefined}, {y:2}) // fail: 'x' must still be there
michael@0 667 *
michael@0 668 * // Patterns nest.
michael@0 669 * do_check_matches({a:1, b:{c:2,d:undefined}}, {a:1, b:{c:2,d:3}})
michael@0 670 *
michael@0 671 * // 'length' property counts, even if non-enumerable.
michael@0 672 * do_check_matches([3,4,5], [3,4,5]) // pass
michael@0 673 * do_check_matches([3,4,5], [3,5,5]) // fail; value doesn't match
michael@0 674 * do_check_matches([3,4,5], [3,4,5,6]) // fail; length doesn't match
michael@0 675 *
michael@0 676 * // functions in patterns get applied.
michael@0 677 * do_check_matches({foo:function (v) v.length == 2}, {foo:"hi"}) // pass
michael@0 678 * do_check_matches({foo:function (v) v.length == 2}, {bar:"hi"}) // fail
michael@0 679 * do_check_matches({foo:function (v) v.length == 2}, {foo:"hello"}) // fail
michael@0 680 *
michael@0 681 * // We don't check constructors, prototypes, or classes. However, if
michael@0 682 * // pattern has a 'length' property, we require values to match that as
michael@0 683 * // well, even if 'length' is non-enumerable in the pattern. So arrays
michael@0 684 * // are useful as patterns.
michael@0 685 * do_check_matches({0:0, 1:1, length:2}, [0,1]) // pass
michael@0 686 * do_check_matches({0:1}, [1,2]) // pass
michael@0 687 * do_check_matches([0], {0:0, length:1}) // pass
michael@0 688 *
michael@0 689 * Notes:
michael@0 690 *
michael@0 691 * The 'length' hack gives us reasonably intuitive handling of arrays.
michael@0 692 *
michael@0 693 * This is not a tight pattern-matcher; it's only good for checking data
michael@0 694 * from well-behaved sources. For example:
michael@0 695 * - By default, we don't mind values having extra properties.
michael@0 696 * - We don't check for proxies or getters.
michael@0 697 * - We don't check the prototype chain.
michael@0 698 * However, if you know the values are, say, JSON, which is pretty
michael@0 699 * well-behaved, and if you want to tolerate additional properties
michael@0 700 * appearing on the JSON for backward-compatibility, then do_check_matches
michael@0 701 * is ideal. If you do want to be more careful, you can use function
michael@0 702 * patterns to implement more stringent checks.
michael@0 703 */
michael@0 704 function do_check_matches(pattern, value, stack=Components.stack.caller, todo=false) {
michael@0 705 var matcher = pattern_matcher(pattern);
michael@0 706 var text = "VALUE: " + uneval(value) + "\nPATTERN: " + uneval(pattern) + "\n";
michael@0 707 var diagnosis = []
michael@0 708 if (matcher(value, diagnosis)) {
michael@0 709 do_report_result(true, "value matches pattern:\n" + text, stack, todo);
michael@0 710 } else {
michael@0 711 text = ("value doesn't match pattern:\n" +
michael@0 712 text +
michael@0 713 "DIAGNOSIS: " +
michael@0 714 format_pattern_match_failure(diagnosis[0]) + "\n");
michael@0 715 do_report_result(false, text, stack, todo);
michael@0 716 }
michael@0 717 }
michael@0 718
michael@0 719 function todo_check_matches(pattern, value, stack=Components.stack.caller) {
michael@0 720 do_check_matches(pattern, value, stack, true);
michael@0 721 }
michael@0 722
michael@0 723 // Return a pattern-matching function of one argument, |value|, that
michael@0 724 // returns true if |value| matches |pattern|.
michael@0 725 //
michael@0 726 // If the pattern doesn't match, and the pattern-matching function was
michael@0 727 // passed its optional |diagnosis| argument, the pattern-matching function
michael@0 728 // sets |diagnosis|'s '0' property to a JSON-ish description of the portion
michael@0 729 // of the pattern that didn't match, which can be formatted legibly by
michael@0 730 // format_pattern_match_failure.
michael@0 731 function pattern_matcher(pattern) {
michael@0 732 function explain(diagnosis, reason) {
michael@0 733 if (diagnosis) {
michael@0 734 diagnosis[0] = reason;
michael@0 735 }
michael@0 736 return false;
michael@0 737 }
michael@0 738 if (typeof pattern == "function") {
michael@0 739 return pattern;
michael@0 740 } else if (typeof pattern == "object" && pattern) {
michael@0 741 var matchers = [[p, pattern_matcher(pattern[p])] for (p in pattern)];
michael@0 742 // Kludge: include 'length', if not enumerable. (If it is enumerable,
michael@0 743 // we picked it up in the array comprehension, above.
michael@0 744 ld = Object.getOwnPropertyDescriptor(pattern, 'length');
michael@0 745 if (ld && !ld.enumerable) {
michael@0 746 matchers.push(['length', pattern_matcher(pattern.length)])
michael@0 747 }
michael@0 748 return function (value, diagnosis) {
michael@0 749 if (!(value && typeof value == "object")) {
michael@0 750 return explain(diagnosis, "value not object");
michael@0 751 }
michael@0 752 for (let [p, m] of matchers) {
michael@0 753 var element_diagnosis = [];
michael@0 754 if (!(p in value && m(value[p], element_diagnosis))) {
michael@0 755 return explain(diagnosis, { property:p,
michael@0 756 diagnosis:element_diagnosis[0] });
michael@0 757 }
michael@0 758 }
michael@0 759 return true;
michael@0 760 };
michael@0 761 } else if (pattern === undefined) {
michael@0 762 return function(value) { return true; };
michael@0 763 } else {
michael@0 764 return function (value, diagnosis) {
michael@0 765 if (value !== pattern) {
michael@0 766 return explain(diagnosis, "pattern " + uneval(pattern) + " not === to value " + uneval(value));
michael@0 767 }
michael@0 768 return true;
michael@0 769 };
michael@0 770 }
michael@0 771 }
michael@0 772
michael@0 773 // Format an explanation for a pattern match failure, as stored in the
michael@0 774 // second argument to a matching function.
michael@0 775 function format_pattern_match_failure(diagnosis, indent="") {
michael@0 776 var a;
michael@0 777 if (!diagnosis) {
michael@0 778 a = "Matcher did not explain reason for mismatch.";
michael@0 779 } else if (typeof diagnosis == "string") {
michael@0 780 a = diagnosis;
michael@0 781 } else if (diagnosis.property) {
michael@0 782 a = "Property " + uneval(diagnosis.property) + " of object didn't match:\n";
michael@0 783 a += format_pattern_match_failure(diagnosis.diagnosis, indent + " ");
michael@0 784 }
michael@0 785 return indent + a;
michael@0 786 }
michael@0 787
michael@0 788 function do_test_pending() {
michael@0 789 ++_tests_pending;
michael@0 790
michael@0 791 _dump("TEST-INFO | (xpcshell/head.js) | test " + _tests_pending +
michael@0 792 " pending\n");
michael@0 793 }
michael@0 794
michael@0 795 function do_test_finished() {
michael@0 796 _dump("TEST-INFO | (xpcshell/head.js) | test " + _tests_pending +
michael@0 797 " finished\n");
michael@0 798
michael@0 799 if (--_tests_pending == 0)
michael@0 800 _do_quit();
michael@0 801 }
michael@0 802
michael@0 803 function do_get_file(path, allowNonexistent) {
michael@0 804 try {
michael@0 805 let lf = Components.classes["@mozilla.org/file/directory_service;1"]
michael@0 806 .getService(Components.interfaces.nsIProperties)
michael@0 807 .get("CurWorkD", Components.interfaces.nsILocalFile);
michael@0 808
michael@0 809 let bits = path.split("/");
michael@0 810 for (let i = 0; i < bits.length; i++) {
michael@0 811 if (bits[i]) {
michael@0 812 if (bits[i] == "..")
michael@0 813 lf = lf.parent;
michael@0 814 else
michael@0 815 lf.append(bits[i]);
michael@0 816 }
michael@0 817 }
michael@0 818
michael@0 819 if (!allowNonexistent && !lf.exists()) {
michael@0 820 // Not using do_throw(): caller will continue.
michael@0 821 _passed = false;
michael@0 822 var stack = Components.stack.caller;
michael@0 823 _dump("TEST-UNEXPECTED-FAIL | " + stack.filename + " | [" +
michael@0 824 stack.name + " : " + stack.lineNumber + "] " + lf.path +
michael@0 825 " does not exist\n");
michael@0 826 }
michael@0 827
michael@0 828 return lf;
michael@0 829 }
michael@0 830 catch (ex) {
michael@0 831 do_throw(ex.toString(), Components.stack.caller);
michael@0 832 }
michael@0 833
michael@0 834 return null;
michael@0 835 }
michael@0 836
michael@0 837 // do_get_cwd() isn't exactly self-explanatory, so provide a helper
michael@0 838 function do_get_cwd() {
michael@0 839 return do_get_file("");
michael@0 840 }
michael@0 841
michael@0 842 function do_load_manifest(path) {
michael@0 843 var lf = do_get_file(path);
michael@0 844 const nsIComponentRegistrar = Components.interfaces.nsIComponentRegistrar;
michael@0 845 do_check_true(Components.manager instanceof nsIComponentRegistrar);
michael@0 846 // Previous do_check_true() is not a test check.
michael@0 847 ++_falsePassedChecks;
michael@0 848 Components.manager.autoRegister(lf);
michael@0 849 }
michael@0 850
michael@0 851 /**
michael@0 852 * Parse a DOM document.
michael@0 853 *
michael@0 854 * @param aPath File path to the document.
michael@0 855 * @param aType Content type to use in DOMParser.
michael@0 856 *
michael@0 857 * @return nsIDOMDocument from the file.
michael@0 858 */
michael@0 859 function do_parse_document(aPath, aType) {
michael@0 860 switch (aType) {
michael@0 861 case "application/xhtml+xml":
michael@0 862 case "application/xml":
michael@0 863 case "text/xml":
michael@0 864 break;
michael@0 865
michael@0 866 default:
michael@0 867 do_throw("type: expected application/xhtml+xml, application/xml or text/xml," +
michael@0 868 " got '" + aType + "'",
michael@0 869 Components.stack.caller);
michael@0 870 }
michael@0 871
michael@0 872 var lf = do_get_file(aPath);
michael@0 873 const C_i = Components.interfaces;
michael@0 874 const parserClass = "@mozilla.org/xmlextras/domparser;1";
michael@0 875 const streamClass = "@mozilla.org/network/file-input-stream;1";
michael@0 876 var stream = Components.classes[streamClass]
michael@0 877 .createInstance(C_i.nsIFileInputStream);
michael@0 878 stream.init(lf, -1, -1, C_i.nsIFileInputStream.CLOSE_ON_EOF);
michael@0 879 var parser = Components.classes[parserClass]
michael@0 880 .createInstance(C_i.nsIDOMParser);
michael@0 881 var doc = parser.parseFromStream(stream, null, lf.fileSize, aType);
michael@0 882 parser = null;
michael@0 883 stream = null;
michael@0 884 lf = null;
michael@0 885 return doc;
michael@0 886 }
michael@0 887
michael@0 888 /**
michael@0 889 * Registers a function that will run when the test harness is done running all
michael@0 890 * tests.
michael@0 891 *
michael@0 892 * @param aFunction
michael@0 893 * The function to be called when the test harness has finished running.
michael@0 894 */
michael@0 895 function do_register_cleanup(aFunction)
michael@0 896 {
michael@0 897 _cleanupFunctions.push(aFunction);
michael@0 898 }
michael@0 899
michael@0 900 /**
michael@0 901 * Registers a directory with the profile service,
michael@0 902 * and return the directory as an nsILocalFile.
michael@0 903 *
michael@0 904 * @return nsILocalFile of the profile directory.
michael@0 905 */
michael@0 906 function do_get_profile() {
michael@0 907 if (!runningInParent) {
michael@0 908 _dump("TEST-INFO | (xpcshell/head.js) | Ignoring profile creation from child process.\n");
michael@0 909 return null;
michael@0 910 }
michael@0 911
michael@0 912 if (!_profileInitialized) {
michael@0 913 // Since we have a profile, we will notify profile shutdown topics at
michael@0 914 // the end of the current test, to ensure correct cleanup on shutdown.
michael@0 915 do_register_cleanup(function() {
michael@0 916 let obsSvc = Components.classes["@mozilla.org/observer-service;1"].
michael@0 917 getService(Components.interfaces.nsIObserverService);
michael@0 918 obsSvc.notifyObservers(null, "profile-change-net-teardown", null);
michael@0 919 obsSvc.notifyObservers(null, "profile-change-teardown", null);
michael@0 920 obsSvc.notifyObservers(null, "profile-before-change", null);
michael@0 921 });
michael@0 922 }
michael@0 923
michael@0 924 let env = Components.classes["@mozilla.org/process/environment;1"]
michael@0 925 .getService(Components.interfaces.nsIEnvironment);
michael@0 926 // the python harness sets this in the environment for us
michael@0 927 let profd = env.get("XPCSHELL_TEST_PROFILE_DIR");
michael@0 928 let file = Components.classes["@mozilla.org/file/local;1"]
michael@0 929 .createInstance(Components.interfaces.nsILocalFile);
michael@0 930 file.initWithPath(profd);
michael@0 931
michael@0 932 let dirSvc = Components.classes["@mozilla.org/file/directory_service;1"]
michael@0 933 .getService(Components.interfaces.nsIProperties);
michael@0 934 let provider = {
michael@0 935 getFile: function(prop, persistent) {
michael@0 936 persistent.value = true;
michael@0 937 if (prop == "ProfD" || prop == "ProfLD" || prop == "ProfDS" ||
michael@0 938 prop == "ProfLDS" || prop == "TmpD") {
michael@0 939 return file.clone();
michael@0 940 }
michael@0 941 throw Components.results.NS_ERROR_FAILURE;
michael@0 942 },
michael@0 943 QueryInterface: function(iid) {
michael@0 944 if (iid.equals(Components.interfaces.nsIDirectoryServiceProvider) ||
michael@0 945 iid.equals(Components.interfaces.nsISupports)) {
michael@0 946 return this;
michael@0 947 }
michael@0 948 throw Components.results.NS_ERROR_NO_INTERFACE;
michael@0 949 }
michael@0 950 };
michael@0 951 dirSvc.QueryInterface(Components.interfaces.nsIDirectoryService)
michael@0 952 .registerProvider(provider);
michael@0 953
michael@0 954 let obsSvc = Components.classes["@mozilla.org/observer-service;1"].
michael@0 955 getService(Components.interfaces.nsIObserverService);
michael@0 956
michael@0 957 if (!_profileInitialized) {
michael@0 958 obsSvc.notifyObservers(null, "profile-do-change", "xpcshell-do-get-profile");
michael@0 959 _profileInitialized = true;
michael@0 960 }
michael@0 961
michael@0 962 // The methods of 'provider' will retain this scope so null out everything
michael@0 963 // to avoid spurious leak reports.
michael@0 964 env = null;
michael@0 965 profd = null;
michael@0 966 dirSvc = null;
michael@0 967 provider = null;
michael@0 968 obsSvc = null;
michael@0 969 return file.clone();
michael@0 970 }
michael@0 971
michael@0 972 /**
michael@0 973 * This function loads head.js (this file) in the child process, so that all
michael@0 974 * functions defined in this file (do_throw, etc) are available to subsequent
michael@0 975 * sendCommand calls. It also sets various constants used by these functions.
michael@0 976 *
michael@0 977 * (Note that you may use sendCommand without calling this function first; you
michael@0 978 * simply won't have any of the functions in this file available.)
michael@0 979 */
michael@0 980 function do_load_child_test_harness()
michael@0 981 {
michael@0 982 // Make sure this isn't called from child process
michael@0 983 if (!runningInParent) {
michael@0 984 do_throw("run_test_in_child cannot be called from child!");
michael@0 985 }
michael@0 986
michael@0 987 // Allow to be called multiple times, but only run once
michael@0 988 if (typeof do_load_child_test_harness.alreadyRun != "undefined")
michael@0 989 return;
michael@0 990 do_load_child_test_harness.alreadyRun = 1;
michael@0 991
michael@0 992 _XPCSHELL_PROCESS = "parent";
michael@0 993
michael@0 994 let command =
michael@0 995 "const _HEAD_JS_PATH=" + uneval(_HEAD_JS_PATH) + "; "
michael@0 996 + "const _HTTPD_JS_PATH=" + uneval(_HTTPD_JS_PATH) + "; "
michael@0 997 + "const _HEAD_FILES=" + uneval(_HEAD_FILES) + "; "
michael@0 998 + "const _TAIL_FILES=" + uneval(_TAIL_FILES) + "; "
michael@0 999 + "const _XPCSHELL_PROCESS='child';";
michael@0 1000
michael@0 1001 if (this._TESTING_MODULES_DIR) {
michael@0 1002 command += " const _TESTING_MODULES_DIR=" + uneval(_TESTING_MODULES_DIR) + ";";
michael@0 1003 }
michael@0 1004
michael@0 1005 command += " load(_HEAD_JS_PATH);";
michael@0 1006
michael@0 1007 sendCommand(command);
michael@0 1008 }
michael@0 1009
michael@0 1010 /**
michael@0 1011 * Runs an entire xpcshell unit test in a child process (rather than in chrome,
michael@0 1012 * which is the default).
michael@0 1013 *
michael@0 1014 * This function returns immediately, before the test has completed.
michael@0 1015 *
michael@0 1016 * @param testFile
michael@0 1017 * The name of the script to run. Path format same as load().
michael@0 1018 * @param optionalCallback.
michael@0 1019 * Optional function to be called (in parent) when test on child is
michael@0 1020 * complete. If provided, the function must call do_test_finished();
michael@0 1021 */
michael@0 1022 function run_test_in_child(testFile, optionalCallback)
michael@0 1023 {
michael@0 1024 var callback = (typeof optionalCallback == 'undefined') ?
michael@0 1025 do_test_finished : optionalCallback;
michael@0 1026
michael@0 1027 do_load_child_test_harness();
michael@0 1028
michael@0 1029 var testPath = do_get_file(testFile).path.replace(/\\/g, "/");
michael@0 1030 do_test_pending();
michael@0 1031 sendCommand("_dump('CHILD-TEST-STARTED'); "
michael@0 1032 + "const _TEST_FILE=['" + testPath + "']; _execute_test(); "
michael@0 1033 + "_dump('CHILD-TEST-COMPLETED');",
michael@0 1034 callback);
michael@0 1035 }
michael@0 1036
michael@0 1037
michael@0 1038 /**
michael@0 1039 * Add a test function to the list of tests that are to be run asynchronously.
michael@0 1040 *
michael@0 1041 * Each test function must call run_next_test() when it's done. Test files
michael@0 1042 * should call run_next_test() in their run_test function to execute all
michael@0 1043 * async tests.
michael@0 1044 *
michael@0 1045 * @return the test function that was passed in.
michael@0 1046 */
michael@0 1047 let _gTests = [];
michael@0 1048 function add_test(func) {
michael@0 1049 _gTests.push([false, func]);
michael@0 1050 return func;
michael@0 1051 }
michael@0 1052
michael@0 1053 // We lazy import Task.jsm so we don't incur a run-time penalty for all tests.
michael@0 1054 let _Task;
michael@0 1055
michael@0 1056 /**
michael@0 1057 * Add a test function which is a Task function.
michael@0 1058 *
michael@0 1059 * Task functions are functions fed into Task.jsm's Task.spawn(). They are
michael@0 1060 * generators that emit promises.
michael@0 1061 *
michael@0 1062 * If an exception is thrown, a do_check_* comparison fails, or if a rejected
michael@0 1063 * promise is yielded, the test function aborts immediately and the test is
michael@0 1064 * reported as a failure.
michael@0 1065 *
michael@0 1066 * Unlike add_test(), there is no need to call run_next_test(). The next test
michael@0 1067 * will run automatically as soon the task function is exhausted. To trigger
michael@0 1068 * premature (but successful) termination of the function, simply return or
michael@0 1069 * throw a Task.Result instance.
michael@0 1070 *
michael@0 1071 * Example usage:
michael@0 1072 *
michael@0 1073 * add_task(function test() {
michael@0 1074 * let result = yield Promise.resolve(true);
michael@0 1075 *
michael@0 1076 * do_check_true(result);
michael@0 1077 *
michael@0 1078 * let secondary = yield someFunctionThatReturnsAPromise(result);
michael@0 1079 * do_check_eq(secondary, "expected value");
michael@0 1080 * });
michael@0 1081 *
michael@0 1082 * add_task(function test_early_return() {
michael@0 1083 * let result = yield somethingThatReturnsAPromise();
michael@0 1084 *
michael@0 1085 * if (!result) {
michael@0 1086 * // Test is ended immediately, with success.
michael@0 1087 * return;
michael@0 1088 * }
michael@0 1089 *
michael@0 1090 * do_check_eq(result, "foo");
michael@0 1091 * });
michael@0 1092 */
michael@0 1093 function add_task(func) {
michael@0 1094 if (!_Task) {
michael@0 1095 let ns = {};
michael@0 1096 _Task = Components.utils.import("resource://gre/modules/Task.jsm", ns).Task;
michael@0 1097 }
michael@0 1098
michael@0 1099 _gTests.push([true, func]);
michael@0 1100 }
michael@0 1101
michael@0 1102 /**
michael@0 1103 * Runs the next test function from the list of async tests.
michael@0 1104 */
michael@0 1105 let _gRunningTest = null;
michael@0 1106 let _gTestIndex = 0; // The index of the currently running test.
michael@0 1107 function run_next_test()
michael@0 1108 {
michael@0 1109 function _run_next_test()
michael@0 1110 {
michael@0 1111 if (_gTestIndex < _gTests.length) {
michael@0 1112 do_test_pending();
michael@0 1113 let _isTask;
michael@0 1114 [_isTask, _gRunningTest] = _gTests[_gTestIndex++];
michael@0 1115 _dump("TEST-INFO | " + _TEST_FILE + " | Starting " + _gRunningTest.name);
michael@0 1116
michael@0 1117 if (_isTask) {
michael@0 1118 _Task.spawn(_gRunningTest)
michael@0 1119 .then(run_next_test, do_report_unexpected_exception);
michael@0 1120 } else {
michael@0 1121 // Exceptions do not kill asynchronous tests, so they'll time out.
michael@0 1122 try {
michael@0 1123 _gRunningTest();
michael@0 1124 } catch (e) {
michael@0 1125 do_throw(e);
michael@0 1126 }
michael@0 1127 }
michael@0 1128 }
michael@0 1129 }
michael@0 1130
michael@0 1131 // For sane stacks during failures, we execute this code soon, but not now.
michael@0 1132 // We do this now, before we call do_test_finished(), to ensure the pending
michael@0 1133 // counter (_tests_pending) never reaches 0 while we still have tests to run
michael@0 1134 // (do_execute_soon bumps that counter).
michael@0 1135 do_execute_soon(_run_next_test);
michael@0 1136
michael@0 1137 if (_gRunningTest !== null) {
michael@0 1138 // Close the previous test do_test_pending call.
michael@0 1139 do_test_finished();
michael@0 1140 }
michael@0 1141 }
michael@0 1142
michael@0 1143 /**
michael@0 1144 * End of code adapted from xpcshell head.js
michael@0 1145 */
michael@0 1146
michael@0 1147
michael@0 1148 /**
michael@0 1149 * JavaBridge facilitates communication between Java and JS. See
michael@0 1150 * JavascriptBridge.java for the corresponding JavascriptBridge and docs.
michael@0 1151 */
michael@0 1152
michael@0 1153 function JavaBridge(obj) {
michael@0 1154
michael@0 1155 this._EVENT_TYPE = "Robocop:JS";
michael@0 1156 this._target = obj;
michael@0 1157 // The number of replies needed to answer all outstanding sync calls.
michael@0 1158 this._repliesNeeded = 0;
michael@0 1159 this._Services.obs.addObserver(this, this._EVENT_TYPE, false);
michael@0 1160
michael@0 1161 this._sendMessage("notify-loaded", []);
michael@0 1162 };
michael@0 1163
michael@0 1164 JavaBridge.prototype = {
michael@0 1165
michael@0 1166 _Services: Components.utils.import(
michael@0 1167 "resource://gre/modules/Services.jsm", {}).Services,
michael@0 1168
michael@0 1169 _sendMessageToJava: Components.utils.import(
michael@0 1170 "resource://gre/modules/Messaging.jsm", {}).sendMessageToJava,
michael@0 1171
michael@0 1172 _sendMessage: function (innerType, args) {
michael@0 1173 this._sendMessageToJava({
michael@0 1174 type: this._EVENT_TYPE,
michael@0 1175 innerType: innerType,
michael@0 1176 method: args[0],
michael@0 1177 args: Array.prototype.slice.call(args, 1),
michael@0 1178 });
michael@0 1179 },
michael@0 1180
michael@0 1181 observe: function(subject, topic, data) {
michael@0 1182 let message = JSON.parse(data);
michael@0 1183 if (message.innerType === "sync-reply") {
michael@0 1184 // Reply to our Javascript-to-Java sync call
michael@0 1185 this._repliesNeeded--;
michael@0 1186 return;
michael@0 1187 }
michael@0 1188 // Call the corresponding method on the target
michael@0 1189 try {
michael@0 1190 this._target[message.method].apply(this._target, message.args);
michael@0 1191 } catch (e) {
michael@0 1192 do_report_unexpected_exception(e, "Failed to call " + message.method);
michael@0 1193 }
michael@0 1194 if (message.innerType === "sync-call") {
michael@0 1195 // Reply for sync message
michael@0 1196 this._sendMessage("sync-reply", [message.method]);
michael@0 1197 }
michael@0 1198 },
michael@0 1199
michael@0 1200 /**
michael@0 1201 * Synchronously call a method in Java,
michael@0 1202 * given the method name followed by a list of arguments.
michael@0 1203 */
michael@0 1204 syncCall: function (methodName /*, ... */) {
michael@0 1205 this._sendMessage("sync-call", arguments);
michael@0 1206 let thread = this._Services.tm.currentThread;
michael@0 1207 let initialReplies = this._repliesNeeded;
michael@0 1208 // Need one more reply to answer the current sync call.
michael@0 1209 this._repliesNeeded++;
michael@0 1210 // Wait for the reply to arrive. Normally we would not want to
michael@0 1211 // spin the event loop, but here we're in a test and our API
michael@0 1212 // specifies a synchronous call, so we spin the loop to wait for
michael@0 1213 // the call to finish.
michael@0 1214 while (this._repliesNeeded > initialReplies) {
michael@0 1215 thread.processNextEvent(true);
michael@0 1216 }
michael@0 1217 },
michael@0 1218
michael@0 1219 /**
michael@0 1220 * Asynchronously call a method in Java,
michael@0 1221 * given the method name followed by a list of arguments.
michael@0 1222 */
michael@0 1223 asyncCall: function (methodName /*, ... */) {
michael@0 1224 this._sendMessage("async-call", arguments);
michael@0 1225 },
michael@0 1226
michael@0 1227 /**
michael@0 1228 * Disconnect with Java.
michael@0 1229 */
michael@0 1230 disconnect: function () {
michael@0 1231 this._Services.obs.removeObserver(this, this._EVENT_TYPE);
michael@0 1232 },
michael@0 1233 };

mercurial