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