From 2b036e45c518c1c6d9f217d6ad6001e4a40998b1 Mon Sep 17 00:00:00 2001 From: Victor Porof Date: Fri, 5 Jul 2019 11:01:24 +0200 Subject: [PATCH] Bug 1561435 - Format testing/, a=automatic-formatting # ignore-this-changeset Differential Revision: https://phabricator.services.mozilla.com/D35962 --HG-- extra : source : c0948f31e520ca087279cf429ca5f1db5a8341b8 --- .eslintrc.js | 1 - .prettierignore | 4 +- testing/marionette/accessibility.js | 74 +- testing/marionette/action.js | 356 ++++--- testing/marionette/addon.js | 24 +- testing/marionette/assert.js | 49 +- testing/marionette/browser.js | 98 +- testing/marionette/capabilities.js | 171 ++-- testing/marionette/capture.js | 95 +- testing/marionette/cert.js | 19 +- testing/marionette/components/marionette.js | 103 +- testing/marionette/cookie.js | 101 +- testing/marionette/dom.js | 22 +- testing/marionette/driver.js | 526 ++++++---- testing/marionette/element.js | 277 +++--- testing/marionette/error.js | 30 +- testing/marionette/evaluate.js | 145 +-- testing/marionette/event.js | 242 +++-- testing/marionette/format.js | 29 +- testing/marionette/interaction.js | 124 ++- testing/marionette/l10n.js | 14 +- testing/marionette/listener.js | 525 ++++++---- testing/marionette/log.js | 5 +- testing/marionette/message.js | 33 +- testing/marionette/modal.js | 34 +- testing/marionette/navigate.js | 11 +- testing/marionette/packets.js | 54 +- testing/marionette/prefs.js | 31 +- testing/marionette/proxy.js | 49 +- testing/marionette/reftest.js | 187 ++-- testing/marionette/server.js | 82 +- testing/marionette/stream-utils.js | 32 +- testing/marionette/sync.js | 170 ++-- testing/marionette/test/unit/test_action.js | 318 +++--- testing/marionette/test/unit/test_assert.js | 30 +- testing/marionette/test/unit/test_browser.js | 4 +- .../marionette/test/unit/test_capabilities.js | 212 ++-- testing/marionette/test/unit/test_cookie.js | 95 +- testing/marionette/test/unit/test_dom.js | 75 +- testing/marionette/test/unit/test_element.js | 207 ++-- testing/marionette/test/unit/test_error.js | 66 +- testing/marionette/test/unit/test_evaluate.js | 63 +- testing/marionette/test/unit/test_format.js | 43 +- testing/marionette/test/unit/test_message.js | 85 +- testing/marionette/test/unit/test_modal.js | 58 +- testing/marionette/test/unit/test_navigate.js | 15 +- testing/marionette/test/unit/test_prefs.js | 23 +- testing/marionette/test/unit/test_sync.js | 141 ++- testing/marionette/transport.js | 67 +- .../BrowserTestUtils/BrowserTestUtils.jsm | 826 ++++++++++------ .../BrowserTestUtils/ContentTask.jsm | 53 +- .../BrowserTestUtils/ContentTaskUtils.jsm | 65 +- .../content/content-about-page-utils.js | 35 +- .../BrowserTestUtils/content/content-task.js | 36 +- .../BrowserTestUtils/content/content-utils.js | 40 +- testing/mochitest/ShutdownLeaksCollector.jsm | 15 +- testing/mochitest/api.js | 78 +- .../browser_baselinecoverage.js | 2 +- ...browser_baselinecoverage_browser-chrome.js | 17 +- testing/mochitest/browser-test.js | 935 ++++++++++++------ testing/mochitest/chrome-harness.js | 69 +- testing/mochitest/chunkifyTests.js | 7 +- testing/mochitest/manifestLibrary.js | 36 +- testing/mochitest/mochitest-e10s-utils.js | 17 +- testing/mochitest/server.js | 553 +++++++---- testing/mochitest/start_desktop.js | 9 +- .../tests/browser/browser_BrowserTestUtils.js | 106 +- .../browser_browserLoaded_content_loaded.js | 23 +- ...rowser_fail_add_task_uncaught_rejection.js | 3 +- .../browser_fail_uncaught_rejection.js | 3 +- .../tests/browser/browser_getTestFile.js | 67 +- .../mochitest/tests/browser/browser_head.js | 6 +- .../tests/browser/browser_parameters.js | 1 - .../tests/browser/browser_privileges.js | 5 +- .../browser_uncaught_rejection_expected.js | 3 +- .../tests/browser/browser_waitForFocus.js | 36 +- testing/mochitest/tests/browser/head.js | 6 +- testing/modules/AppData.jsm | 16 +- testing/modules/AppInfo.jsm | 44 +- testing/modules/Assert.jsm | 140 ++- testing/modules/CoverageUtils.jsm | 51 +- testing/modules/FileTestUtils.jsm | 28 +- testing/modules/MockRegistrar.jsm | 39 +- testing/modules/MockRegistry.jsm | 18 +- testing/modules/Sinon.jsm | 28 +- testing/modules/StructuredLog.jsm | 90 +- testing/modules/TestUtils.jsm | 41 +- testing/modules/tests/xpcshell/test_assert.js | 206 ++-- .../tests/xpcshell/test_mockRegistrar.js | 40 +- .../tests/xpcshell/test_structuredlog.js | 19 +- .../mozlog/mozlog/formatters/html/main.js | 231 +++-- testing/raptor/webext/raptor/benchmark.js | 4 +- testing/raptor/webext/raptor/pageload.js | 84 +- testing/raptor/webext/raptor/runner.js | 141 +-- testing/specialpowers/api.js | 31 +- .../specialpowers/content/MockColorPicker.jsm | 21 +- .../specialpowers/content/MockFilePicker.jsm | 151 +-- .../content/MockPermissionPrompt.jsm | 28 +- .../content/SpecialPowersAPI.jsm | 887 ++++++++++------- .../content/SpecialPowersAPIParent.jsm | 285 ++++-- .../content/SpecialPowersChild.jsm | 55 +- .../content/SpecialPowersParent.jsm | 43 +- .../content/SpecialPowersSandbox.jsm | 33 +- .../specialpowers/content/WrapPrivileged.jsm | 111 ++- testing/talos/talos/bootstrap.js | 21 +- testing/talos/talos/pageloader/api.js | 50 +- .../pageloader/chrome/MozillaFileLogger.js | 40 +- .../talos/talos/pageloader/chrome/Profiler.js | 106 +- .../talos/pageloader/chrome/lh_fnbpaint.js | 28 +- .../talos/talos/pageloader/chrome/lh_hero.js | 24 +- .../talos/talos/pageloader/chrome/lh_moz.js | 19 +- .../talos/pageloader/chrome/pageloader.js | 324 ++++-- testing/talos/talos/pageloader/chrome/quit.js | 8 +- .../talos/talos/pageloader/chrome/report.js | 81 +- .../talos/talos/pageloader/chrome/tscroll.js | 132 ++- .../talos/talos/pageloader/chrome/utils.js | 7 +- .../talos/talos/scripts/MozillaFileLogger.js | 41 +- testing/talos/talos/scripts/Profiler.js | 49 +- testing/talos/talos/scripts/talos-debug.js | 93 +- testing/talos/talos/scripts/xpigen.js | 66 +- .../startup_test/sessionrestore/addon/api.js | 44 +- .../startup_about_home_paint/addon/api.js | 14 +- testing/talos/talos/talos-powers/api.js | 111 ++- .../chrome/talos-powers-content.js | 174 ++-- .../content/TalosContentProfiler.js | 32 +- .../content/TalosParentProfiler.jsm | 40 +- .../content/TalosPowersContent.js | 41 +- testing/talos/talos/tests/a11y/a11y.js | 12 +- .../talos/tests/cpstartup/extension/api.js | 61 +- .../tests/cpstartup/extension/framescript.js | 39 +- .../talos/talos/tests/devtools/addon/api.js | 9 +- .../devtools/addon/content/damp-tests.js | 105 +- .../tests/devtools/addon/content/damp.js | 128 ++- .../addon/content/tests/debugger/cold-open.js | 7 +- .../content/tests/debugger/complicated.js | 12 +- .../addon/content/tests/debugger/custom.js | 22 +- .../tests/debugger/debugger-helpers.js | 47 +- .../addon/content/tests/debugger/simple.js | 12 +- .../devtools/addon/content/tests/head.js | 7 +- .../content/tests/inspector/cold-open.js | 9 +- .../content/tests/inspector/complicated.js | 9 +- .../addon/content/tests/inspector/custom.js | 30 +- .../addon/content/tests/inspector/layout.js | 25 +- .../content/tests/inspector/mutations.js | 21 +- .../addon/content/tests/inspector/simple.js | 9 +- .../content/tests/netmonitor/cold-open.js | 9 +- .../content/tests/netmonitor/complicated.js | 22 +- .../tests/netmonitor/netmonitor-helpers.js | 11 +- .../addon/content/tests/netmonitor/simple.js | 17 +- .../addon/content/tests/server/actor.js | 1 - .../addon/content/tests/server/protocol.js | 23 +- .../addon/content/tests/server/spec.js | 4 +- .../content/tests/styleeditor/complicated.js | 15 +- .../addon/content/tests/styleeditor/simple.js | 10 +- .../tests/toolbox/panels-in-background.js | 10 +- .../content/tests/webconsole/autocomplete.js | 1 - .../addon/content/tests/webconsole/bulklog.js | 22 +- .../content/tests/webconsole/cold-open.js | 9 +- .../content/tests/webconsole/complicated.js | 9 +- .../addon/content/tests/webconsole/custom.js | 13 +- .../content/tests/webconsole/objectexpand.js | 26 +- .../content/tests/webconsole/openwithcache.js | 21 +- .../addon/content/tests/webconsole/simple.js | 9 +- .../content/tests/webconsole/streamlog.js | 23 +- .../addon/content/tests/webconsole/typing.js | 10 +- .../talos/tests/devtools/addon/driver.js | 6 +- .../tests/perf-reftest-singletons/util.js | 25 +- .../talos/talos/tests/perf-reftest/util.js | 25 +- testing/talos/talos/tests/tabpaint/api.js | 53 +- .../talos/talos/tests/tabpaint/framescript.js | 146 +-- testing/talos/talos/tests/tabswitch/api.js | 131 ++- .../content/tabswitch-content-process.js | 20 +- testing/talos/talos/tests/tart/addon/api.js | 56 +- .../tests/tart/addon/content/Profiler.js | 49 +- .../tests/tart/addon/content/framescript.js | 79 +- .../talos/tests/tart/addon/content/tart.js | 613 +++++++++--- .../talos/talos/tests/tresize/addon/api.js | 48 +- .../tests/tresize/addon/content/Profiler.js | 49 +- .../tresize/addon/content/framescript.js | 38 +- .../tests/tresize/addon/content/tresize.js | 2 +- testing/talos/talos/tests/twinopen/api.js | 42 +- .../talos/webextensions/dummy/background.js | 54 +- .../talos/webextensions/dummy/content.js | 2 +- testing/xpcshell/dbg-actors.js | 4 +- .../xpcshell/example/unit/check_profile.js | 4 +- .../xpcshell/example/unit/import_module.jsm | 2 +- .../example/unit/test_check_nsIException.js | 6 +- .../unit/test_check_nsIException_failing.js | 1 - .../example/unit/test_do_check_matches.js | 6 +- .../unit/test_do_check_matches_failing.js | 8 +- .../xpcshell/example/unit/test_get_idle.js | 5 +- .../example/unit/test_import_module.js | 4 +- .../example/unit/test_load_httpd_js.js | 2 +- testing/xpcshell/head.js | 627 +++++++----- 194 files changed, 10107 insertions(+), 5510 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 1e02e4c04d22..53789baa5264 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -45,7 +45,6 @@ module.exports = { "overrides": [{ "files": [ "devtools/**", - "testing/**", "toolkit/**", "tools/**", "uriloader/**", diff --git a/.prettierignore b/.prettierignore index 06a4fa792316..c013a692df36 100644 --- a/.prettierignore +++ b/.prettierignore @@ -40,7 +40,6 @@ toolkit/components/telemetry/datareporting-prefs.js toolkit/components/telemetry/healthreport-prefs.js # Ignore all top-level directories for now. -testing/** toolkit/** tools/** uriloader/** @@ -81,6 +80,9 @@ devtools/server/** devtools/shared/** devtools/startup/** +# Ignore testing pref files which aren't parsed normally. +testing/profiles/**/user.js + # Ignore CORS fixtures which require specific resource hashes. dom/security/test/sri/script* diff --git a/testing/marionette/accessibility.js b/testing/marionette/accessibility.js index 777fa0c841a4..eb1354fbec48 100644 --- a/testing/marionette/accessibility.js +++ b/testing/marionette/accessibility.js @@ -4,18 +4,23 @@ "use strict"; -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); -const {ElementNotAccessibleError} = ChromeUtils.import("chrome://marionette/content/error.js"); -const {Log} = ChromeUtils.import("chrome://marionette/content/log.js"); +const { ElementNotAccessibleError } = ChromeUtils.import( + "chrome://marionette/content/error.js" +); +const { Log } = ChromeUtils.import("chrome://marionette/content/log.js"); XPCOMUtils.defineLazyGetter(this, "logger", Log.get); XPCOMUtils.defineLazyGetter(this, "service", () => { try { - return Cc["@mozilla.org/accessibilityService;1"] - .getService(Ci.nsIAccessibilityService); + return Cc["@mozilla.org/accessibilityService;1"].getService( + Ci.nsIAccessibilityService + ); } catch (e) { logger.warn("Accessibility module is not present"); return undefined; @@ -81,7 +86,6 @@ accessibility.ActionableRoles = new Set([ "switch", ]); - /** * Factory function that constructs a new {@code accessibility.Checks} * object with enforced strictness or not. @@ -131,8 +135,9 @@ accessibility.Checks = class { } // First, check if accessibility is ready. - let docAcc = accessibility.service - .getAccessibleFor(element.ownerDocument); + let docAcc = accessibility.service.getAccessibleFor( + element.ownerDocument + ); let state = {}; docAcc.getState(state, {}); if ((state.value & Ci.nsIAccessibleStates.STATE_BUSY) == 0) { @@ -174,8 +179,9 @@ accessibility.Checks = class { }, }; Services.obs.addObserver(eventObserver, "accessible-event"); - }).catch(() => this.error( - "Element does not have an accessible object", element)); + }).catch(() => + this.error("Element does not have an accessible object", element) + ); } /** @@ -191,7 +197,8 @@ accessibility.Checks = class { */ isActionableRole(accessible) { return accessibility.ActionableRoles.has( - accessibility.service.getStringRole(accessible.role)); + accessibility.service.getStringRole(accessible.role) + ); } /** @@ -302,11 +309,13 @@ accessibility.Checks = class { let message; if (visible && hiddenAccessibility) { - message = "Element is not currently visible via the accessibility API " + - "and may not be manipulated by it"; + message = + "Element is not currently visible via the accessibility API " + + "and may not be manipulated by it"; } else if (!visible && !hiddenAccessibility) { - message = "Element is currently only visible via the accessibility API " + - "and can be manipulated by it"; + message = + "Element is currently only visible via the accessibility API " + + "and can be manipulated by it"; } this.error(message, element); } @@ -332,14 +341,18 @@ accessibility.Checks = class { let win = element.ownerGlobal; let disabledAccessibility = this.matchState( - accessible, accessibility.State.Unavailable); - let explorable = win.getComputedStyle(element) - .getPropertyValue("pointer-events") !== "none"; + accessible, + accessibility.State.Unavailable + ); + let explorable = + win.getComputedStyle(element).getPropertyValue("pointer-events") !== + "none"; let message; if (!explorable && !disabledAccessibility) { - message = "Element is enabled but is not explorable via the " + - "accessibility API"; + message = + "Element is enabled but is not explorable via the " + + "accessibility API"; } else if (enabled && disabledAccessibility) { message = "Element is enabled but disabled via the accessibility API"; } else if (!enabled && !disabledAccessibility) { @@ -369,8 +382,9 @@ accessibility.Checks = class { if (!this.hasActionCount(accessible)) { message = "Element does not support any accessible actions"; } else if (!this.isActionableRole(accessible)) { - message = "Element does not have a correct accessibility role " + - "and may not be manipulated via the accessibility API"; + message = + "Element does not have a correct accessibility role " + + "and may not be manipulated via the accessibility API"; } else if (!this.hasValidName(accessible)) { message = "Element is missing an accessible name"; } else if (!this.matchState(accessible, accessibility.State.Focusable)) { @@ -405,14 +419,18 @@ accessibility.Checks = class { return; } - let selectedAccessibility = - this.matchState(accessible, accessibility.State.Selected); + let selectedAccessibility = this.matchState( + accessible, + accessibility.State.Selected + ); let message; if (selected && !selectedAccessibility) { - message = "Element is selected but not selected via the accessibility API"; + message = + "Element is selected but not selected via the accessibility API"; } else if (!selected && selectedAccessibility) { - message = "Element is not selected but selected via the accessibility API"; + message = + "Element is not selected but selected via the accessibility API"; } this.error(message, element); } @@ -433,7 +451,7 @@ accessibility.Checks = class { return; } if (element) { - let {id, tagName, className} = element; + let { id, tagName, className } = element; message += `: id: ${id}, tagName: ${tagName}, className: ${className}`; } diff --git a/testing/marionette/action.js b/testing/marionette/action.js index 8854c05fe093..68ee3c688baa 100644 --- a/testing/marionette/action.js +++ b/testing/marionette/action.js @@ -7,18 +7,20 @@ "use strict"; -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {assert} = ChromeUtils.import("chrome://marionette/content/assert.js"); -const {element} = ChromeUtils.import("chrome://marionette/content/element.js"); +const { assert } = ChromeUtils.import("chrome://marionette/content/assert.js"); +const { element } = ChromeUtils.import( + "chrome://marionette/content/element.js" +); const { InvalidArgumentError, MoveTargetOutOfBoundsError, UnsupportedOperationError, } = ChromeUtils.import("chrome://marionette/content/error.js"); -const {event} = ChromeUtils.import("chrome://marionette/content/event.js"); -const {pprint} = ChromeUtils.import("chrome://marionette/content/format.js"); -const {Sleep} = ChromeUtils.import("chrome://marionette/content/sync.js"); +const { event } = ChromeUtils.import("chrome://marionette/content/event.js"); +const { pprint } = ChromeUtils.import("chrome://marionette/content/format.js"); +const { Sleep } = ChromeUtils.import("chrome://marionette/content/sync.js"); this.EXPORTED_SYMBOLS = ["action"]; @@ -54,10 +56,10 @@ const ACTIONS = { /** Map from normalized key value to UI Events modifier key name */ const MODIFIER_NAME_LOOKUP = { - "Alt": "alt", - "Shift": "shift", - "Control": "ctrl", - "Meta": "meta", + Alt: "alt", + Shift: "shift", + Control: "ctrl", + Meta: "meta", }; /** Map from raw key (codepoint) to normalized key value */ @@ -202,7 +204,7 @@ const KEY_CODE_LOOKUP = { "@": "Digit2", "#": "Digit3", "3": "Digit3", - "$": "Digit4", + $: "Digit4", "4": "Digit4", "%": "Digit5", "5": "Digit5", @@ -236,60 +238,60 @@ const KEY_CODE_LOOKUP = { "\uE016": "Insert", "<": "IntlBackslash", ">": "IntlBackslash", - "A": "KeyA", - "a": "KeyA", - "B": "KeyB", - "b": "KeyB", - "C": "KeyC", - "c": "KeyC", - "D": "KeyD", - "d": "KeyD", - "E": "KeyE", - "e": "KeyE", - "F": "KeyF", - "f": "KeyF", - "G": "KeyG", - "g": "KeyG", - "H": "KeyH", - "h": "KeyH", - "I": "KeyI", - "i": "KeyI", - "J": "KeyJ", - "j": "KeyJ", - "K": "KeyK", - "k": "KeyK", - "L": "KeyL", - "l": "KeyL", - "M": "KeyM", - "m": "KeyM", - "N": "KeyN", - "n": "KeyN", - "O": "KeyO", - "o": "KeyO", - "P": "KeyP", - "p": "KeyP", - "Q": "KeyQ", - "q": "KeyQ", - "R": "KeyR", - "r": "KeyR", - "S": "KeyS", - "s": "KeyS", - "T": "KeyT", - "t": "KeyT", - "U": "KeyU", - "u": "KeyU", - "V": "KeyV", - "v": "KeyV", - "W": "KeyW", - "w": "KeyW", - "X": "KeyX", - "x": "KeyX", - "Y": "KeyY", - "y": "KeyY", - "Z": "KeyZ", - "z": "KeyZ", + A: "KeyA", + a: "KeyA", + B: "KeyB", + b: "KeyB", + C: "KeyC", + c: "KeyC", + D: "KeyD", + d: "KeyD", + E: "KeyE", + e: "KeyE", + F: "KeyF", + f: "KeyF", + G: "KeyG", + g: "KeyG", + H: "KeyH", + h: "KeyH", + I: "KeyI", + i: "KeyI", + J: "KeyJ", + j: "KeyJ", + K: "KeyK", + k: "KeyK", + L: "KeyL", + l: "KeyL", + M: "KeyM", + m: "KeyM", + N: "KeyN", + n: "KeyN", + O: "KeyO", + o: "KeyO", + P: "KeyP", + p: "KeyP", + Q: "KeyQ", + q: "KeyQ", + R: "KeyR", + r: "KeyR", + S: "KeyS", + s: "KeyS", + T: "KeyT", + t: "KeyT", + U: "KeyU", + u: "KeyU", + V: "KeyV", + v: "KeyV", + W: "KeyW", + w: "KeyW", + X: "KeyX", + x: "KeyX", + Y: "KeyY", + y: "KeyY", + Z: "KeyZ", + z: "KeyZ", "-": "Minus", - "_": "Minus", + _: "Minus", "\uE01A": "Numpad0", "\uE05C": "Numpad0", "\uE01B": "Numpad1", @@ -323,7 +325,7 @@ const KEY_CODE_LOOKUP = { "\uE01F": "PageUp", ".": "Period", ">": "Period", - "\"": "Quote", + '"': "Quote", "'": "Quote", ":": "Semicolon", ";": "Semicolon", @@ -367,9 +369,11 @@ action.PointerOrigin.get = function(obj) { assert.in(name, this, pprint`Unknown pointer-move origin: ${obj}`); origin = this[name]; } else if (!element.isDOMElement(obj)) { - throw new InvalidArgumentError("Expected 'origin' to be undefined, " + + throw new InvalidArgumentError( + "Expected 'origin' to be undefined, " + '"viewport", "pointer", ' + - pprint`or an element, got: ${obj}`); + pprint`or an element, got: ${obj}` + ); } return origin; }; @@ -465,10 +469,13 @@ class InputState { assert.in(type, ACTIONS, pprint`Unknown action type: ${type}`); let name = type == "none" ? "Null" : capitalize(type); if (name == "Pointer") { - if (!obj.pointerType && - (!obj.parameters || !obj.parameters.pointerType)) { + if ( + !obj.pointerType && + (!obj.parameters || !obj.parameters.pointerType) + ) { throw new InvalidArgumentError( - pprint`Expected obj to have pointerType, got ${obj}`); + pprint`Expected obj to have pointerType, got ${obj}` + ); } let pointerType = obj.pointerType || obj.parameters.pointerType; return new action.InputState[name](pointerType); @@ -509,9 +516,10 @@ action.InputState.Key = class Key extends InputState { this[MODIFIER_NAME_LOOKUP[key]] = value; } else { throw new InvalidArgumentError( - "Expected 'key' to be one of " + + "Expected 'key' to be one of " + Object.keys(MODIFIER_NAME_LOOKUP) + - pprint`, got ${key}`); + pprint`, got ${key}` + ); } } @@ -578,8 +586,10 @@ action.InputState.Pointer = class Pointer extends InputState { constructor(subtype) { super(); this.pressed = new Set(); - assert.defined(subtype, - pprint`Expected subtype to be defined, got ${subtype}`); + assert.defined( + subtype, + pprint`Expected subtype to be defined, got ${subtype}` + ); this.subtype = action.PointerType.get(subtype); this.x = 0; this.y = 0; @@ -613,7 +623,7 @@ action.InputState.Pointer = class Pointer extends InputState { return this.pressed.add(button); } - /** + /** * Remove |button| from the set of pressed buttons. * * @param {number} button @@ -687,13 +697,17 @@ action.Action = class { let subtype = actionItem.type; if (!subtypes.has(subtype)) { throw new InvalidArgumentError( - `Unknown subtype for ${type} action: ${subtype}`); + `Unknown subtype for ${type} action: ${subtype}` + ); } let item = new action.Action(id, type, subtype); if (type === "pointer") { - action.processPointerAction(id, - action.PointerParameters.fromJSON(actionSequence.parameters), item); + action.processPointerAction( + id, + action.PointerParameters.fromJSON(actionSequence.parameters), + item + ); } switch (item.subtype) { @@ -703,35 +717,45 @@ action.Action = class { // TODO countGraphemes // TODO key.value could be a single code point like "\uE012" // (see rawKey) or "grapheme cluster" - assert.string(key, - "Expected 'value' to be a string that represents single code point " + - pprint`or grapheme cluster, got ${key}`); + assert.string( + key, + "Expected 'value' to be a string that represents single code point " + + pprint`or grapheme cluster, got ${key}` + ); item.value = key; break; case action.PointerDown: case action.PointerUp: - assert.positiveInteger(actionItem.button, - pprint`Expected 'button' (${actionItem.button}) to be >= 0`); + assert.positiveInteger( + actionItem.button, + pprint`Expected 'button' (${actionItem.button}) to be >= 0` + ); item.button = actionItem.button; break; case action.PointerMove: item.duration = actionItem.duration; if (typeof item.duration != "undefined") { - assert.positiveInteger(item.duration, - pprint`Expected 'duration' (${item.duration}) to be >= 0`); + assert.positiveInteger( + item.duration, + pprint`Expected 'duration' (${item.duration}) to be >= 0` + ); } item.origin = action.PointerOrigin.get(actionItem.origin); item.x = actionItem.x; if (typeof item.x != "undefined") { - assert.integer(item.x, - pprint`Expected 'x' (${item.x}) to be an Integer`); + assert.integer( + item.x, + pprint`Expected 'x' (${item.x}) to be an Integer` + ); } item.y = actionItem.y; if (typeof item.y != "undefined") { - assert.integer(item.y, - pprint`Expected 'y' (${item.y}) to be an Integer`); + assert.integer( + item.y, + pprint`Expected 'y' (${item.y}) to be an Integer` + ); } break; @@ -743,7 +767,8 @@ action.Action = class { if (typeof item.duration != "undefined") { // eslint-disable-next-line assert.positiveInteger(item.duration, - pprint`Expected 'duration' (${item.duration}) to be >= 0`); + pprint`Expected 'duration' (${item.duration}) to be >= 0` + ); } break; } @@ -773,8 +798,10 @@ action.Chain = class extends Array { * If actions is not an Array. */ static fromJSON(actions) { - assert.array(actions, - pprint`Expected 'actions' to be an array, got ${actions}`); + assert.array( + actions, + pprint`Expected 'actions' to be an array, got ${actions}` + ); let actionsByTick = new action.Chain(); for (let actionSequence of actions) { @@ -783,7 +810,7 @@ action.Chain = class extends Array { let inputSourceActions = action.Sequence.fromJSON(actionSequence); for (let i = 0; i < inputSourceActions.length; i++) { // new tick - if (actionsByTick.length < (i + 1)) { + if (actionsByTick.length < i + 1) { actionsByTick.push([]); } actionsByTick[i].push(inputSourceActions[i]); @@ -823,16 +850,18 @@ action.Sequence = class extends Array { assert.string(id, pprint`Expected 'id' to be a string, got ${id}`); let actionItems = actionSequence.actions; assert.array( - actionItems, - "Expected 'actionSequence.actions' to be an array, " + - pprint`got ${actionSequence.actions}`); + actionItems, + "Expected 'actionSequence.actions' to be an array, " + + pprint`got ${actionSequence.actions}` + ); if (!action.inputStateMap.has(id)) { action.inputStateMap.set(id, inputSourceState); } else if (!action.inputStateMap.get(id).is(inputSourceState)) { throw new InvalidArgumentError( - `Expected ${id} to be mapped to ${inputSourceState}, ` + - `got ${action.inputStateMap.get(id)}`); + `Expected ${id} to be mapped to ${inputSourceState}, ` + + `got ${action.inputStateMap.get(id)}` + ); } let actions = new action.Sequence(); @@ -893,20 +922,26 @@ action.PointerParameters = class { * act.type or pointerParams.pointerType. */ action.processPointerAction = function(id, pointerParams, act) { - if (action.inputStateMap.has(id) && - action.inputStateMap.get(id).type !== act.type) { + if ( + action.inputStateMap.has(id) && + action.inputStateMap.get(id).type !== act.type + ) { throw new InvalidArgumentError( - `Expected 'id' ${id} to be mapped to InputState whose type is ` + + `Expected 'id' ${id} to be mapped to InputState whose type is ` + action.inputStateMap.get(id).type + - pprint` , got ${act.type}`); + pprint` , got ${act.type}` + ); } let pointerType = pointerParams.pointerType; - if (action.inputStateMap.has(id) && - action.inputStateMap.get(id).subtype !== pointerType) { + if ( + action.inputStateMap.has(id) && + action.inputStateMap.get(id).subtype !== pointerType + ) { throw new InvalidArgumentError( - `Expected 'id' ${id} to be mapped to InputState whose subtype is ` + + `Expected 'id' ${id} to be mapped to InputState whose subtype is ` + action.inputStateMap.get(id).subtype + - pprint` , got ${pointerType}`); + pprint` , got ${pointerType}` + ); } act.pointerType = pointerParams.pointerType; }; @@ -915,7 +950,7 @@ action.processPointerAction = function(id, pointerParams, act) { action.Key = class { constructor(rawKey) { this.key = NORMALIZED_KEY_LOOKUP[rawKey] || rawKey; - this.code = KEY_CODE_LOOKUP[rawKey]; + this.code = KEY_CODE_LOOKUP[rawKey]; this.location = KEY_LOCATION_LOOKUP[rawKey] || 0; this.altKey = false; this.shiftKey = false; @@ -991,9 +1026,10 @@ action.dispatch = function(chain, win, specCompatPointerOrigin = true) { let chainEvents = (async () => { for (let tickActions of chain) { await action.dispatchTickActions( - tickActions, - action.computeTickDuration(tickActions), - win); + tickActions, + action.computeTickDuration(tickActions), + win + ); } })(); return chainEvents; @@ -1037,8 +1073,9 @@ action.dispatchTickActions = function(tickActions, tickDuration, win) { action.computeTickDuration = function(tickActions) { let max = 0; for (let a of tickActions) { - let affectsWallClockTime = a.subtype == action.Pause || - (a.type == "pointer" && a.subtype == action.PointerMove); + let affectsWallClockTime = + a.subtype == action.Pause || + (a.type == "pointer" && a.subtype == action.PointerMove); if (affectsWallClockTime && a.duration) { max = Math.max(a.duration, max); } @@ -1060,9 +1097,8 @@ action.computeTickDuration = function(tickActions) { * @return {Map.} * x and y coordinates of pointer destination. */ -action.computePointerDestination = function( - a, inputState, center = undefined) { - let {x, y} = a; +action.computePointerDestination = function(a, inputState, center = undefined) { + let { x, y } = a; switch (a.origin) { case action.PointerOrigin.Viewport: break; @@ -1078,7 +1114,7 @@ action.computePointerDestination = function( x += center.x; y += center.y; } - return {"x": x, "y": y}; + return { x, y }; }; /** @@ -1111,8 +1147,7 @@ function toEvents(tickDuration, win) { return dispatchPointerUp(a, inputState, win); case action.PointerMove: - return dispatchPointerMove( - a, inputState, tickDuration, win); + return dispatchPointerMove(a, inputState, tickDuration, win); case action.PointerCancel: throw new UnsupportedOperationError(); @@ -1149,7 +1184,7 @@ function dispatchKeyDown(a, inputState, win) { } // Append a copy of |a| with keyUp subtype - action.inputsToCancel.push(Object.assign({}, a, {subtype: action.KeyUp})); + action.inputsToCancel.push(Object.assign({}, a, { subtype: action.KeyUp })); keyEvent.update(inputState); event.sendKeyDown(a.value, keyEvent, win); @@ -1213,7 +1248,7 @@ function dispatchPointerDown(a, inputState, win) { inputState.press(a.button); // Append a copy of |a| with pointerUp subtype - let copy = Object.assign({}, a, {subtype: action.PointerUp}); + let copy = Object.assign({}, a, { subtype: action.PointerUp }); action.inputsToCancel.push(copy); switch (inputState.subtype) { @@ -1226,29 +1261,35 @@ function dispatchPointerDown(a, inputState, win) { event.DoubleClickTracker.resetClick(); } } else if (event.DoubleClickTracker.isClicked()) { - mouseEvent = Object.assign({}, - mouseEvent, {clickCount: 2}); + mouseEvent = Object.assign({}, mouseEvent, { clickCount: 2 }); } event.synthesizeMouseAtPoint( + inputState.x, + inputState.y, + mouseEvent, + win + ); + if ( + event.MouseButton.isSecondary(a.button) || + (mouseEvent.ctrlKey && Services.appinfo.OS !== "WINNT") + ) { + let contextMenuEvent = Object.assign({}, mouseEvent, { + type: "contextmenu", + }); + event.synthesizeMouseAtPoint( inputState.x, inputState.y, - mouseEvent, - win); - if (event.MouseButton.isSecondary(a.button) || - mouseEvent.ctrlKey && Services.appinfo.OS !== "WINNT") { - let contextMenuEvent = Object.assign({}, - mouseEvent, {type: "contextmenu"}); - event.synthesizeMouseAtPoint( - inputState.x, - inputState.y, - contextMenuEvent, - win); + contextMenuEvent, + win + ); } break; case action.PointerType.Pen: case action.PointerType.Touch: - throw new UnsupportedOperationError("Only 'mouse' pointer type is supported"); + throw new UnsupportedOperationError( + "Only 'mouse' pointer type is supported" + ); default: throw new TypeError(`Unknown pointer type: ${inputState.subtype}`); @@ -1286,16 +1327,21 @@ function dispatchPointerUp(a, inputState, win) { let mouseEvent = new action.Mouse("mouseup", a.button); mouseEvent.update(inputState); if (event.DoubleClickTracker.isClicked()) { - mouseEvent = Object.assign({}, - mouseEvent, {clickCount: 2}); + mouseEvent = Object.assign({}, mouseEvent, { clickCount: 2 }); } event.synthesizeMouseAtPoint( - inputState.x, inputState.y, mouseEvent, win); + inputState.x, + inputState.y, + mouseEvent, + win + ); break; case action.PointerType.Pen: case action.PointerType.Touch: - throw new UnsupportedOperationError("Only 'mouse' pointer type is supported"); + throw new UnsupportedOperationError( + "Only 'mouse' pointer type is supported" + ); default: throw new TypeError(`Unknown pointer type: ${inputState.subtype}`); @@ -1340,12 +1386,14 @@ function dispatchPointerMove(a, inputState, tickDuration, win) { if (!inViewPort(targetX, targetY, win)) { throw new MoveTargetOutOfBoundsError( - `(${targetX}, ${targetY}) is out of bounds of viewport ` + + `(${targetX}, ${targetY}) is out of bounds of viewport ` + `width (${win.innerWidth}) ` + - `and height (${win.innerHeight})`); + `and height (${win.innerHeight})` + ); } - const duration = typeof a.duration == "undefined" ? tickDuration : a.duration; + const duration = + typeof a.duration == "undefined" ? tickDuration : a.duration; if (duration === 0) { // move pointer to destination in one step performOnePointerMove(inputState, targetX, targetY, win); @@ -1359,17 +1407,19 @@ function dispatchPointerMove(a, inputState, tickDuration, win) { let intermediatePointerEvents = (async () => { // wait |fps60| ms before performing first incremental pointer move await new Promise(resolveTimer => - timer.initWithCallback(resolveTimer, fps60, ONE_SHOT)); + timer.initWithCallback(resolveTimer, fps60, ONE_SHOT) + ); let durationRatio = Math.floor(Date.now() - start) / duration; const epsilon = fps60 / duration / 10; - while ((1 - durationRatio) > epsilon) { + while (1 - durationRatio > epsilon) { let x = Math.floor(durationRatio * distanceX + startX); let y = Math.floor(durationRatio * distanceY + startY); performOnePointerMove(inputState, x, y, win); // wait |fps60| ms before performing next pointer move await new Promise(resolveTimer => - timer.initWithCallback(resolveTimer, fps60, ONE_SHOT)); + timer.initWithCallback(resolveTimer, fps60, ONE_SHOT) + ); durationRatio = Math.floor(Date.now() - start) / duration; } @@ -1377,12 +1427,14 @@ function dispatchPointerMove(a, inputState, tickDuration, win) { // perform last pointer move after all incremental moves are resolved and // durationRatio is close enough to 1 - intermediatePointerEvents.then(() => { - performOnePointerMove(inputState, targetX, targetY, win); - resolve(); - }).catch(err => { - reject(err); - }); + intermediatePointerEvents + .then(() => { + performOnePointerMove(inputState, targetX, targetY, win); + resolve(); + }) + .catch(err => { + reject(err); + }); }); } @@ -1401,7 +1453,9 @@ function performOnePointerMove(inputState, targetX, targetY, win) { case action.PointerType.Pen: case action.PointerType.Touch: - throw new UnsupportedOperationError("Only 'mouse' pointer type is supported"); + throw new UnsupportedOperationError( + "Only 'mouse' pointer type is supported" + ); default: throw new TypeError(`Unknown pointer type: ${inputState.subtype}`); diff --git a/testing/marionette/addon.js b/testing/marionette/addon.js index b0d163167e06..ae5fe6727794 100644 --- a/testing/marionette/addon.js +++ b/testing/marionette/addon.js @@ -4,10 +4,16 @@ "use strict"; -const {AddonManager} = ChromeUtils.import("resource://gre/modules/AddonManager.jsm"); -const {FileUtils} = ChromeUtils.import("resource://gre/modules/FileUtils.jsm"); +const { AddonManager } = ChromeUtils.import( + "resource://gre/modules/AddonManager.jsm" +); +const { FileUtils } = ChromeUtils.import( + "resource://gre/modules/FileUtils.jsm" +); -const {UnknownError} = ChromeUtils.import("chrome://marionette/content/error.js"); +const { UnknownError } = ChromeUtils.import( + "chrome://marionette/content/error.js" +); this.EXPORTED_SYMBOLS = ["Addon"]; @@ -21,7 +27,9 @@ const ERRORS = { }; async function installAddon(file) { - let install = await AddonManager.getInstallForFile(file, null, {source: "internal"}); + let install = await AddonManager.getInstallForFile(file, null, { + source: "internal", + }); if (install.error) { throw new UnknownError(ERRORS[install.error]); @@ -76,7 +84,9 @@ class Addon { } } catch (e) { throw new UnknownError( - `Could not install add-on: ${path}: ${e.message}`, e); + `Could not install add-on: ${path}: ${e.message}`, + e + ); } return addon.id; @@ -104,7 +114,9 @@ class Addon { onOperationCancelled: addon => { if (addon.id === candidate.id) { AddonManager.removeAddonListener(listener); - throw new UnknownError(`Uninstall of ${candidate.id} has been canceled`); + throw new UnknownError( + `Uninstall of ${candidate.id} has been canceled` + ); } }, diff --git a/testing/marionette/assert.js b/testing/marionette/assert.js index 5ddd56656faf..ad772ee2b115 100644 --- a/testing/marionette/assert.js +++ b/testing/marionette/assert.js @@ -4,9 +4,13 @@ "use strict"; -const {AppConstants} = ChromeUtils.import("resource://gre/modules/AppConstants.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { AppConstants } = ChromeUtils.import( + "resource://gre/modules/AppConstants.jsm" +); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); const { InvalidArgumentError, @@ -16,7 +20,7 @@ const { UnexpectedAlertOpenError, UnsupportedOperationError, } = ChromeUtils.import("chrome://marionette/content/error.js"); -const {pprint} = ChromeUtils.import("chrome://marionette/content/format.js"); +const { pprint } = ChromeUtils.import("chrome://marionette/content/format.js"); XPCOMUtils.defineLazyModuleGetters(this, { evaluate: "chrome://marionette/content/evaluate.js", @@ -27,9 +31,9 @@ this.EXPORTED_SYMBOLS = ["assert"]; const isFennec = () => AppConstants.platform == "android"; const isFirefox = () => - Services.appinfo.ID == "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"; + Services.appinfo.ID == "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"; const isThunderbird = () => - Services.appinfo.ID == "{3550f703-e582-4d05-9a08-453d09bdfdc6}"; + Services.appinfo.ID == "{3550f703-e582-4d05-9a08-453d09bdfdc6}"; /** * Shorthands for common assertions made in Marionette. @@ -73,8 +77,9 @@ assert.acyclic = function(obj, msg = "", error = JavaScriptError) { * If driver does not have a session ID. */ assert.session = function(driver, msg = "") { - assert.that(sessionID => sessionID, - msg, InvalidSessionIDError)(driver.sessionID); + assert.that(sessionID => sessionID, msg, InvalidSessionIDError)( + driver.sessionID + ); return driver.sessionID; }; @@ -103,8 +108,11 @@ assert.firefox = function(msg = "") { */ assert.desktop = function(msg = "") { msg = msg || "Only supported in desktop applications"; - assert.that(obj => isFirefox(obj) || isThunderbird(obj), - msg, UnsupportedOperationError)(); + assert.that( + obj => isFirefox(obj) || isThunderbird(obj), + msg, + UnsupportedOperationError + )(); }; /** @@ -137,7 +145,9 @@ assert.fennec = function(msg = "") { */ assert.content = function(context, msg = "") { msg = msg || "Only supported in content context"; - assert.that(c => c.toString() == "content", msg, UnsupportedOperationError)(context); + assert.that(c => c.toString() == "content", msg, UnsupportedOperationError)( + context + ); }; /** @@ -170,9 +180,9 @@ assert.open = function(context, msg = "") { } msg = msg || "Browsing context has been discarded"; - return assert.that(ctx => ctx && !ctx.closed, - msg, - NoSuchWindowError)(context); + return assert.that(ctx => ctx && !ctx.closed, msg, NoSuchWindowError)( + context + ); }; /** @@ -187,9 +197,11 @@ assert.open = function(context, msg = "") { * If there is a user prompt. */ assert.noUserPrompt = function(dialog, msg = "") { - assert.that(d => d === null || typeof d == "undefined", - msg, - UnexpectedAlertOpenError)(dialog); + assert.that( + d => d === null || typeof d == "undefined", + msg, + UnexpectedAlertOpenError + )(dialog); }; /** @@ -410,8 +422,7 @@ assert.array = function(obj, msg = "") { * and which may throw error with message * if predicate evaluates to false. */ -assert.that = function( - predicate, message = "", error = InvalidArgumentError) { +assert.that = function(predicate, message = "", error = InvalidArgumentError) { return obj => { if (!predicate(obj)) { throw new error(message); diff --git a/testing/marionette/browser.js b/testing/marionette/browser.js index 13f6c87b5f1d..dead62df27a2 100644 --- a/testing/marionette/browser.js +++ b/testing/marionette/browser.js @@ -5,16 +5,21 @@ "use strict"; /* global frame */ -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); -const {WebElementEventTarget} = ChromeUtils.import("chrome://marionette/content/dom.js"); -const {element} = ChromeUtils.import("chrome://marionette/content/element.js"); -const { - NoSuchWindowError, - UnsupportedOperationError, -} = ChromeUtils.import("chrome://marionette/content/error.js"); -const {Log} = ChromeUtils.import("chrome://marionette/content/log.js"); +const { WebElementEventTarget } = ChromeUtils.import( + "chrome://marionette/content/dom.js" +); +const { element } = ChromeUtils.import( + "chrome://marionette/content/element.js" +); +const { NoSuchWindowError, UnsupportedOperationError } = ChromeUtils.import( + "chrome://marionette/content/error.js" +); +const { Log } = ChromeUtils.import("chrome://marionette/content/log.js"); const { MessageManagerDestroyedPromise, waitForEvent, @@ -81,7 +86,7 @@ browser.getBrowserForTab = function(tab) { if (tab && "browser" in tab) { return tab.browser; - // Firefox + // Firefox } else if (tab && "linkedBrowser" in tab) { return tab.linkedBrowser; } @@ -103,11 +108,11 @@ browser.getTabBrowser = function(window) { if ("BrowserApp" in window) { return window.BrowserApp; - // Firefox + // Firefox } else if ("gBrowser" in window) { return window.gBrowser; - // Thunderbird + // Thunderbird } else if (window.document.getElementById("tabmail")) { return window.document.getElementById("tabmail"); } @@ -173,8 +178,10 @@ browser.Context = class { get contentBrowser() { if (this.tab) { return browser.getBrowserForTab(this.tab); - } else if (this.tabBrowser && - this.driver.isReftestBrowser(this.tabBrowser)) { + } else if ( + this.tabBrowser && + this.driver.isReftestBrowser(this.tabBrowser) + ) { return this.tabBrowser; } @@ -232,7 +239,8 @@ browser.Context = class { return this.contentBrowser.contentTitle; } throw new NoSuchWindowError( - "Current window does not have a content browser"); + "Current window does not have a content browser" + ); } /** @@ -251,7 +259,8 @@ browser.Context = class { return this.contentBrowser.currentURI; } throw new NoSuchWindowError( - "Current window does not have a content browser"); + "Current window does not have a content browser" + ); } /** @@ -282,7 +291,9 @@ browser.Context = class { // The modal is a direct sibling of the browser element. // See tabbrowser.xml's getTabModalPromptBox. let modalElements = br.parentNode.getElementsByTagNameNS( - XUL_NS, "tabmodalprompt"); + XUL_NS, + "tabmodalprompt" + ); return br.tabModalPromptBox.prompts.get(modalElements[0]); } @@ -295,7 +306,8 @@ browser.Context = class { */ closeWindow() { let destroyed = new MessageManagerDestroyedPromise( - this.window.messageManager); + this.window.messageManager + ); let unloaded = waitForEvent(this.window, "unload"); this.window.close(); @@ -312,7 +324,7 @@ browser.Context = class { async focusWindow() { if (Services.focus.activeWindow != this.window) { let activated = waitForEvent(this.window, "activate"); - let focused = waitForEvent(this.window, "focus", {capture: true}); + let focused = waitForEvent(this.window, "focus", { capture: true }); this.window.focus(); @@ -335,9 +347,11 @@ browser.Context = class { let win = this.window.OpenBrowserWindow(); let activated = waitForEvent(win, "activate"); - let focused = waitForEvent(win, "focus", {capture: true}); - let startup = waitForObserverTopic("browser-delayed-startup-finished", - subject => subject == win); + let focused = waitForEvent(win, "focus", { capture: true }); + let startup = waitForObserverTopic( + "browser-delayed-startup-finished", + subject => subject == win + ); win.focus(); await Promise.all([activated, focused, startup]); @@ -352,7 +366,8 @@ browser.Context = class { default: throw new UnsupportedOperationError( - `openWindow() not supported in ${this.driver.appName}`); + `openWindow() not supported in ${this.driver.appName}` + ); } } @@ -368,10 +383,12 @@ browser.Context = class { closeTab() { // If the current window is not a browser then close it directly. Do the // same if only one remaining tab is open, or no tab selected at all. - if (!this.tabBrowser || - !this.tabBrowser.tabs || - this.tabBrowser.tabs.length === 1 || - !this.tab) { + if ( + !this.tabBrowser || + !this.tabBrowser.tabs || + this.tabBrowser.tabs.length === 1 || + !this.tab + ) { return this.closeWindow(); } @@ -392,7 +409,8 @@ browser.Context = class { default: throw new UnsupportedOperationError( - `closeTab() not supported in ${this.driver.appName}`); + `closeTab() not supported in ${this.driver.appName}` + ); } return Promise.all([destroyed, tabClosed]); @@ -425,7 +443,8 @@ browser.Context = class { default: throw new UnsupportedOperationError( - `openTab() not supported in ${this.driver.appName}`); + `openTab() not supported in ${this.driver.appName}` + ); } await tabOpened; @@ -482,7 +501,8 @@ browser.Context = class { default: throw new UnsupportedOperationError( - `switchToTab() not supported in ${this.driver.appName}`); + `switchToTab() not supported in ${this.driver.appName}` + ); } } @@ -534,15 +554,15 @@ browser.Context = class { } /** - * This function intercepts commands interacting with content and queues - * or executes them as needed. - * - * No commands interacting with content are safe to process until - * the new listener script is loaded and registered itself. - * This occurs when a command whose effect is asynchronous (such - * as goBack) results in process change of the frame script and new - * commands are subsequently posted to the server. - */ + * This function intercepts commands interacting with content and queues + * or executes them as needed. + * + * No commands interacting with content are safe to process until + * the new listener script is loaded and registered itself. + * This occurs when a command whose effect is asynchronous (such + * as goBack) results in process change of the frame script and new + * commands are subsequently posted to the server. + */ executeWhenReady(cb) { if (this._needsFlushPendingCommands) { this.pendingCommands.push(cb); diff --git a/testing/marionette/capabilities.js b/testing/marionette/capabilities.js index 5e877096b5cd..d8465eb787a3 100644 --- a/testing/marionette/capabilities.js +++ b/testing/marionette/capabilities.js @@ -4,17 +4,19 @@ "use strict"; -const {Preferences} = ChromeUtils.import("resource://gre/modules/Preferences.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { Preferences } = ChromeUtils.import( + "resource://gre/modules/Preferences.jsm" +); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); -const {assert} = ChromeUtils.import("chrome://marionette/content/assert.js"); -const { - InvalidArgumentError, -} = ChromeUtils.import("chrome://marionette/content/error.js"); -const { - pprint, -} = ChromeUtils.import("chrome://marionette/content/format.js"); +const { assert } = ChromeUtils.import("chrome://marionette/content/assert.js"); +const { InvalidArgumentError } = ChromeUtils.import( + "chrome://marionette/content/error.js" +); +const { pprint } = ChromeUtils.import("chrome://marionette/content/format.js"); XPCOMUtils.defineLazyGlobalGetters(this, ["URL"]); @@ -28,9 +30,13 @@ this.EXPORTED_SYMBOLS = [ // Enable testing this module, as Services.appinfo.* is not available // in xpcshell tests. -const appinfo = {name: "", version: ""}; -try { appinfo.name = Services.appinfo.name.toLowerCase(); } catch (e) {} -try { appinfo.version = Services.appinfo.version; } catch (e) {} +const appinfo = { name: "", version: "" }; +try { + appinfo.name = Services.appinfo.name.toLowerCase(); +} catch (e) {} +try { + appinfo.version = Services.appinfo.version; +} catch (e) {} /** Representation of WebDriver session timeouts. */ class Timeouts { @@ -43,7 +49,9 @@ class Timeouts { this.script = 30000; } - toString() { return "[object Timeouts]"; } + toString() { + return "[object Timeouts]"; + } /** Marshals timeout durations to a JSON Object. */ toJSON() { @@ -55,28 +63,36 @@ class Timeouts { } static fromJSON(json) { - assert.object(json, - pprint`Expected "timeouts" to be an object, got ${json}`); + assert.object( + json, + pprint`Expected "timeouts" to be an object, got ${json}` + ); let t = new Timeouts(); for (let [type, ms] of Object.entries(json)) { switch (type) { case "implicit": - t.implicit = assert.positiveInteger(ms, - pprint`Expected ${type} to be a positive integer, got ${ms}`); + t.implicit = assert.positiveInteger( + ms, + pprint`Expected ${type} to be a positive integer, got ${ms}` + ); break; case "script": if (ms !== null) { - assert.positiveInteger(ms, - pprint`Expected ${type} to be a positive integer, got ${ms}`); + assert.positiveInteger( + ms, + pprint`Expected ${type} to be a positive integer, got ${ms}` + ); } t.script = ms; break; case "pageLoad": - t.pageLoad = assert.positiveInteger(ms, - pprint`Expected ${type} to be a positive integer, got ${ms}`); + t.pageLoad = assert.positiveInteger( + ms, + pprint`Expected ${type} to be a positive integer, got ${ms}` + ); break; default: @@ -179,14 +195,19 @@ class Proxy { } if (this.noProxy) { - Preferences.set("network.proxy.no_proxies_on", this.noProxy.join(", ")); + Preferences.set( + "network.proxy.no_proxies_on", + this.noProxy.join(", ") + ); } return true; case "pac": Preferences.set("network.proxy.type", 2); Preferences.set( - "network.proxy.autoconfig_url", this.proxyAutoconfigUrl); + "network.proxy.autoconfig_url", + this.proxyAutoconfigUrl + ); return true; case "system": @@ -207,13 +228,17 @@ class Proxy { */ static fromJSON(json) { function stripBracketsFromIpv6Hostname(hostname) { - return hostname.includes(":") ? hostname.replace(/[\[\]]/g, "") : hostname; + return hostname.includes(":") + ? hostname.replace(/[\[\]]/g, "") + : hostname; } // Parse hostname and optional port from host function fromHost(scheme, host) { - assert.string(host, - pprint`Expected proxy "host" to be a string, got ${host}`); + assert.string( + host, + pprint`Expected proxy "host" to be a string, got ${host}` + ); if (host.includes("://")) { throw new InvalidArgumentError(`${host} contains a scheme`); @@ -247,13 +272,16 @@ class Proxy { } } - if (url.username != "" || - url.password != "" || - url.pathname != "/" || - url.search != "" || - url.hash != "") { + if ( + url.username != "" || + url.password != "" || + url.pathname != "/" || + url.search != "" || + url.hash != "" + ) { throw new InvalidArgumentError( - `${host} was not of the form host[:port]`); + `${host} was not of the form host[:port]` + ); } return [hostname, port]; @@ -266,10 +294,15 @@ class Proxy { assert.object(json, pprint`Expected "proxy" to be an object, got ${json}`); - assert.in("proxyType", json, - pprint`Expected "proxyType" in "proxy" object, got ${json}`); - p.proxyType = assert.string(json.proxyType, - pprint`Expected "proxyType" to be a string, got ${json.proxyType}`); + assert.in( + "proxyType", + json, + pprint`Expected "proxyType" in "proxy" object, got ${json}` + ); + p.proxyType = assert.string( + json.proxyType, + pprint`Expected "proxyType" to be a string, got ${json.proxyType}` + ); switch (p.proxyType) { case "autodetect": @@ -278,9 +311,11 @@ class Proxy { break; case "pac": - p.proxyAutoconfigUrl = assert.string(json.proxyAutoconfigUrl, - `Expected "proxyAutoconfigUrl" to be a string, ` + - pprint`got ${json.proxyAutoconfigUrl}`); + p.proxyAutoconfigUrl = assert.string( + json.proxyAutoconfigUrl, + `Expected "proxyAutoconfigUrl" to be a string, ` + + pprint`got ${json.proxyAutoconfigUrl}` + ); break; case "manual": @@ -295,23 +330,30 @@ class Proxy { } if (typeof json.socksProxy != "undefined") { [p.socksProxy, p.socksProxyPort] = fromHost("socks", json.socksProxy); - p.socksVersion = assert.positiveInteger(json.socksVersion, - pprint`Expected "socksVersion" to be a positive integer, got ${json.socksVersion}`); + p.socksVersion = assert.positiveInteger( + json.socksVersion, + pprint`Expected "socksVersion" to be a positive integer, got ${ + json.socksVersion + }` + ); } if (typeof json.noProxy != "undefined") { - let entries = assert.array(json.noProxy, - pprint`Expected "noProxy" to be an array, got ${json.noProxy}`); + let entries = assert.array( + json.noProxy, + pprint`Expected "noProxy" to be an array, got ${json.noProxy}` + ); p.noProxy = entries.map(entry => { - assert.string(entry, - pprint`Expected "noProxy" entry to be a string, got ${entry}`); + assert.string( + entry, + pprint`Expected "noProxy" entry to be a string, got ${entry}` + ); return stripBracketsFromIpv6Hostname(entry); }); } break; default: - throw new InvalidArgumentError( - `Invalid type of proxy: ${p.proxyType}`); + throw new InvalidArgumentError(`Invalid type of proxy: ${p.proxyType}`); } return p; @@ -358,7 +400,9 @@ class Proxy { }); } - toString() { return "[object Proxy]"; } + toString() { + return "[object Proxy]"; + } } /** @@ -409,10 +453,16 @@ class Capabilities extends Map { // proprietary ["moz:accessibilityChecks", false], ["moz:buildID", Services.appinfo.appBuildID], - ["moz:headless", Cc["@mozilla.org/gfx/info;1"].getService(Ci.nsIGfxInfo).isHeadless], + [ + "moz:headless", + Cc["@mozilla.org/gfx/info;1"].getService(Ci.nsIGfxInfo).isHeadless, + ], ["moz:processID", Services.appinfo.processID], ["moz:profile", maybeProfile()], - ["moz:shutdownTimeout", Services.prefs.getIntPref("toolkit.asyncshutdown.crash_timeout")], + [ + "moz:shutdownTimeout", + Services.prefs.getIntPref("toolkit.asyncshutdown.crash_timeout"), + ], ["moz:useNonSpecCompliantPointerOrigin", false], ["moz:webdriverClick", true], ]); @@ -434,7 +484,9 @@ class Capabilities extends Map { return super.set(key, value); } - toString() { return "[object Capabilities]"; } + toString() { + return "[object Capabilities]"; + } /** * JSON serialisation of capabilities object. @@ -460,8 +512,10 @@ class Capabilities extends Map { if (typeof json == "undefined" || json === null) { json = {}; } - assert.object(json, - pprint`Expected "capabilities" to be an object, got ${json}"`); + assert.object( + json, + pprint`Expected "capabilities" to be an object, got ${json}"` + ); return Capabilities.match_(json); } @@ -492,7 +546,9 @@ class Capabilities extends Map { if (appinfo.name == "firefox" && !v) { throw new InvalidArgumentError("setWindowRect cannot be disabled"); } else if (appinfo.name != "firefox" && v) { - throw new InvalidArgumentError("setWindowRect is only supported in Firefox desktop"); + throw new InvalidArgumentError( + "setWindowRect is only supported in Firefox desktop" + ); } break; @@ -508,7 +564,8 @@ class Capabilities extends Map { assert.string(v, pprint`Expected ${k} to be a string, got ${v}`); if (!Object.values(UnhandledPromptBehavior).includes(v)) { throw new InvalidArgumentError( - `Unknown unhandled prompt behavior: ${v}`); + `Unknown unhandled prompt behavior: ${v}` + ); } break; @@ -583,7 +640,7 @@ function marshal(obj) { if (typeof v.toJSON == "function") { v = marshal(v.toJSON()); - // Or do the same for object literals. + // Or do the same for object literals. } else if (isObject(v)) { v = marshal(v); } diff --git a/testing/marionette/capture.js b/testing/marionette/capture.js index 8916d4d24fad..526ef39586e3 100644 --- a/testing/marionette/capture.js +++ b/testing/marionette/capture.js @@ -4,10 +4,14 @@ "use strict"; -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); -const {InvalidArgumentError} = ChromeUtils.import("chrome://marionette/content/error.js"); -const {Log} = ChromeUtils.import("chrome://marionette/content/log.js"); +const { InvalidArgumentError } = ChromeUtils.import( + "chrome://marionette/content/error.js" +); +const { Log } = ChromeUtils.import("chrome://marionette/content/log.js"); XPCOMUtils.defineLazyGetter(this, "logger", Log.get); XPCOMUtils.defineLazyGlobalGetters(this, ["crypto"]); @@ -48,13 +52,9 @@ capture.element = function(node, highlights = []) { let win = node.ownerGlobal; let rect = node.getBoundingClientRect(); - return capture.canvas( - win, - rect.left, - rect.top, - rect.width, - rect.height, - {highlights}); + return capture.canvas(win, rect.left, rect.top, rect.width, rect.height, { + highlights, + }); }; /** @@ -73,12 +73,13 @@ capture.element = function(node, highlights = []) { */ capture.viewport = function(win, highlights = []) { return capture.canvas( - win, - win.pageXOffset, - win.pageYOffset, - win.innerWidth, - win.innerHeight, - {highlights}); + win, + win.pageXOffset, + win.pageYOffset, + win.innerWidth, + win.innerHeight, + { highlights } + ); }; /** @@ -108,8 +109,14 @@ capture.viewport = function(win, highlights = []) { * The canvas on which the selection from the window's framebuffer * has been painted on. */ -capture.canvas = function(win, left, top, width, height, - {highlights = [], canvas = null, flags = null} = {}) { +capture.canvas = function( + win, + left, + top, + width, + height, + { highlights = [], canvas = null, flags = null } = {} +) { const scale = win.devicePixelRatio; if (canvas === null) { @@ -117,14 +124,20 @@ capture.canvas = function(win, left, top, width, height, let canvasHeight = height * scale; if (canvasWidth > MAX_SKIA_DIMENSIONS) { - logger.warn("Reducing screenshot width because it exceeds " + - MAX_SKIA_DIMENSIONS + " pixels"); + logger.warn( + "Reducing screenshot width because it exceeds " + + MAX_SKIA_DIMENSIONS + + " pixels" + ); canvasWidth = MAX_SKIA_DIMENSIONS; } if (canvasHeight > MAX_SKIA_DIMENSIONS) { - logger.warn("Reducing screenshot height because it exceeds " + - MAX_SKIA_DIMENSIONS + " pixels"); + logger.warn( + "Reducing screenshot height because it exceeds " + + MAX_SKIA_DIMENSIONS + + " pixels" + ); canvasHeight = MAX_SKIA_DIMENSIONS; } @@ -173,11 +186,7 @@ capture.highlight_ = function(context, highlights, top = 0, left = 0) { let oy = -top; let ox = -left; - context.strokeRect( - rect.left + ox, - rect.top + oy, - rect.width, - rect.height); + context.strokeRect(rect.left + ox, rect.top + oy, rect.width, rect.height); } return context; @@ -198,14 +207,14 @@ capture.toBase64 = function(canvas) { }; /** -* Hash the contents of an HTMLCanvasElement to a SHA-256 hex digest. -* -* @param {HTMLCanvasElement} canvas -* The canvas to encode. -* -* @return {string} -* A hex digest of the SHA-256 hash of the base64 encoded string. -*/ + * Hash the contents of an HTMLCanvasElement to a SHA-256 hex digest. + * + * @param {HTMLCanvasElement} canvas + * The canvas to encode. + * + * @return {string} + * A hex digest of the SHA-256 hash of the base64 encoded string. + */ capture.toHash = function(canvas) { let u = capture.toBase64(canvas); let buffer = new TextEncoder("utf-8").encode(u); @@ -213,14 +222,14 @@ capture.toHash = function(canvas) { }; /** -* Convert buffer into to hex. -* -* @param {ArrayBuffer} buffer -* The buffer containing the data to convert to hex. -* -* @return {string} -* A hex digest of the input buffer. -*/ + * Convert buffer into to hex. + * + * @param {ArrayBuffer} buffer + * The buffer containing the data to convert to hex. + * + * @return {string} + * A hex digest of the input buffer. + */ function hex(buffer) { let hexCodes = []; let view = new DataView(buffer); diff --git a/testing/marionette/cert.js b/testing/marionette/cert.js index c3b53e58a57d..f3cb49771d1c 100644 --- a/testing/marionette/cert.js +++ b/testing/marionette/cert.js @@ -4,18 +4,22 @@ "use strict"; -const {Preferences} = ChromeUtils.import("resource://gre/modules/Preferences.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { Preferences } = ChromeUtils.import( + "resource://gre/modules/Preferences.jsm" +); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); this.EXPORTED_SYMBOLS = [ "CertificateOverrideManager", "InsecureSweepingOverride", ]; -const registrar = - Components.manager.QueryInterface(Ci.nsIComponentRegistrar); -const sss = Cc["@mozilla.org/ssservice;1"] - .getService(Ci.nsISiteSecurityService); +const registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); +const sss = Cc["@mozilla.org/ssservice;1"].getService( + Ci.nsISiteSecurityService +); const CERT_PINNING_ENFORCEMENT_PREF = "security.cert_pinning.enforcement_level"; const CID = Components.ID("{4b67cce0-a51c-11e6-9598-0800200c9a66}"); @@ -91,8 +95,7 @@ function InsecureSweepingOverride() { // make your life miserable. let service = function() {}; service.prototype = { - hasMatchingOverride( - aHostName, aPort, aCert, aOverrideBits, aIsTemporary) { + hasMatchingOverride(aHostName, aPort, aCert, aOverrideBits, aIsTemporary) { aIsTemporary.value = false; aOverrideBits.value = Error.Untrusted | Error.Mismatch | Error.Time; diff --git a/testing/marionette/components/marionette.js b/testing/marionette/components/marionette.js index c1b6af9d87d6..125746784572 100644 --- a/testing/marionette/components/marionette.js +++ b/testing/marionette/components/marionette.js @@ -4,13 +4,15 @@ "use strict"; -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); -const { - EnvironmentPrefs, - MarionettePrefs, -} = ChromeUtils.import("chrome://marionette/content/prefs.js", null); +const { EnvironmentPrefs, MarionettePrefs } = ChromeUtils.import( + "chrome://marionette/content/prefs.js", + null +); XPCOMUtils.defineLazyModuleGetters(this, { Log: "chrome://marionette/content/log.js", @@ -21,9 +23,14 @@ XPCOMUtils.defineLazyModuleGetters(this, { XPCOMUtils.defineLazyGetter(this, "log", Log.get); XPCOMUtils.defineLazyServiceGetter( - this, "env", "@mozilla.org/process/environment;1", "nsIEnvironment"); + this, + "env", + "@mozilla.org/process/environment;1", + "nsIEnvironment" +); -const XMLURI_PARSE_ERROR = "http://www.mozilla.org/newlayout/xml/parsererror.xml"; +const XMLURI_PARSE_ERROR = + "http://www.mozilla.org/newlayout/xml/parsererror.xml"; const NOTIFY_RUNNING = "remote-active"; @@ -60,7 +67,6 @@ const ENV_PRESERVE_PREFS = "MOZ_MARIONETTE_PREF_STATE_ACROSS_RESTARTS"; // such backward compatibility has to be ensured at least for the last three // releases. const RECOMMENDED_PREFS = new Map([ - // Make sure Shield doesn't hit the network. ["app.normandy.api_url", ""], @@ -213,10 +219,7 @@ const RECOMMENDED_PREFS = new Map([ ["extensions.update.notifyUser", false], // Make sure opening about:addons will not hit the network - [ - "extensions.webservice.discoverURL", - "http://%(server)s/dummy/discoveryURL", - ], + ["extensions.webservice.discoverURL", "http://%(server)s/dummy/discoveryURL"], // Allow the application to have focus even it runs in the background ["focusmanager.testmode", true], @@ -283,11 +286,10 @@ const RECOMMENDED_PREFS = new Map([ // Prevent starting into safe mode after application crashes ["toolkit.startup.max_resumed_crashes", -1], - ]); -const isRemote = Services.appinfo.processType == - Services.appinfo.PROCESS_TYPE_CONTENT; +const isRemote = + Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT; class MarionetteParentProcess { constructor() { @@ -320,7 +322,7 @@ class MarionetteParentProcess { return MarionettePrefs.enabled; } - receiveMessage({name}) { + receiveMessage({ name }) { switch (name) { case "Marionette:IsRunning": return this.running; @@ -390,16 +392,20 @@ class MarionetteParentProcess { break; case "toplevel-window-ready": - subject.addEventListener("load", ev => { - if (ev.target.documentElement.namespaceURI == XMLURI_PARSE_ERROR) { - Services.obs.removeObserver(this, topic); + subject.addEventListener( + "load", + ev => { + if (ev.target.documentElement.namespaceURI == XMLURI_PARSE_ERROR) { + Services.obs.removeObserver(this, topic); - let parserError = ev.target.querySelector("parsererror"); - log.fatal(parserError.textContent); - this.uninit(); - Services.startup.quit(Ci.nsIAppStartup.eForceQuit); - } - }, {once: true}); + let parserError = ev.target.querySelector("parsererror"); + log.fatal(parserError.textContent); + this.uninit(); + Services.startup.quit(Ci.nsIAppStartup.eForceQuit); + } + }, + { once: true } + ); break; case "marionette-startup-requested": @@ -409,14 +415,19 @@ class MarionetteParentProcess { // window may appear off-screen. Marionette should wait for it // to close. for (let win of Services.wm.getEnumerator(null)) { - if (win.document.documentURI == "chrome://gfxsanity/content/sanityparent.html") { + if ( + win.document.documentURI == + "chrome://gfxsanity/content/sanityparent.html" + ) { this.gfxWindow = win; break; } } if (this.gfxWindow) { - log.trace("GFX sanity window detected, waiting until it has been closed..."); + log.trace( + "GFX sanity window detected, waiting until it has been closed..." + ); Services.obs.addObserver(this, "domwindowclosed"); } else { Services.obs.removeObserver(this, "toplevel-window-ready"); @@ -437,30 +448,38 @@ class MarionetteParentProcess { } suppressSafeModeDialog(win) { - win.addEventListener("load", () => { - if (win.document.getElementById("safeModeDialog")) { - // accept the dialog to start in safe-mode - log.trace("Safe mode detected, supressing dialog"); - win.setTimeout(() => { - win.document.documentElement.getButton("accept").click(); - }); - } - }, {once: true}); + win.addEventListener( + "load", + () => { + if (win.document.getElementById("safeModeDialog")) { + // accept the dialog to start in safe-mode + log.trace("Safe mode detected, supressing dialog"); + win.setTimeout(() => { + win.document.documentElement.getButton("accept").click(); + }); + } + }, + { once: true } + ); } init(quit = true) { if (this.running || !this.enabled || !this.finalUIStartup) { - log.debug(`Init aborted (running=${this.running}, ` + - `enabled=${this.enabled}, finalUIStartup=${this.finalUIStartup})`); + log.debug( + `Init aborted (running=${this.running}, ` + + `enabled=${this.enabled}, finalUIStartup=${this.finalUIStartup})` + ); return; } - log.trace(`Waiting until startup recorder finished recording startup scripts...`); + log.trace( + `Waiting until startup recorder finished recording startup scripts...` + ); Services.tm.idleDispatchToMainThread(async () => { let startupRecorder = Promise.resolve(); if ("@mozilla.org/test/startuprecorder;1" in Cc) { - startupRecorder = Cc["@mozilla.org/test/startuprecorder;1"] - .getService().wrappedJSObject.done; + startupRecorder = Cc["@mozilla.org/test/startuprecorder;1"].getService() + .wrappedJSObject.done; } await startupRecorder; log.trace(`All scripts recorded.`); diff --git a/testing/marionette/cookie.js b/testing/marionette/cookie.js index 639b886820d5..f07234c9d8cc 100644 --- a/testing/marionette/cookie.js +++ b/testing/marionette/cookie.js @@ -4,14 +4,13 @@ "use strict"; -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {assert} = ChromeUtils.import("chrome://marionette/content/assert.js"); -const { - InvalidCookieDomainError, - UnableToSetCookieError, -} = ChromeUtils.import("chrome://marionette/content/error.js"); -const {pprint} = ChromeUtils.import("chrome://marionette/content/format.js"); +const { assert } = ChromeUtils.import("chrome://marionette/content/assert.js"); +const { InvalidCookieDomainError, UnableToSetCookieError } = ChromeUtils.import( + "chrome://marionette/content/error.js" +); +const { pprint } = ChromeUtils.import("chrome://marionette/content/format.js"); this.EXPORTED_SYMBOLS = ["cookie"]; @@ -61,16 +60,28 @@ cookie.fromJSON = function(json) { newCookie.path = assert.string(json.path, "Cookie path must be string"); } if (typeof json.domain != "undefined") { - newCookie.domain = assert.string(json.domain, "Cookie domain must be string"); + newCookie.domain = assert.string( + json.domain, + "Cookie domain must be string" + ); } if (typeof json.secure != "undefined") { - newCookie.secure = assert.boolean(json.secure, "Cookie secure flag must be boolean"); + newCookie.secure = assert.boolean( + json.secure, + "Cookie secure flag must be boolean" + ); } if (typeof json.httpOnly != "undefined") { - newCookie.httpOnly = assert.boolean(json.httpOnly, "Cookie httpOnly flag must be boolean"); + newCookie.httpOnly = assert.boolean( + json.httpOnly, + "Cookie httpOnly flag must be boolean" + ); } if (typeof json.expiry != "undefined") { - newCookie.expiry = assert.positiveInteger(json.expiry, "Cookie expiry must be a positive integer"); + newCookie.expiry = assert.positiveInteger( + json.expiry, + "Cookie expiry must be a positive integer" + ); } return newCookie; @@ -93,7 +104,7 @@ cookie.fromJSON = function(json) { * @throws {UnableToSetCookieError} * If an error occurred while trying to save the cookie. */ -cookie.add = function(newCookie, {restrictToHost = null} = {}) { +cookie.add = function(newCookie, { restrictToHost = null } = {}) { assert.string(newCookie.name, "Cookie name must be string"); assert.string(newCookie.value, "Cookie value must be string"); @@ -145,11 +156,15 @@ cookie.add = function(newCookie, {restrictToHost = null} = {}) { } if (restrictToHost) { - if (!restrictToHost.endsWith(newCookie.domain) && - ("." + restrictToHost) !== newCookie.domain && - restrictToHost !== newCookie.domain) { - throw new InvalidCookieDomainError(`Cookies may only be set ` + - `for the current domain (${restrictToHost})`); + if ( + !restrictToHost.endsWith(newCookie.domain) && + "." + restrictToHost !== newCookie.domain && + restrictToHost !== newCookie.domain + ) { + throw new InvalidCookieDomainError( + `Cookies may only be set ` + + `for the current domain (${restrictToHost})` + ); } } @@ -160,16 +175,17 @@ cookie.add = function(newCookie, {restrictToHost = null} = {}) { try { cookie.manager.add( - newCookie.domain, - newCookie.path, - newCookie.name, - newCookie.value, - newCookie.secure, - newCookie.httpOnly, - newCookie.session, - newCookie.expiry, - {} /* origin attributes */, - Ci.nsICookie.SAMESITE_NONE); + newCookie.domain, + newCookie.path, + newCookie.name, + newCookie.value, + newCookie.secure, + newCookie.httpOnly, + newCookie.session, + newCookie.expiry, + {} /* origin attributes */, + Ci.nsICookie.SAMESITE_NONE + ); } catch (e) { throw new UnableToSetCookieError(e); } @@ -183,11 +199,12 @@ cookie.add = function(newCookie, {restrictToHost = null} = {}) { */ cookie.remove = function(toDelete) { cookie.manager.remove( - toDelete.domain, - toDelete.name, - toDelete.path, - false, - {} /* originAttributes */); + toDelete.domain, + toDelete.name, + toDelete.path, + false, + {} /* originAttributes */ + ); }; /** @@ -204,7 +221,7 @@ cookie.remove = function(toDelete) { * @return {Iterable.} * Iterator. */ -cookie.iter = function* (host, currentPath = "/") { +cookie.iter = function*(host, currentPath = "/") { assert.string(host, "host must be string"); assert.string(currentPath, "currentPath must be string"); @@ -215,15 +232,17 @@ cookie.iter = function* (host, currentPath = "/") { // take the hostname and progressively shorten let hostname = host; do { - if ((cookie.host == "." + hostname || cookie.host == hostname) && - isForCurrentPath(cookie.path)) { + if ( + (cookie.host == "." + hostname || cookie.host == hostname) && + isForCurrentPath(cookie.path) + ) { let data = { - "name": cookie.name, - "value": cookie.value, - "path": cookie.path, - "domain": cookie.host, - "secure": cookie.isSecure, - "httpOnly": cookie.isHttpOnly, + name: cookie.name, + value: cookie.value, + path: cookie.path, + domain: cookie.host, + secure: cookie.isSecure, + httpOnly: cookie.isHttpOnly, }; if (!cookie.isSession) { diff --git a/testing/marionette/dom.js b/testing/marionette/dom.js index 1959fb30ea74..2b89512ce5e2 100644 --- a/testing/marionette/dom.js +++ b/testing/marionette/dom.js @@ -4,9 +4,11 @@ "use strict"; -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); -const {Log} = ChromeUtils.import("chrome://marionette/content/log.js"); +const { Log } = ChromeUtils.import("chrome://marionette/content/log.js"); XPCOMUtils.defineLazyGetter(this, "logger", Log.get); @@ -60,7 +62,7 @@ class WebElementEventTarget { * most once after being added. If true, the ``listener`` * would automatically be removed when invoked. */ - addEventListener(type, listener, {once = false} = {}) { + addEventListener(type, listener, { once = false } = {}) { if (!(type in this.listeners)) { this.listeners[type] = []; } @@ -70,7 +72,7 @@ class WebElementEventTarget { this.listeners[type].push(listener); } - this.mm.sendAsyncMessage("Marionette:DOM:AddEventListener", {type}); + this.mm.sendAsyncMessage("Marionette:DOM:AddEventListener", { type }); } /** @@ -91,7 +93,9 @@ class WebElementEventTarget { if (stack[i] === listener) { stack.splice(i, 1); if (stack.length == 0) { - this.mm.sendAsyncMessage("Marionette:DOM:RemoveEventListener", {type}); + this.mm.sendAsyncMessage("Marionette:DOM:RemoveEventListener", { + type, + }); } return; } @@ -119,7 +123,7 @@ class WebElementEventTarget { }); } - receiveMessage({name, data, objects}) { + receiveMessage({ name, data, objects }) { if (name != "Marionette:DOM:OnEvent") { return; } @@ -196,15 +200,15 @@ class ContentEventObserverService { } } - * [Symbol.iterator]() { + *[Symbol.iterator]() { for (let ev of this.events) { yield ev; } } - handleEvent({type, target}) { + handleEvent({ type, target }) { logger.trace(`Received DOM event ${type}`); - this.sendAsyncMessage("Marionette:DOM:OnEvent", {type}, {target}); + this.sendAsyncMessage("Marionette:DOM:OnEvent", { type }, { target }); } } this.ContentEventObserverService = ContentEventObserverService; diff --git a/testing/marionette/driver.js b/testing/marionette/driver.js index a2b579906e39..c3e1918b69d5 100644 --- a/testing/marionette/driver.js +++ b/testing/marionette/driver.js @@ -5,37 +5,37 @@ "use strict"; /* global XPCNativeWrapper */ -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); -const {accessibility} = ChromeUtils.import("chrome://marionette/content/accessibility.js"); -const {Addon} = ChromeUtils.import("chrome://marionette/content/addon.js"); -const {assert} = ChromeUtils.import("chrome://marionette/content/assert.js"); -const {atom} = ChromeUtils.import("chrome://marionette/content/atom.js"); -const { - browser, - Context, - WindowState, -} = ChromeUtils.import("chrome://marionette/content/browser.js"); -const { - Capabilities, - Timeouts, - UnhandledPromptBehavior, -} = ChromeUtils.import("chrome://marionette/content/capabilities.js"); -const {capture} = ChromeUtils.import("chrome://marionette/content/capture.js"); +const { accessibility } = ChromeUtils.import( + "chrome://marionette/content/accessibility.js" +); +const { Addon } = ChromeUtils.import("chrome://marionette/content/addon.js"); +const { assert } = ChromeUtils.import("chrome://marionette/content/assert.js"); +const { atom } = ChromeUtils.import("chrome://marionette/content/atom.js"); +const { browser, Context, WindowState } = ChromeUtils.import( + "chrome://marionette/content/browser.js" +); +const { Capabilities, Timeouts, UnhandledPromptBehavior } = ChromeUtils.import( + "chrome://marionette/content/capabilities.js" +); +const { capture } = ChromeUtils.import( + "chrome://marionette/content/capture.js" +); const { CertificateOverrideManager, InsecureSweepingOverride, } = ChromeUtils.import("chrome://marionette/content/cert.js"); -const {cookie} = ChromeUtils.import("chrome://marionette/content/cookie.js"); -const { - WebElementEventTarget, -} = ChromeUtils.import("chrome://marionette/content/dom.js"); -const { - ChromeWebElement, - element, - WebElement, -} = ChromeUtils.import("chrome://marionette/content/element.js"); +const { cookie } = ChromeUtils.import("chrome://marionette/content/cookie.js"); +const { WebElementEventTarget } = ChromeUtils.import( + "chrome://marionette/content/dom.js" +); +const { ChromeWebElement, element, WebElement } = ChromeUtils.import( + "chrome://marionette/content/element.js" +); const { ElementNotInteractableError, InsecureCertificateError, @@ -51,16 +51,27 @@ const { UnsupportedOperationError, WebDriverError, } = ChromeUtils.import("chrome://marionette/content/error.js"); -const {Sandboxes, evaluate} = ChromeUtils.import("chrome://marionette/content/evaluate.js"); -const {pprint} = ChromeUtils.import("chrome://marionette/content/format.js"); -const {interaction} = ChromeUtils.import("chrome://marionette/content/interaction.js"); -const {l10n} = ChromeUtils.import("chrome://marionette/content/l10n.js"); -const {legacyaction} = ChromeUtils.import("chrome://marionette/content/legacyaction.js"); -const {Log} = ChromeUtils.import("chrome://marionette/content/log.js"); -const {modal} = ChromeUtils.import("chrome://marionette/content/modal.js"); -const {MarionettePrefs} = ChromeUtils.import("chrome://marionette/content/prefs.js", null); -const {proxy} = ChromeUtils.import("chrome://marionette/content/proxy.js"); -const {reftest} = ChromeUtils.import("chrome://marionette/content/reftest.js"); +const { Sandboxes, evaluate } = ChromeUtils.import( + "chrome://marionette/content/evaluate.js" +); +const { pprint } = ChromeUtils.import("chrome://marionette/content/format.js"); +const { interaction } = ChromeUtils.import( + "chrome://marionette/content/interaction.js" +); +const { l10n } = ChromeUtils.import("chrome://marionette/content/l10n.js"); +const { legacyaction } = ChromeUtils.import( + "chrome://marionette/content/legacyaction.js" +); +const { Log } = ChromeUtils.import("chrome://marionette/content/log.js"); +const { modal } = ChromeUtils.import("chrome://marionette/content/modal.js"); +const { MarionettePrefs } = ChromeUtils.import( + "chrome://marionette/content/prefs.js", + null +); +const { proxy } = ChromeUtils.import("chrome://marionette/content/proxy.js"); +const { reftest } = ChromeUtils.import( + "chrome://marionette/content/reftest.js" +); const { DebounceCallback, IdlePromise, @@ -147,7 +158,9 @@ this.GeckoDriver = function(server) { this.mm = globalMessageManager; this.listener = proxy.toListener( - this.sendAsync.bind(this), () => this.curBrowser); + this.sendAsync.bind(this), + () => this.curBrowser + ); // used for modal dialogs or tab modal alerts this.dialog = null; @@ -243,7 +256,9 @@ Object.defineProperty(GeckoDriver.prototype, "windows", { Object.defineProperty(GeckoDriver.prototype, "windowType", { get() { - return this.curBrowser.window.document.documentElement.getAttribute("windowtype"); + return this.curBrowser.window.document.documentElement.getAttribute( + "windowtype" + ); }, }); @@ -355,7 +370,8 @@ GeckoDriver.prototype.sendAsync = function(name, data, commandID) { this.curBrowser.messageManager.sendAsyncMessage(target, payload); } else { throw new NoSuchWindowError( - "No such content frame; perhaps the listener was not registered?"); + "No such content frame; perhaps the listener was not registered?" + ); } }); }; @@ -377,7 +393,8 @@ GeckoDriver.prototype.sendAsync = function(name, data, commandID) { * The current top-level browsing context. */ GeckoDriver.prototype.getCurrentWindow = function(forcedContext = undefined) { - let context = typeof forcedContext == "undefined" ? this.context : forcedContext; + let context = + typeof forcedContext == "undefined" ? this.context : forcedContext; let win = null; switch (context) { @@ -402,11 +419,13 @@ GeckoDriver.prototype.getCurrentWindow = function(forcedContext = undefined) { }; GeckoDriver.prototype.isReftestBrowser = function(element) { - return this._reftest && + return ( + this._reftest && element && element.tagName === "xul:browser" && element.parentElement && - element.parentElement.id === "reftest"; + element.parentElement.id === "reftest" + ); }; GeckoDriver.prototype.addFrameCloseListener = function(action) { @@ -541,8 +560,12 @@ GeckoDriver.prototype.registerBrowser = function(id, be) { // xul:tabbrowser), and accept HTML iframes (because tests depend on it), // as well as XUL frames. Ideally this should be cleaned up and we should // keep track of browsers a different way. - if (this.appId != APP_ID_FIREFOX || be.namespaceURI != XUL_NS || - be.nodeName != "browser" || be.getTabBrowser()) { + if ( + this.appId != APP_ID_FIREFOX || + be.namespaceURI != XUL_NS || + be.nodeName != "browser" || + be.getTabBrowser() + ) { // curBrowser holds all the registered frames in knownFrames this.curBrowser.register(id, be); } @@ -555,8 +578,8 @@ GeckoDriver.prototype.registerPromise = function() { const li = "Marionette:Register"; return new Promise(resolve => { - let cb = ({json, target}) => { - let {outerWindowID} = json; + let cb = ({ json, target }) => { + let { outerWindowID } = json; this.registerBrowser(outerWindowID, target); if (this.curBrowser.frameRegsPending > 0) { @@ -568,7 +591,7 @@ GeckoDriver.prototype.registerPromise = function() { resolve(); } - return {outerWindowID}; + return { outerWindowID }; }; this.mm.addMessageListener(li, cb); }); @@ -753,8 +776,11 @@ GeckoDriver.prototype.newSession = async function(cmd) { if (!win) { // if the window isn't even created, just poll wait for it let checkTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); - checkTimer.initWithCallback(waitForWindow.bind(this), 100, - Ci.nsITimer.TYPE_ONE_SHOT); + checkTimer.initWithCallback( + waitForWindow.bind(this), + 100, + Ci.nsITimer.TYPE_ONE_SHOT + ); } else if (win.document.readyState != "complete") { // otherwise, wait for it to be fully loaded before proceeding let listener = ev => { @@ -769,7 +795,11 @@ GeckoDriver.prototype.newSession = async function(cmd) { win.addEventListener("load", listener, true); } else { if (MarionettePrefs.clickToStart) { - Services.prompt.alert(win, "", "Click to start execution of marionette tests"); + Services.prompt.alert( + win, + "", + "Click to start execution of marionette tests" + ); } this.startBrowser(win, true); } @@ -822,7 +852,7 @@ GeckoDriver.prototype.newSession = async function(cmd) { * numerical or string. */ GeckoDriver.prototype.getSessionCapabilities = function() { - return {capabilities: this.capabilities}; + return { capabilities: this.capabilities }; }; /** @@ -904,7 +934,7 @@ GeckoDriver.prototype.getContext = function() { * If an {@link Error} was thrown whilst evaluating the script. */ GeckoDriver.prototype.executeScript = async function(cmd) { - let {script, args} = cmd.parameters; + let { script, args } = cmd.parameters; let opts = { script: cmd.parameters.script, args: cmd.parameters.args, @@ -914,7 +944,7 @@ GeckoDriver.prototype.executeScript = async function(cmd) { line: cmd.parameters.line, }; - return {value: await this.execute_(script, args, opts)}; + return { value: await this.execute_(script, args, opts) }; }; /** @@ -969,7 +999,7 @@ GeckoDriver.prototype.executeScript = async function(cmd) { * If an Error was thrown whilst evaluating the script. */ GeckoDriver.prototype.executeAsyncScript = async function(cmd) { - let {script, args} = cmd.parameters; + let { script, args } = cmd.parameters; let opts = { script: cmd.parameters.script, args: cmd.parameters.args, @@ -980,28 +1010,35 @@ GeckoDriver.prototype.executeAsyncScript = async function(cmd) { async: true, }; - return {value: await this.execute_(script, args, opts)}; + return { value: await this.execute_(script, args, opts) }; }; GeckoDriver.prototype.execute_ = async function( - script, - args = [], - { - sandboxName = null, - newSandbox = false, - file = "", - line = 0, - async = false, - } = {}) { + script, + args = [], + { + sandboxName = null, + newSandbox = false, + file = "", + line = 0, + async = false, + } = {} +) { assert.open(this.getCurrentWindow()); await this._handleUserPrompts(); assert.string(script, pprint`Expected "script" to be a string: ${script}`); assert.array(args, pprint`Expected script args to be an array: ${args}`); if (sandboxName !== null) { - assert.string(sandboxName, pprint`Expected sandbox name to be a string: ${sandboxName}`); + assert.string( + sandboxName, + pprint`Expected sandbox name to be a string: ${sandboxName}` + ); } - assert.boolean(newSandbox, pprint`Expected newSandbox to be boolean: ${newSandbox}`); + assert.boolean( + newSandbox, + pprint`Expected newSandbox to be boolean: ${newSandbox}` + ); assert.string(file, pprint`Expected file to be a string: ${file}`); assert.number(line, pprint`Expected line to be a number: ${line}`); @@ -1022,7 +1059,7 @@ GeckoDriver.prototype.execute_ = async function( if (!sandboxName) { res = await this.listener.execute(script, args, opts); - // evaluate in content with sandbox + // evaluate in content with sandbox } else { res = await this.listener.executeInSandbox(script, args, opts); } @@ -1080,7 +1117,7 @@ GeckoDriver.prototype.get = async function(cmd) { let url = cmd.parameters.url; - let get = this.listener.get({url, pageTimeout: this.timeouts.pageLoad}); + let get = this.listener.get({ url, pageTimeout: this.timeouts.pageLoad }); // If a process change of the frame script interrupts our page load, this // will never return. We need to re-issue this request to correctly poll for @@ -1093,7 +1130,9 @@ GeckoDriver.prototype.get = async function(cmd) { startTime: new Date().getTime(), }; this.curBrowser.messageManager.sendAsyncMessage( - "Marionette:waitForPageLoaded", parameters); + "Marionette:waitForPageLoaded", + parameters + ); }); await get; @@ -1199,7 +1238,7 @@ GeckoDriver.prototype.goBack = async function() { } let lastURL = this.currentURL; - let goBack = this.listener.goBack({pageTimeout: this.timeouts.pageLoad}); + let goBack = this.listener.goBack({ pageTimeout: this.timeouts.pageLoad }); // If a process change of the frame script interrupts our page load, this // will never return. We need to re-issue this request to correctly poll for @@ -1213,7 +1252,9 @@ GeckoDriver.prototype.goBack = async function() { startTime: new Date().getTime(), }; this.curBrowser.messageManager.sendAsyncMessage( - "Marionette:waitForPageLoaded", parameters); + "Marionette:waitForPageLoaded", + parameters + ); }); await goBack; @@ -1241,8 +1282,9 @@ GeckoDriver.prototype.goForward = async function() { } let lastURL = this.currentURL; - let goForward = this.listener.goForward( - {pageTimeout: this.timeouts.pageLoad}); + let goForward = this.listener.goForward({ + pageTimeout: this.timeouts.pageLoad, + }); // If a process change of the frame script interrupts our page load, this // will never return. We need to re-issue this request to correctly poll for @@ -1256,7 +1298,9 @@ GeckoDriver.prototype.goForward = async function() { startTime: new Date().getTime(), }; this.curBrowser.messageManager.sendAsyncMessage( - "Marionette:waitForPageLoaded", parameters); + "Marionette:waitForPageLoaded", + parameters + ); }); await goForward; @@ -1278,8 +1322,7 @@ GeckoDriver.prototype.refresh = async function() { assert.open(this.getCurrentWindow()); await this._handleUserPrompts(); - let refresh = this.listener.refresh( - {pageTimeout: this.timeouts.pageLoad}); + let refresh = this.listener.refresh({ pageTimeout: this.timeouts.pageLoad }); // If a process change of the frame script interrupts our page load, this // will never return. We need to re-issue this request to correctly poll for @@ -1292,7 +1335,9 @@ GeckoDriver.prototype.refresh = async function() { startTime: new Date().getTime(), }; this.curBrowser.messageManager.sendAsyncMessage( - "Marionette:waitForPageLoaded", parameters); + "Marionette:waitForPageLoaded", + parameters + ); }); await refresh; @@ -1460,7 +1505,7 @@ GeckoDriver.prototype.setWindowRect = async function(cmd) { const win = assert.open(this.getCurrentWindow()); await this._handleUserPrompts(); - let {x, y, width, height} = cmd.parameters; + let { x, y, width, height } = cmd.parameters; switch (WindowState.from(win.windowState)) { case WindowState.Fullscreen: @@ -1554,10 +1599,10 @@ GeckoDriver.prototype.findWindow = function(winIterable, filter) { // In case the wanted window is a chrome window, we are done. if (filter(win, outerId)) { - return {win, outerId, hasTabBrowser: !!tabBrowser}; + return { win, outerId, hasTabBrowser: !!tabBrowser }; - // Otherwise check if the chrome window has a tab browser, and that it - // contains a tab with the wanted window handle. + // Otherwise check if the chrome window has a tab browser, and that it + // contains a tab with the wanted window handle. } else if (tabBrowser && tabBrowser.tabs) { for (let i = 0; i < tabBrowser.tabs.length; ++i) { let contentBrowser = browser.getBrowserForTab(tabBrowser.tabs[i]); @@ -1592,7 +1637,9 @@ GeckoDriver.prototype.findWindow = function(winIterable, filter) { * Defaults to true. */ GeckoDriver.prototype.setWindowHandle = async function( - winProperties, focus = true) { + winProperties, + focus = true +) { if (!(winProperties.outerId in this.browsers)) { // Initialise Marionette if the current chrome window has not been seen // before. Also register the initial tab, if one exists. @@ -1618,7 +1665,10 @@ GeckoDriver.prototype.setWindowHandle = async function( // .. and activate the tab if it's a content browser. if ("tabIndex" in winProperties) { await this.curBrowser.switchToTab( - winProperties.tabIndex, winProperties.win, focus); + winProperties.tabIndex, + winProperties.win, + focus + ); } } @@ -1681,7 +1731,7 @@ GeckoDriver.prototype.switchToFrame = async function(cmd) { assert.open(this.getCurrentWindow()); await this._handleUserPrompts(); - let {id, focus} = cmd.parameters; + let { id, focus } = cmd.parameters; // TODO(ato): element can be either string (deprecated) or a web // element JSON Object. Can be removed with Firefox 60. @@ -1711,7 +1761,10 @@ GeckoDriver.prototype.switchToFrame = async function(cmd) { } checkTimer.initWithCallback( - checkLoad.bind(this), 100, Ci.nsITimer.TYPE_ONE_SHOT); + checkLoad.bind(this), + 100, + Ci.nsITimer.TYPE_ONE_SHOT + ); }; if (this.context == Context.Chrome) { @@ -1724,7 +1777,10 @@ GeckoDriver.prototype.switchToFrame = async function(cmd) { this.mainFrame.focus(); } checkTimer.initWithCallback( - checkLoad.bind(this), 100, Ci.nsITimer.TYPE_ONE_SHOT); + checkLoad.bind(this), + 100, + Ci.nsITimer.TYPE_ONE_SHOT + ); return; } @@ -1733,15 +1789,20 @@ GeckoDriver.prototype.switchToFrame = async function(cmd) { let wantedFrame = this.curBrowser.seenEls.get(byFrame); // Deal with an embedded xul:browser case - if (wantedFrame.tagName == "xul:browser" || - wantedFrame.tagName == "browser") { + if ( + wantedFrame.tagName == "xul:browser" || + wantedFrame.tagName == "browser" + ) { curWindow = wantedFrame.contentWindow; this.curFrame = curWindow; if (focus) { this.curFrame.focus(); } checkTimer.initWithCallback( - checkLoad.bind(this), 100, Ci.nsITimer.TYPE_ONE_SHOT); + checkLoad.bind(this), + 100, + Ci.nsITimer.TYPE_ONE_SHOT + ); return; } @@ -1749,10 +1810,12 @@ GeckoDriver.prototype.switchToFrame = async function(cmd) { let parent = curWindow.document.getBindingParent(wantedFrame); // Shadow nodes also show up in getAnonymousNodes, we should // ignore them. - if (parent && - !(parent.shadowRoot && parent.shadowRoot.contains(wantedFrame))) { + if ( + parent && + !(parent.shadowRoot && parent.shadowRoot.contains(wantedFrame)) + ) { const doc = curWindow.document; - let anonNodes = [...doc.getAnonymousNodes(parent) || []]; + let anonNodes = [...(doc.getAnonymousNodes(parent) || [])]; if (anonNodes.length > 0) { let el = wantedFrame; while (el) { @@ -1763,7 +1826,10 @@ GeckoDriver.prototype.switchToFrame = async function(cmd) { this.curFrame.focus(); } checkTimer.initWithCallback( - checkLoad.bind(this), 100, Ci.nsITimer.TYPE_ONE_SHOT); + checkLoad.bind(this), + 100, + Ci.nsITimer.TYPE_ONE_SHOT + ); return; } el = el.parentNode; @@ -1784,7 +1850,10 @@ GeckoDriver.prototype.switchToFrame = async function(cmd) { this.curFrame.focus(); } checkTimer.initWithCallback( - checkLoad.bind(this), 100, Ci.nsITimer.TYPE_ONE_SHOT); + checkLoad.bind(this), + 100, + Ci.nsITimer.TYPE_ONE_SHOT + ); return; } } @@ -1827,7 +1896,10 @@ GeckoDriver.prototype.switchToFrame = async function(cmd) { this.curFrame.focus(); } checkTimer.initWithCallback( - checkLoad.bind(this), 100, Ci.nsITimer.TYPE_ONE_SHOT); + checkLoad.bind(this), + 100, + Ci.nsITimer.TYPE_ONE_SHOT + ); } else { throw new NoSuchFrameError(`Unable to locate frame: ${id}`); } @@ -1862,13 +1934,14 @@ GeckoDriver.prototype.setTimeouts = function(cmd) { GeckoDriver.prototype.singleTap = async function(cmd) { assert.open(this.getCurrentWindow()); - let {id, x, y} = cmd.parameters; + let { id, x, y } = cmd.parameters; let webEl = WebElement.fromUUID(id, this.context); switch (this.context) { case Context.Chrome: throw new UnsupportedOperationError( - "Command 'singleTap' is not yet available in chrome context"); + "Command 'singleTap' is not yet available in chrome context" + ); case Context.Content: await this.listener.singleTap(webEl, x, y); @@ -1890,13 +1963,15 @@ GeckoDriver.prototype.singleTap = async function(cmd) { * A modal dialog is open, blocking this operation. */ GeckoDriver.prototype.performActions = async function(cmd) { - assert.content(this.context, - "Command 'performActions' is not yet available in chrome context"); + assert.content( + this.context, + "Command 'performActions' is not yet available in chrome context" + ); assert.open(this.getCurrentWindow()); await this._handleUserPrompts(); let actions = cmd.parameters.actions; - await this.listener.performActions({"actions": actions}); + await this.listener.performActions({ actions }); }; /** @@ -1938,7 +2013,7 @@ GeckoDriver.prototype.actionChain = async function(cmd) { const win = assert.open(this.getCurrentWindow()); await this._handleUserPrompts(); - let {chain, nextId} = cmd.parameters; + let { chain, nextId } = cmd.parameters; switch (this.context) { case Context.Chrome: @@ -1947,7 +2022,11 @@ GeckoDriver.prototype.actionChain = async function(cmd) { assert.firefox(); return this.legacyactions.dispatchActions( - chain, nextId, {frame: win}, this.curBrowser.seenEls); + chain, + nextId, + { frame: win }, + this.curBrowser.seenEls + ); case Context.Content: return this.listener.actionChain(chain, nextId); @@ -1977,7 +2056,7 @@ GeckoDriver.prototype.multiAction = async function(cmd) { assert.open(this.getCurrentWindow()); await this._handleUserPrompts(); - let {value, max_length} = cmd.parameters; // eslint-disable-line camelcase + let { value, max_length } = cmd.parameters; // eslint-disable-line camelcase await this.listener.multiAction(value, max_length); }; @@ -1998,7 +2077,7 @@ GeckoDriver.prototype.findElement = async function(cmd) { const win = assert.open(this.getCurrentWindow()); await this._handleUserPrompts(); - let {using, value} = cmd.parameters; + let { using, value } = cmd.parameters; let startNode; if (typeof cmd.parameters.element != "undefined") { startNode = WebElement.fromUUID(cmd.parameters.element, this.context); @@ -2016,7 +2095,7 @@ GeckoDriver.prototype.findElement = async function(cmd) { throw new InvalidSelectorError(`Strategy not supported: ${using}`); } - let container = {frame: win}; + let container = { frame: win }; if (opts.startNode) { opts.startNode = this.curBrowser.seenEls.get(opts.startNode); } @@ -2043,7 +2122,7 @@ GeckoDriver.prototype.findElements = async function(cmd) { const win = assert.open(this.getCurrentWindow()); await this._handleUserPrompts(); - let {using, value} = cmd.parameters; + let { using, value } = cmd.parameters; let startNode; if (typeof cmd.parameters.element != "undefined") { startNode = WebElement.fromUUID(cmd.parameters.element, this.context); @@ -2061,7 +2140,7 @@ GeckoDriver.prototype.findElements = async function(cmd) { throw new InvalidSelectorError(`Strategy not supported: ${using}`); } - let container = {frame: win}; + let container = { frame: win }; if (startNode) { opts.startNode = this.curBrowser.seenEls.get(opts.startNode); } @@ -2130,8 +2209,10 @@ GeckoDriver.prototype.clickElement = async function(cmd) { break; case Context.Content: - let click = this.listener.clickElement( - {webElRef: webEl.toJSON(), pageTimeout: this.timeouts.pageLoad}); + let click = this.listener.clickElement({ + webElRef: webEl.toJSON(), + pageTimeout: this.timeouts.pageLoad, + }); // If a process change of the frame script interrupts our page load, // this will never return. We need to re-issue this request to correctly @@ -2144,7 +2225,9 @@ GeckoDriver.prototype.clickElement = async function(cmd) { startTime: new Date().getTime(), }; this.curBrowser.messageManager.sendAsyncMessage( - "Marionette:waitForPageLoaded", parameters); + "Marionette:waitForPageLoaded", + parameters + ); }); await click; @@ -2539,8 +2622,9 @@ GeckoDriver.prototype.sendKeysToElement = async function(cmd) { switch (this.context) { case Context.Chrome: let el = this.curBrowser.seenEls.get(webEl); - await interaction.sendKeysToElement(el, text, - {accessibilityChecks: this.a11yChecks}); + await interaction.sendKeysToElement(el, text, { + accessibilityChecks: this.a11yChecks, + }); break; case Context.Content: @@ -2640,7 +2724,7 @@ GeckoDriver.prototype.addCookie = async function(cmd) { assert.open(this.getCurrentWindow()); await this._handleUserPrompts(); - let {protocol, hostname} = this.currentURL; + let { protocol, hostname } = this.currentURL; const networkSchemes = ["ftp:", "http:", "https:"]; if (!networkSchemes.includes(protocol)) { @@ -2649,7 +2733,7 @@ GeckoDriver.prototype.addCookie = async function(cmd) { let newCookie = cookie.fromJSON(cmd.parameters.cookie); - cookie.add(newCookie, {restrictToHost: hostname}); + cookie.add(newCookie, { restrictToHost: hostname }); }; /** @@ -2670,7 +2754,7 @@ GeckoDriver.prototype.getCookies = async function() { assert.open(this.getCurrentWindow()); await this._handleUserPrompts(); - let {hostname, pathname} = this.currentURL; + let { hostname, pathname } = this.currentURL; return [...cookie.iter(hostname, pathname)]; }; @@ -2689,7 +2773,7 @@ GeckoDriver.prototype.deleteAllCookies = async function() { assert.open(this.getCurrentWindow()); await this._handleUserPrompts(); - let {hostname, pathname} = this.currentURL; + let { hostname, pathname } = this.currentURL; for (let toDelete of cookie.iter(hostname, pathname)) { cookie.remove(toDelete); } @@ -2710,7 +2794,7 @@ GeckoDriver.prototype.deleteCookie = async function(cmd) { assert.open(this.getCurrentWindow()); await this._handleUserPrompts(); - let {hostname, pathname} = this.currentURL; + let { hostname, pathname } = this.currentURL; let name = assert.string(cmd.parameters.name); for (let c of cookie.iter(hostname, pathname)) { if (c.name === name) { @@ -2738,14 +2822,18 @@ GeckoDriver.prototype.newWindow = async function(cmd) { let focus = false; if (typeof cmd.parameters.focus != "undefined") { - focus = assert.boolean(cmd.parameters.focus, - pprint`Expected "focus" to be a boolean, got ${cmd.parameters.focus}`); + focus = assert.boolean( + cmd.parameters.focus, + pprint`Expected "focus" to be a boolean, got ${cmd.parameters.focus}` + ); } let type; if (typeof cmd.parameters.type != "undefined") { - type = assert.string(cmd.parameters.type, - pprint`Expected "type" to be a string, got ${cmd.parameters.type}`); + type = assert.string( + cmd.parameters.type, + pprint`Expected "type" to be a string, got ${cmd.parameters.type}` + ); } // If an invalid or no type has been specified default to a tab. @@ -2776,7 +2864,7 @@ GeckoDriver.prototype.newWindow = async function(cmd) { this.windowHandles.includes(id) ? resolve(id) : reject(); }); - return {handle: windowId.toString(), type}; + return { handle: windowId.toString(), type }; }; /** @@ -2872,7 +2960,8 @@ GeckoDriver.prototype.deleteSession = function() { win.messageManager.removeDelayedFrameScript(FRAME_SCRIPT); } else { logger.error( - `Could not remove listener from page ${win.location.href}`); + `Could not remove listener from page ${win.location.href}` + ); } } } @@ -2936,22 +3025,22 @@ GeckoDriver.prototype.deleteSession = function() { GeckoDriver.prototype.takeScreenshot = function(cmd) { let win = assert.open(this.getCurrentWindow()); - let {id, highlights, full, hash} = cmd.parameters; + let { id, highlights, full, hash } = cmd.parameters; highlights = highlights || []; let format = hash ? capture.Format.Hash : capture.Format.Base64; switch (this.context) { case Context.Chrome: let highlightEls = highlights - .map(ref => WebElement.fromUUID(ref, Context.Chrome)) - .map(webEl => this.curBrowser.seenEls.get(webEl)); + .map(ref => WebElement.fromUUID(ref, Context.Chrome)) + .map(webEl => this.curBrowser.seenEls.get(webEl)); // viewport let canvas; if (!id && !full) { canvas = capture.viewport(win, highlightEls); - // element or full document element + // element or full document element } else { let node; if (id) { @@ -3010,9 +3099,12 @@ GeckoDriver.prototype.setScreenOrientation = function(cmd) { let win = assert.open(this.getCurrentWindow()); const ors = [ - "portrait", "landscape", - "portrait-primary", "landscape-primary", - "portrait-secondary", "landscape-secondary", + "portrait", + "landscape", + "portrait-primary", + "landscape-primary", + "portrait-secondary", + "landscape-secondary", ]; let or = String(cmd.parameters.orientation); @@ -3064,11 +3156,14 @@ GeckoDriver.prototype.minimizeWindow = async function() { let cb; let observer = new WebElementEventTarget(this.curBrowser.messageManager); // Use a timed promise to abort if no window manager is present - await new TimedPromise(resolve => { - cb = new DebounceCallback(resolve); - observer.addEventListener("visibilitychange", cb); - win.minimize(); - }, {throws: null, timeout: TIMEOUT_NO_WINDOW_MANAGER}); + await new TimedPromise( + resolve => { + cb = new DebounceCallback(resolve); + observer.addEventListener("visibilitychange", cb); + win.minimize(); + }, + { throws: null, timeout: TIMEOUT_NO_WINDOW_MANAGER } + ); observer.removeEventListener("visibilitychange", cb); await new IdlePromise(win); } @@ -3112,11 +3207,14 @@ GeckoDriver.prototype.maximizeWindow = async function() { if (WindowState.from(win.windowState) != WindowState.Maximized) { let cb; // Use a timed promise to abort if no window manager is present - await new TimedPromise(resolve => { - cb = new DebounceCallback(resolve); - win.addEventListener("sizemodechange", cb); - win.maximize(); - }, {throws: null, timeout: TIMEOUT_NO_WINDOW_MANAGER}); + await new TimedPromise( + resolve => { + cb = new DebounceCallback(resolve); + win.addEventListener("sizemodechange", cb); + win.maximize(); + }, + { throws: null, timeout: TIMEOUT_NO_WINDOW_MANAGER } + ); win.removeEventListener("sizemodechange", cb); await new IdlePromise(win); } @@ -3157,11 +3255,14 @@ GeckoDriver.prototype.fullscreenWindow = async function() { if (WindowState.from(win.windowState) != WindowState.Fullscreen) { let cb; // Use a timed promise to abort if no window manager is present - await new TimedPromise(resolve => { - cb = new DebounceCallback(resolve); - win.addEventListener("sizemodechange", cb); - win.fullScreen = true; - }, {throws: null, timeout: TIMEOUT_NO_WINDOW_MANAGER}); + await new TimedPromise( + resolve => { + cb = new DebounceCallback(resolve); + win.addEventListener("sizemodechange", cb); + win.fullScreen = true; + }, + { throws: null, timeout: TIMEOUT_NO_WINDOW_MANAGER } + ); win.removeEventListener("sizemodechange", cb); } await new IdlePromise(win); @@ -3179,7 +3280,7 @@ GeckoDriver.prototype.dismissDialog = async function() { let dialogClosed = waitForEvent(win, "DOMModalDialogClosed"); - let {button0, button1} = this.dialog.ui; + let { button0, button1 } = this.dialog.ui; (button1 ? button1 : button0).click(); await dialogClosed; @@ -3196,7 +3297,7 @@ GeckoDriver.prototype.acceptDialog = async function() { let dialogClosed = waitForEvent(win, "DOMModalDialogClosed"); - let {button0} = this.dialog.ui; + let { button0 } = this.dialog.ui; button0.click(); await dialogClosed; @@ -3244,16 +3345,18 @@ GeckoDriver.prototype.sendKeysToDialog = async function(cmd) { case "alert": case "confirm": throw new ElementNotInteractableError( - `User prompt of type ${promptType} is not interactable`); + `User prompt of type ${promptType} is not interactable` + ); case "prompt": break; default: throw new UnsupportedOperationError( - `User prompt of type ${promptType} is not supported`); + `User prompt of type ${promptType} is not supported` + ); } // see toolkit/components/prompts/content/commonDialog.js - let {loginTextbox} = this.dialog.ui; + let { loginTextbox } = this.dialog.ui; loginTextbox.value = text; }; @@ -3268,7 +3371,7 @@ GeckoDriver.prototype._handleUserPrompts = async function() { return; } - let {textContent} = this.dialog.ui.infoBody; + let { textContent } = this.dialog.ui.infoBody; let behavior = this.capabilities.get("unhandledPromptBehavior"); switch (behavior) { @@ -3279,7 +3382,8 @@ GeckoDriver.prototype._handleUserPrompts = async function() { case UnhandledPromptBehavior.AcceptAndNotify: await this.acceptDialog(); throw new UnexpectedAlertOpenError( - `Accepted user prompt dialog: ${textContent}`); + `Accepted user prompt dialog: ${textContent}` + ); case UnhandledPromptBehavior.Dismiss: await this.dismissDialog(); @@ -3288,11 +3392,13 @@ GeckoDriver.prototype._handleUserPrompts = async function() { case UnhandledPromptBehavior.DismissAndNotify: await this.dismissDialog(); throw new UnexpectedAlertOpenError( - `Dismissed user prompt dialog: ${textContent}`); + `Dismissed user prompt dialog: ${textContent}` + ); case UnhandledPromptBehavior.Ignore: throw new UnexpectedAlertOpenError( - "Encountered unhandled user prompt dialog"); + "Encountered unhandled user prompt dialog" + ); default: throw new TypeError(`Unknown unhandledPromptBehavior "${behavior}"`); @@ -3368,7 +3474,8 @@ GeckoDriver.prototype.quit = async function(cmd) { if (quits.includes(k)) { if (quitSeen) { throw new InvalidArgumentError( - `${k} cannot be combined with ${quitSeen}`); + `${k} cannot be combined with ${quitSeen}` + ); } quitSeen = k; } @@ -3386,7 +3493,7 @@ GeckoDriver.prototype.quit = async function(cmd) { let quitApplication = waitForObserverTopic("quit-application"); Services.startup.quit(mode); - return {cause: (await quitApplication).data}; + return { cause: (await quitApplication).data }; }; GeckoDriver.prototype.installAddon = function(cmd) { @@ -3394,8 +3501,11 @@ GeckoDriver.prototype.installAddon = function(cmd) { let path = cmd.parameters.path; let temp = cmd.parameters.temporary || false; - if (typeof path == "undefined" || typeof path != "string" || - typeof temp != "boolean") { + if ( + typeof path == "undefined" || + typeof path != "string" || + typeof temp != "boolean" + ) { throw new InvalidArgumentError(); } @@ -3425,12 +3535,14 @@ GeckoDriver.prototype.receiveMessage = function(message) { // we allow frame switching after modals appear, which would // override this value and we'd lose our reference if (message.json.storePrevious) { - this.previousFrameElement = - new ChromeWebElement(this.currentFrameElement); + this.previousFrameElement = new ChromeWebElement( + this.currentFrameElement + ); } if (message.json.frameValue) { - this.currentFrameElement = - new ChromeWebElement(message.json.frameValue); + this.currentFrameElement = new ChromeWebElement( + message.json.frameValue + ); } else { this.currentFrameElement = null; } @@ -3438,9 +3550,9 @@ GeckoDriver.prototype.receiveMessage = function(message) { break; case "Marionette:Register": - let {outerWindowID} = message.json; + let { outerWindowID } = message.json; this.registerBrowser(outerWindowID, message.target); - return {outerWindowID}; + return { outerWindowID }; case "Marionette:ListenersAttached": if (message.json.outerWindowID === this.curBrowser.curFrameId) { @@ -3475,7 +3587,7 @@ GeckoDriver.prototype.responseCompleted = function() { * The localized string for the requested entity. */ GeckoDriver.prototype.localizeEntity = function(cmd) { - let {urls, id} = cmd.parameters; + let { urls, id } = cmd.parameters; if (!Array.isArray(urls)) { throw new InvalidArgumentError("Value of `urls` should be of type 'Array'"); @@ -3504,7 +3616,7 @@ GeckoDriver.prototype.localizeEntity = function(cmd) { * The localized string for the requested property. */ GeckoDriver.prototype.localizeProperty = function(cmd) { - let {urls, id} = cmd.parameters; + let { urls, id } = cmd.parameters; if (!Array.isArray(urls)) { throw new InvalidArgumentError("Value of `urls` should be of type 'Array'"); @@ -3522,40 +3634,51 @@ GeckoDriver.prototype.localizeProperty = function(cmd) { GeckoDriver.prototype.setupReftest = async function(cmd) { if (this._reftest) { throw new UnsupportedOperationError( - "Called reftest:setup with a reftest session already active"); + "Called reftest:setup with a reftest session already active" + ); } if (this.context !== Context.Chrome) { throw new UnsupportedOperationError( - "Must set chrome context before running reftests"); + "Must set chrome context before running reftests" + ); } - let {urlCount = {}, screenshot = "unexpected"} = cmd.parameters; + let { urlCount = {}, screenshot = "unexpected" } = cmd.parameters; if (!["always", "fail", "unexpected"].includes(screenshot)) { throw new InvalidArgumentError( - "Value of `screenshot` should be 'always', 'fail' or 'unexpected'"); + "Value of `screenshot` should be 'always', 'fail' or 'unexpected'" + ); } this._reftest = new reftest.Runner(this); this._reftest.setup(urlCount, screenshot); }; - /** Run a reftest. */ GeckoDriver.prototype.runReftest = async function(cmd) { - let {test, references, expected, timeout, width, height} = cmd.parameters; + let { test, references, expected, timeout, width, height } = cmd.parameters; if (!this._reftest) { throw new UnsupportedOperationError( - "Called reftest:run before reftest:start"); + "Called reftest:run before reftest:start" + ); } assert.string(test); assert.string(expected); assert.array(references); - return {value: await this._reftest.run( - test, references, expected, timeout, width, height)}; + return { + value: await this._reftest.run( + test, + references, + expected, + timeout, + width, + height + ), + }; }; /** @@ -3567,7 +3690,8 @@ GeckoDriver.prototype.runReftest = async function(cmd) { GeckoDriver.prototype.teardownReftest = function() { if (!this._reftest) { throw new UnsupportedOperationError( - "Called reftest:teardown before reftest:start"); + "Called reftest:teardown before reftest:start" + ); } this._reftest.abort(); @@ -3583,8 +3707,8 @@ GeckoDriver.prototype.commands = { "Marionette:Quit": GeckoDriver.prototype.quit, "Marionette:SetContext": GeckoDriver.prototype.setContext, "Marionette:SetScreenOrientation": GeckoDriver.prototype.setScreenOrientation, - "Marionette:ActionChain": GeckoDriver.prototype.actionChain, // bug 1354578, legacy actions - "Marionette:MultiAction": GeckoDriver.prototype.multiAction, // bug 1354578, legacy actions + "Marionette:ActionChain": GeckoDriver.prototype.actionChain, // bug 1354578, legacy actions + "Marionette:MultiAction": GeckoDriver.prototype.multiAction, // bug 1354578, legacy actions "Marionette:SingleTap": GeckoDriver.prototype.singleTap, // Addon service @@ -3602,7 +3726,7 @@ GeckoDriver.prototype.commands = { // WebDriver service "WebDriver:AcceptAlert": GeckoDriver.prototype.acceptDialog, - "WebDriver:AcceptDialog": GeckoDriver.prototype.acceptDialog, // deprecated, but used in geckodriver (see also bug 1495063) + "WebDriver:AcceptDialog": GeckoDriver.prototype.acceptDialog, // deprecated, but used in geckodriver (see also bug 1495063) "WebDriver:AddCookie": GeckoDriver.prototype.addCookie, "WebDriver:Back": GeckoDriver.prototype.goBack, "WebDriver:CloseChromeWindow": GeckoDriver.prototype.closeChromeWindow, @@ -3624,13 +3748,17 @@ GeckoDriver.prototype.commands = { "WebDriver:GetActiveFrame": GeckoDriver.prototype.getActiveFrame, "WebDriver:GetAlertText": GeckoDriver.prototype.getTextFromDialog, "WebDriver:GetCapabilities": GeckoDriver.prototype.getSessionCapabilities, - "WebDriver:GetChromeWindowHandle": GeckoDriver.prototype.getChromeWindowHandle, - "WebDriver:GetChromeWindowHandles": GeckoDriver.prototype.getChromeWindowHandles, + "WebDriver:GetChromeWindowHandle": + GeckoDriver.prototype.getChromeWindowHandle, + "WebDriver:GetChromeWindowHandles": + GeckoDriver.prototype.getChromeWindowHandles, "WebDriver:GetCookies": GeckoDriver.prototype.getCookies, - "WebDriver:GetCurrentChromeWindowHandle": GeckoDriver.prototype.getChromeWindowHandle, + "WebDriver:GetCurrentChromeWindowHandle": + GeckoDriver.prototype.getChromeWindowHandle, "WebDriver:GetCurrentURL": GeckoDriver.prototype.getCurrentUrl, "WebDriver:GetElementAttribute": GeckoDriver.prototype.getElementAttribute, - "WebDriver:GetElementCSSValue": GeckoDriver.prototype.getElementValueOfCssProperty, + "WebDriver:GetElementCSSValue": + GeckoDriver.prototype.getElementValueOfCssProperty, "WebDriver:GetElementProperty": GeckoDriver.prototype.getElementProperty, "WebDriver:GetElementRect": GeckoDriver.prototype.getElementRect, "WebDriver:GetElementTagName": GeckoDriver.prototype.getElementTagName, @@ -3650,7 +3778,7 @@ GeckoDriver.prototype.commands = { "WebDriver:NewSession": GeckoDriver.prototype.newSession, "WebDriver:NewWindow": GeckoDriver.prototype.newWindow, "WebDriver:PerformActions": GeckoDriver.prototype.performActions, - "WebDriver:Refresh": GeckoDriver.prototype.refresh, + "WebDriver:Refresh": GeckoDriver.prototype.refresh, "WebDriver:ReleaseActions": GeckoDriver.prototype.releaseActions, "WebDriver:SendAlertText": GeckoDriver.prototype.sendKeysToDialog, "WebDriver:SetTimeouts": GeckoDriver.prototype.setTimeouts, @@ -3669,22 +3797,28 @@ function getOuterWindowId(win) { async function exitFullscreen(win) { let cb; // Use a timed promise to abort if no window manager is present - await new TimedPromise(resolve => { - cb = new DebounceCallback(resolve); - win.addEventListener("sizemodechange", cb); - win.fullScreen = false; - }, {throws: null, timeout: TIMEOUT_NO_WINDOW_MANAGER}); + await new TimedPromise( + resolve => { + cb = new DebounceCallback(resolve); + win.addEventListener("sizemodechange", cb); + win.fullScreen = false; + }, + { throws: null, timeout: TIMEOUT_NO_WINDOW_MANAGER } + ); win.removeEventListener("sizemodechange", cb); } async function restoreWindow(win) { win.restore(); // Use a poll promise to abort if no window manager is present - await new PollPromise((resolve, reject) => { - if (WindowState.from(win.windowState) == WindowState.Normal) { - resolve(); - } else { - reject(); - } - }, {timeout: TIMEOUT_NO_WINDOW_MANAGER}); + await new PollPromise( + (resolve, reject) => { + if (WindowState.from(win.windowState) == WindowState.Normal) { + resolve(); + } else { + reject(); + } + }, + { timeout: TIMEOUT_NO_WINDOW_MANAGER } + ); } diff --git a/testing/marionette/element.js b/testing/marionette/element.js index 4097c0803248..00e64991d1e0 100644 --- a/testing/marionette/element.js +++ b/testing/marionette/element.js @@ -5,16 +5,18 @@ "use strict"; /* global XPCNativeWrapper */ -const {assert} = ChromeUtils.import("chrome://marionette/content/assert.js"); -const {atom} = ChromeUtils.import("chrome://marionette/content/atom.js"); +const { assert } = ChromeUtils.import("chrome://marionette/content/assert.js"); +const { atom } = ChromeUtils.import("chrome://marionette/content/atom.js"); const { InvalidArgumentError, InvalidSelectorError, NoSuchElementError, StaleElementReferenceError, } = ChromeUtils.import("chrome://marionette/content/error.js"); -const {pprint} = ChromeUtils.import("chrome://marionette/content/format.js"); -const {PollPromise} = ChromeUtils.import("chrome://marionette/content/sync.js"); +const { pprint } = ChromeUtils.import("chrome://marionette/content/format.js"); +const { PollPromise } = ChromeUtils.import( + "chrome://marionette/content/sync.js" +); this.EXPORTED_SYMBOLS = [ "ChromeWebElement", @@ -35,11 +37,7 @@ const XBLNS = "http://www.mozilla.org/xbl"; const XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; /** XUL elements that support checked property. */ -const XUL_CHECKED_ELS = new Set([ - "button", - "checkbox", - "toolbarbutton", -]); +const XUL_CHECKED_ELS = new Set(["button", "checkbox", "toolbarbutton"]); /** XUL elements that support selected property. */ const XUL_SELECTED_ELS = new Set([ @@ -51,8 +49,9 @@ const XUL_SELECTED_ELS = new Set([ "tab", ]); -const uuidGen = Cc["@mozilla.org/uuid-generator;1"] - .getService(Ci.nsIUUIDGenerator); +const uuidGen = Cc["@mozilla.org/uuid-generator;1"].getService( + Ci.nsIUUIDGenerator +); /** * This module provides shared functionality for dealing with DOM- @@ -144,8 +143,8 @@ element.Store = class { if (!(isDOMElement || isDOMWindow || isXULElement)) { throw new TypeError( - "Expected an element or WindowProxy, " + - pprint`got: ${el}`); + "Expected an element or WindowProxy, " + pprint`got: ${el}` + ); } for (let i in this.els) { @@ -159,7 +158,7 @@ element.Store = class { return WebElement.fromUUID(i, context); } - // cleanup reference to gc'd element + // cleanup reference to gc'd element } else { delete this.els[i]; } @@ -188,8 +187,7 @@ element.Store = class { */ has(webEl) { if (!(webEl instanceof WebElement)) { - throw new TypeError( - pprint`Expected web element, got: ${webEl}`); + throw new TypeError(pprint`Expected web element, got: ${webEl}`); } return Object.keys(this.els).includes(webEl.uuid); } @@ -220,12 +218,12 @@ element.Store = class { */ get(webEl, win) { if (!(webEl instanceof WebElement)) { - throw new TypeError( - pprint`Expected web element, got: ${webEl}`); + throw new TypeError(pprint`Expected web element, got: ${webEl}`); } if (!this.has(webEl)) { throw new NoSuchElementError( - "Web element reference not seen before: " + webEl.uuid); + "Web element reference not seen before: " + webEl.uuid + ); } let el; @@ -238,10 +236,11 @@ element.Store = class { if (element.isStale(el, win)) { throw new StaleElementReferenceError( - pprint`The element reference of ${el || webEl.uuid} is stale; ` + - "either the element is no longer attached to the DOM, " + - "it is not in the current frame context, " + - "or the document has been refreshed"); + pprint`The element reference of ${el || webEl.uuid} is stale; ` + + "either the element is no longer attached to the DOM, " + + "it is not in the current frame context, " + + "or the document has been refreshed" + ); } return el; @@ -311,15 +310,20 @@ element.find = function(container, strategy, selector, opts = {}) { } return new Promise((resolve, reject) => { - let findElements = new PollPromise((resolve, reject) => { - let res = find_(container, strategy, selector, searchFn, - {all, startNode}); - if (res.length > 0) { - resolve(Array.from(res)); - } else { - reject([]); - } - }, {timeout}); + let findElements = new PollPromise( + (resolve, reject) => { + let res = find_(container, strategy, selector, searchFn, { + all, + startNode, + }); + if (res.length > 0) { + resolve(Array.from(res)); + } else { + reject([]); + } + }, + { timeout } + ); findElements.then(foundEls => { // the following code ought to be moved into findElement @@ -328,8 +332,8 @@ element.find = function(container, strategy, selector, opts = {}) { let msg; switch (strategy) { case element.Strategy.AnonAttribute: - msg = "Unable to locate anonymous element: " + - JSON.stringify(selector); + msg = + "Unable to locate anonymous element: " + JSON.stringify(selector); break; default: @@ -347,8 +351,13 @@ element.find = function(container, strategy, selector, opts = {}) { }); }; -function find_(container, strategy, selector, searchFn, - {startNode = null, all = false} = {}) { +function find_( + container, + strategy, + selector, + searchFn, + { startNode = null, all = false } = {} +) { let rootNode = container.shadowRoot || container.frame.document; if (!startNode) { @@ -372,7 +381,8 @@ function find_(container, strategy, selector, searchFn, res = searchFn(strategy, selector, rootNode, startNode); } catch (e) { throw new InvalidSelectorError( - `Given ${strategy} expression "${selector}" is invalid: ${e}`); + `Given ${strategy} expression "${selector}" is invalid: ${e}` + ); } if (res) { @@ -399,7 +409,12 @@ function find_(container, strategy, selector, searchFn, */ element.findByXPath = function(document, startNode, expression) { let iter = document.evaluate( - expression, startNode, null, FIRST_ORDERED_NODE_TYPE, null); + expression, + startNode, + null, + FIRST_ORDERED_NODE_TYPE, + null + ); return iter.singleNodeValue; }; @@ -416,9 +431,14 @@ element.findByXPath = function(document, startNode, expression) { * @return {Iterable.} * Iterator over elements matching expression. */ -element.findByXPathAll = function* (document, startNode, expression) { +element.findByXPathAll = function*(document, startNode, expression) { let iter = document.evaluate( - expression, startNode, null, ORDERED_NODE_ITERATOR_TYPE, null); + expression, + startNode, + null, + ORDERED_NODE_ITERATOR_TYPE, + null + ); let el = iter.iterateNext(); while (el) { yield el; @@ -439,8 +459,10 @@ element.findByXPathAll = function* (document, startNode, expression) { * Sequence of link elements which text is s. */ element.findByLinkText = function(startNode, linkText) { - return filterLinks(startNode, - link => atom.getElementText(link).trim() === linkText); + return filterLinks( + startNode, + link => atom.getElementText(link).trim() === linkText + ); }; /** @@ -457,8 +479,9 @@ element.findByLinkText = function(startNode, linkText) { * linkText. */ element.findByPartialLinkText = function(startNode, linkText) { - return filterLinks(startNode, - link => atom.getElementText(link).includes(linkText)); + return filterLinks(startNode, link => + atom.getElementText(link).includes(linkText) + ); }; /** @@ -472,7 +495,7 @@ element.findByPartialLinkText = function(startNode, linkText) { * @return {Iterable.} * Iterator over anonymous elements. */ -element.findAnonymousNodes = function* (document, node) { +element.findAnonymousNodes = function*(document, node) { let anons = document.getAnonymousNodes(node) || []; for (let node of anons) { yield node; @@ -522,23 +545,21 @@ function* filterLinks(startNode, predicate) { */ function findElement(strategy, selector, document, startNode = undefined) { switch (strategy) { - case element.Strategy.ID: - { - if (startNode.getElementById) { - return startNode.getElementById(selector); - } - let expr = `.//*[@id="${selector}"]`; - return element.findByXPath(document, startNode, expr); + case element.Strategy.ID: { + if (startNode.getElementById) { + return startNode.getElementById(selector); } + let expr = `.//*[@id="${selector}"]`; + return element.findByXPath(document, startNode, expr); + } - case element.Strategy.Name: - { - if (startNode.getElementsByName) { - return startNode.getElementsByName(selector)[0]; - } - let expr = `.//*[@name="${selector}"]`; - return element.findByXPath(document, startNode, expr); + case element.Strategy.Name: { + if (startNode.getElementsByName) { + return startNode.getElementsByName(selector)[0]; } + let expr = `.//*[@name="${selector}"]`; + return element.findByXPath(document, startNode, expr); + } case element.Strategy.ClassName: return startNode.getElementsByClassName(selector)[0]; @@ -578,7 +599,10 @@ function findElement(strategy, selector, document, startNode = undefined) { case element.Strategy.AnonAttribute: let attr = Object.keys(selector)[0]; return document.getAnonymousElementByAttribute( - startNode, attr, selector[attr]); + startNode, + attr, + selector[attr] + ); } throw new InvalidSelectorError(`No such strategy: ${strategy}`); @@ -617,8 +641,13 @@ function findElements(strategy, selector, document, startNode = undefined) { if (startNode.getElementsByName) { return startNode.getElementsByName(selector); } - return [...element.findByXPathAll( - document, startNode, `.//*[@name="${selector}"]`)]; + return [ + ...element.findByXPathAll( + document, + startNode, + `.//*[@name="${selector}"]` + ), + ]; case element.Strategy.ClassName: return startNode.getElementsByClassName(selector); @@ -641,7 +670,10 @@ function findElements(strategy, selector, document, startNode = undefined) { case element.Strategy.AnonAttribute: let attr = Object.keys(selector)[0]; let el = document.getAnonymousElementByAttribute( - startNode, attr, selector[attr]); + startNode, + attr, + selector[attr] + ); if (el) { return [el]; } @@ -733,9 +765,7 @@ element.isStale = function(el, win = undefined) { win = el.ownerGlobal; } - if (el === null || - !el.ownerGlobal || - el.ownerDocument !== win.document) { + if (el === null || !el.ownerGlobal || el.ownerDocument !== win.document) { return true; } @@ -790,8 +820,11 @@ element.isSelected = function(el) { * True if element is read only. */ element.isReadOnly = function(el) { - return element.isDOMElement(el) && - ["input", "textarea"].includes(el.localName) && el.readOnly; + return ( + element.isDOMElement(el) && + ["input", "textarea"].includes(el.localName) && + el.readOnly + ); }; /** @@ -896,8 +929,10 @@ element.isMutableFormControl = function(el) { * True if editing host, false otherwise. */ element.isEditingHost = function(el) { - return element.isDOMElement(el) && - (el.isContentEditable || el.ownerDocument.designMode == "on"); + return ( + element.isDOMElement(el) && + (el.isContentEditable || el.ownerDocument.designMode == "on") + ); }; /** @@ -956,8 +991,7 @@ element.isEditable = function(el) { * @throws TypeError * If xOffset or yOffset are not numbers. */ -element.coordinates = function( - node, xOffset = undefined, yOffset = undefined) { +element.coordinates = function(node, xOffset = undefined, yOffset = undefined) { let box = node.getBoundingClientRect(); if (typeof xOffset == "undefined" || xOffset === null) { @@ -998,14 +1032,16 @@ element.inViewport = function(el, x = undefined, y = undefined) { let vp = { top: win.pageYOffset, left: win.pageXOffset, - bottom: (win.pageYOffset + win.innerHeight), - right: (win.pageXOffset + win.innerWidth), + bottom: win.pageYOffset + win.innerHeight, + right: win.pageXOffset + win.innerWidth, }; - return (vp.left <= c.x + win.pageXOffset && - c.x + win.pageXOffset <= vp.right && - vp.top <= c.y + win.pageYOffset && - c.y + win.pageYOffset <= vp.bottom); + return ( + vp.left <= c.x + win.pageXOffset && + c.x + win.pageXOffset <= vp.right && + vp.top <= c.y + win.pageYOffset && + c.y + win.pageYOffset <= vp.bottom + ); }; /** @@ -1163,7 +1199,7 @@ element.isObscured = function(el) { * `rect`. */ element.getInViewCentrePoint = function(rect, win) { - const {floor, max, min} = Math; + const { floor, max, min } = Math; // calculate the intersection of the rect that is inside the viewport let visible = { @@ -1181,7 +1217,7 @@ element.getInViewCentrePoint = function(rect, win) { x = floor(x); y = floor(y); - return {x, y}; + return { x, y }; }; /** @@ -1232,7 +1268,7 @@ element.isKeyboardInteractable = () => true; */ element.scrollIntoView = function(el) { if (el.scrollIntoView) { - el.scrollIntoView({block: "end", inline: "nearest", behavior: "instant"}); + el.scrollIntoView({ block: "end", inline: "nearest", behavior: "instant" }); } }; @@ -1260,11 +1296,13 @@ element.isElement = function(node) { * True if node is a DOM element, false otherwise. */ element.isDOMElement = function(node) { - return typeof node == "object" && - node !== null && - "nodeType" in node && - [ELEMENT_NODE, DOCUMENT_NODE].includes(node.nodeType) && - !element.isXULElement(node); + return ( + typeof node == "object" && + node !== null && + "nodeType" in node && + [ELEMENT_NODE, DOCUMENT_NODE].includes(node.nodeType) && + !element.isXULElement(node) + ); }; /** @@ -1278,11 +1316,13 @@ element.isDOMElement = function(node) { * false otherwise. */ element.isXULElement = function(node) { - return typeof node == "object" && - node !== null && - "nodeType" in node && - node.nodeType === node.ELEMENT_NODE && - [XBLNS, XULNS].includes(node.namespaceURI); + return ( + typeof node == "object" && + node !== null && + "nodeType" in node && + node.nodeType === node.ELEMENT_NODE && + [XBLNS, XULNS].includes(node.namespaceURI) + ); }; /** @@ -1298,11 +1338,13 @@ element.isDOMWindow = function(node) { // TODO(ato): This should use Object.prototype.toString.call(node) // but it's not clear how to write a good xpcshell test for that, // seeing as we stub out a WindowProxy. - return typeof node == "object" && - node !== null && - typeof node.toString == "function" && - node.toString() == "[object Window]" && - node.self === node; + return ( + typeof node == "object" && + node !== null && + typeof node.toString == "function" && + node.toString() == "[object Window]" && + node.self === node + ); }; const boolEls = { @@ -1428,8 +1470,9 @@ class WebElement { return new ChromeWebElement(uuid); } - throw new InvalidArgumentError("Expected DOM window/element " + - pprint`or XUL element, got: ${node}`); + throw new InvalidArgumentError( + "Expected DOM window/element " + pprint`or XUL element, got: ${node}` + ); } /** @@ -1469,7 +1512,8 @@ class WebElement { } throw new InvalidArgumentError( - pprint`Expected web element reference, got: ${json}`); + pprint`Expected web element reference, got: ${json}` + ); } /** @@ -1526,10 +1570,12 @@ class WebElement { return false; } - if ((ContentWebElement.Identifier in obj) || - (ContentWebWindow.Identifier in obj) || - (ContentWebFrame.Identifier in obj) || - (ChromeWebElement.Identifier in obj)) { + if ( + ContentWebElement.Identifier in obj || + ContentWebWindow.Identifier in obj || + ContentWebFrame.Identifier in obj || + ChromeWebElement.Identifier in obj + ) { return true; } return false; @@ -1554,15 +1600,16 @@ this.WebElement = WebElement; */ class ContentWebElement extends WebElement { toJSON() { - return {[ContentWebElement.Identifier]: this.uuid}; + return { [ContentWebElement.Identifier]: this.uuid }; } static fromJSON(json) { - const {Identifier} = ContentWebElement; + const { Identifier } = ContentWebElement; if (!(Identifier in json)) { throw new InvalidArgumentError( - pprint`Expected web element reference, got: ${json}`); + pprint`Expected web element reference, got: ${json}` + ); } let uuid = json[Identifier]; @@ -1579,13 +1626,14 @@ this.ContentWebElement = ContentWebElement; */ class ContentWebWindow extends WebElement { toJSON() { - return {[ContentWebWindow.Identifier]: this.uuid}; + return { [ContentWebWindow.Identifier]: this.uuid }; } static fromJSON(json) { if (!(ContentWebWindow.Identifier in json)) { throw new InvalidArgumentError( - pprint`Expected web window reference, got: ${json}`); + pprint`Expected web window reference, got: ${json}` + ); } let uuid = json[ContentWebWindow.Identifier]; return new ContentWebWindow(uuid); @@ -1601,13 +1649,14 @@ this.ContentWebWindow = ContentWebWindow; */ class ContentWebFrame extends WebElement { toJSON() { - return {[ContentWebFrame.Identifier]: this.uuid}; + return { [ContentWebFrame.Identifier]: this.uuid }; } static fromJSON(json) { if (!(ContentWebFrame.Identifier in json)) { throw new InvalidArgumentError( - pprint`Expected web frame reference, got: ${json}`); + pprint`Expected web frame reference, got: ${json}` + ); } let uuid = json[ContentWebFrame.Identifier]; return new ContentWebFrame(uuid); @@ -1622,13 +1671,15 @@ this.ContentWebFrame = ContentWebFrame; */ class ChromeWebElement extends WebElement { toJSON() { - return {[ChromeWebElement.Identifier]: this.uuid}; + return { [ChromeWebElement.Identifier]: this.uuid }; } static fromJSON(json) { if (!(ChromeWebElement.Identifier in json)) { - throw new InvalidArgumentError("Expected chrome element reference " + - pprint`for XUL/XBL element, got: ${json}`); + throw new InvalidArgumentError( + "Expected chrome element reference " + + pprint`for XUL/XBL element, got: ${json}` + ); } let uuid = json[ChromeWebElement.Identifier]; return new ChromeWebElement(uuid); diff --git a/testing/marionette/error.js b/testing/marionette/error.js index aba291a48ab8..43bb52eb451d 100644 --- a/testing/marionette/error.js +++ b/testing/marionette/error.js @@ -4,7 +4,7 @@ "use strict"; -const {pprint} = ChromeUtils.import("chrome://marionette/content/format.js"); +const { pprint } = ChromeUtils.import("chrome://marionette/content/format.js"); const ERRORS = new Set([ "ElementClickInterceptedError", @@ -45,10 +45,7 @@ const BUILTIN_ERRORS = new Set([ "URIError", ]); -this.EXPORTED_SYMBOLS = [ - "error", - "stack", -].concat(Array.from(ERRORS)); +this.EXPORTED_SYMBOLS = ["error", "stack"].concat(Array.from(ERRORS)); /** @namespace */ this.error = {}; @@ -103,8 +100,7 @@ error.isError = function(val) { * false otherwise. */ error.isWebDriverError = function(obj) { - return error.isError(obj) && - ("name" in obj && ERRORS.has(obj.name)); + return error.isError(obj) && ("name" in obj && ERRORS.has(obj.name)); }; /** @@ -257,18 +253,20 @@ class ElementClickInterceptedError extends WebDriverError { switch (obscuredEl.style.pointerEvents) { case "none": - msg = pprint`Element ${obscuredEl} is not clickable ` + - `at point (${coords.x},${coords.y}) ` + - `because it does not have pointer events enabled, ` + - pprint`and element ${overlayingEl} ` + - `would receive the click instead`; + msg = + pprint`Element ${obscuredEl} is not clickable ` + + `at point (${coords.x},${coords.y}) ` + + `because it does not have pointer events enabled, ` + + pprint`and element ${overlayingEl} ` + + `would receive the click instead`; break; default: - msg = pprint`Element ${obscuredEl} is not clickable ` + - `at point (${coords.x},${coords.y}) ` + - pprint`because another element ${overlayingEl} ` + - `obscures it`; + msg = + pprint`Element ${obscuredEl} is not clickable ` + + `at point (${coords.x},${coords.y}) ` + + pprint`because another element ${overlayingEl} ` + + `obscures it`; break; } } diff --git a/testing/marionette/evaluate.js b/testing/marionette/evaluate.js index d37a029427f7..0cd83afde8ce 100644 --- a/testing/marionette/evaluate.js +++ b/testing/marionette/evaluate.js @@ -4,19 +4,21 @@ "use strict"; -const {clearTimeout, setTimeout} = ChromeUtils.import("resource://gre/modules/Timer.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { clearTimeout, setTimeout } = ChromeUtils.import( + "resource://gre/modules/Timer.jsm" +); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); -const {assert} = ChromeUtils.import("chrome://marionette/content/assert.js"); -const { - element, - WebElement, -} = ChromeUtils.import("chrome://marionette/content/element.js"); -const { - JavaScriptError, - ScriptTimeoutError, -} = ChromeUtils.import("chrome://marionette/content/error.js"); -const {Log} = ChromeUtils.import("chrome://marionette/content/log.js"); +const { assert } = ChromeUtils.import("chrome://marionette/content/assert.js"); +const { element, WebElement } = ChromeUtils.import( + "chrome://marionette/content/element.js" +); +const { JavaScriptError, ScriptTimeoutError } = ChromeUtils.import( + "chrome://marionette/content/error.js" +); +const { Log } = ChromeUtils.import("chrome://marionette/content/log.js"); XPCOMUtils.defineLazyGetter(this, "log", Log.get); @@ -84,13 +86,17 @@ this.evaluate = {}; * @throws {ScriptTimeoutError} * If the script was interrupted due to script timeout. */ -evaluate.sandbox = function(sb, script, args = [], - { - async = false, - file = "dummy file", - line = 0, - timeout = DEFAULT_TIMEOUT, - } = {}) { +evaluate.sandbox = function( + sb, + script, + args = [], + { + async = false, + file = "dummy file", + line = 0, + timeout = DEFAULT_TIMEOUT, + } = {} +) { let unloadHandler; // timeout handler @@ -121,7 +127,9 @@ evaluate.sandbox = function(sb, script, args = [], }).apply(null, ${ARGUMENTS})`; unloadHandler = sandbox.cloneInto( - () => reject(new JavaScriptError("Document was unloaded")), sb); + () => reject(new JavaScriptError("Document was unloaded")), + sb + ); sb.window.onunload = unloadHandler; let promises = [ @@ -132,28 +140,33 @@ evaluate.sandbox = function(sb, script, args = [], // Wait for the immediate result of calling evalInSandbox, or a timeout. // Only resolve the promise if the scriptPromise was resolved and is not // async, because the latter has to call resolve() itself. - Promise.race(promises).then(value => { - if (!async) { - resolve(value); + Promise.race(promises).then( + value => { + if (!async) { + resolve(value); + } + }, + err => { + reject(err); } - }, err => { - reject(err); - }); + ); }); // This block is mainly for async scripts, which escape the inner promise // when calling resolve() on their own. The timeout promise will be re-used // to break out after the initially setup timeout. - return Promise.race([promise, timeoutPromise]).catch(err => { - // Only raise valid errors for both the sync and async scripts. - if (err instanceof ScriptTimeoutError) { - throw err; - } - throw new JavaScriptError(err); - }).finally(() => { - clearTimeout(scriptTimeoutID); - sb.window.removeEventListener("unload", unloadHandler); - }); + return Promise.race([promise, timeoutPromise]) + .catch(err => { + // Only raise valid errors for both the sync and async scripts. + if (err instanceof ScriptTimeoutError) { + throw err; + } + throw new JavaScriptError(err); + }) + .finally(() => { + clearTimeout(scriptTimeoutID); + sb.window.removeEventListener("unload", unloadHandler); + }); }; /** @@ -192,11 +205,11 @@ evaluate.fromJSON = function(obj, seenEls = undefined, win = undefined) { if (obj === null) { return obj; - // arrays + // arrays } else if (Array.isArray(obj)) { return obj.map(e => evaluate.fromJSON(e, seenEls, win)); - // web elements + // web elements } else if (WebElement.isReference(obj)) { let webEl = WebElement.fromJSON(obj); if (seenEls) { @@ -255,26 +268,28 @@ evaluate.toJSON = function(obj, seenEls) { if (t == "[object Undefined]" || t == "[object Null]") { return null; - // primitives - } else if (t == "[object Boolean]" || - t == "[object Number]" || - t == "[object String]") { + // primitives + } else if ( + t == "[object Boolean]" || + t == "[object Number]" || + t == "[object String]" + ) { return obj; - // Array, NodeList, HTMLCollection, et al. + // Array, NodeList, HTMLCollection, et al. } else if (element.isCollection(obj)) { assert.acyclic(obj); return [...obj].map(el => evaluate.toJSON(el, seenEls)); - // WebElement + // WebElement } else if (WebElement.isReference(obj)) { return obj; - // Element (HTMLElement, SVGElement, XULElement, et al.) + // Element (HTMLElement, SVGElement, XULElement, et al.) } else if (element.isElement(obj)) { return seenEls.add(obj); - // custom JSON representation + // custom JSON representation } else if (typeof obj.toJSON == "function") { let unsafeJSON = obj.toJSON(); return evaluate.toJSON(unsafeJSON, seenEls); @@ -318,17 +333,19 @@ evaluate.isCyclic = function(value, stack = []) { if (t == "[object Undefined]" || t == "[object Null]") { return false; - // primitives - } else if (t == "[object Boolean]" || - t == "[object Number]" || - t == "[object String]") { + // primitives + } else if ( + t == "[object Boolean]" || + t == "[object Number]" || + t == "[object String]" + ) { return false; - // HTMLElement, SVGElement, XULElement, et al. + // HTMLElement, SVGElement, XULElement, et al. } else if (element.isElement(value)) { return false; - // Array, NodeList, HTMLCollection, et al. + // Array, NodeList, HTMLCollection, et al. } else if (element.isCollection(value)) { if (stack.includes(value)) { return true; @@ -397,7 +414,7 @@ this.sandbox = {}; * functions and DOM elements. */ sandbox.cloneInto = function(obj, sb) { - return Cu.cloneInto(obj, sb, {cloneFunctions: true, wrapReflectors: true}); + return Cu.cloneInto(obj, sb, { cloneFunctions: true, wrapReflectors: true }); }; /** @@ -442,13 +459,16 @@ sandbox.augment = function(sb, adapter) { */ sandbox.create = function(win, principal = null, opts = {}) { let p = principal || win; - opts = Object.assign({ - sameZoneAs: win, - sandboxPrototype: win, - wantComponents: true, - wantXrays: true, - wantGlobalProperties: ["ChromeUtils"], - }, opts); + opts = Object.assign( + { + sameZoneAs: win, + sandboxPrototype: win, + wantComponents: true, + wantXrays: true, + wantGlobalProperties: ["ChromeUtils"], + }, + opts + ); return new Cu.Sandbox(p, opts); }; @@ -472,8 +492,9 @@ sandbox.createMutable = function(win) { }; sandbox.createSystemPrincipal = function(win) { - let principal = Cc["@mozilla.org/systemprincipal;1"] - .createInstance(Ci.nsIPrincipal); + let principal = Cc["@mozilla.org/systemprincipal;1"].createInstance( + Ci.nsIPrincipal + ); return sandbox.create(win, principal); }; diff --git a/testing/marionette/event.js b/testing/marionette/event.js index 7be4295088cd..2143094dc493 100644 --- a/testing/marionette/event.js +++ b/testing/marionette/event.js @@ -5,13 +5,15 @@ /** Provides functionality for creating and sending DOM events. */ this.event = {}; -"use strict"; +("use strict"); /* global content, is */ /* eslint-disable no-restricted-globals */ -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {element} = ChromeUtils.import("chrome://marionette/content/element.js"); +const { element } = ChromeUtils.import( + "chrome://marionette/content/element.js" +); const dblclickTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); @@ -67,8 +69,11 @@ event.DoubleClickTracker = { event.DoubleClickTracker.cancelTimer(); }, startTimer() { - dblclickTimer.initWithCallback(event.DoubleClickTracker.resetClick, - DBLCLICK_INTERVAL, Ci.nsITimer.TYPE_ONE_SHOT); + dblclickTimer.initWithCallback( + event.DoubleClickTracker.resetClick, + DBLCLICK_INTERVAL, + Ci.nsITimer.TYPE_ONE_SHOT + ); }, cancelTimer() { dblclickTimer.cancel(); @@ -127,7 +132,11 @@ event.parseModifiers_ = function(modifiers) { event.synthesizeMouse = function(element, offsetX, offsetY, opts, win) { let rect = element.getBoundingClientRect(); event.synthesizeMouseAtPoint( - rect.left + offsetX, rect.top + offsetY, opts, win); + rect.left + offsetX, + rect.top + offsetY, + opts, + win + ); }; /* @@ -153,11 +162,11 @@ event.synthesizeMouseAtPoint = function(left, top, opts, win) { let button = opts.button || 0; let clickCount = opts.clickCount || 1; let modifiers = event.parseModifiers_(opts); - let pressure = ("pressure" in opts) ? opts.pressure : 0; - let inputSource = ("inputSource" in opts) ? opts.inputSource : - win.MouseEvent.MOZ_SOURCE_MOUSE; + let pressure = "pressure" in opts ? opts.pressure : 0; + let inputSource = + "inputSource" in opts ? opts.inputSource : win.MouseEvent.MOZ_SOURCE_MOUSE; let isDOMEventSynthesized = - ("isSynthesized" in opts) ? opts.isSynthesized : true; + "isSynthesized" in opts ? opts.isSynthesized : true; let isWidgetEventSynthesized; if ("isWidgetEventSynthesized" in opts) { isWidgetEventSynthesized = opts.isWidgetEventSynthesized; @@ -171,47 +180,50 @@ event.synthesizeMouseAtPoint = function(left, top, opts, win) { buttons = domutils.MOUSE_BUTTONS_NOT_SPECIFIED; } - if (("type" in opts) && opts.type) { + if ("type" in opts && opts.type) { domutils.sendMouseEvent( - opts.type, - left, - top, - button, - clickCount, - modifiers, - false, - pressure, - inputSource, - isDOMEventSynthesized, - isWidgetEventSynthesized, - buttons); + opts.type, + left, + top, + button, + clickCount, + modifiers, + false, + pressure, + inputSource, + isDOMEventSynthesized, + isWidgetEventSynthesized, + buttons + ); } else { domutils.sendMouseEvent( - "mousedown", - left, - top, - button, - clickCount, - modifiers, - false, - pressure, - inputSource, - isDOMEventSynthesized, - isWidgetEventSynthesized, - buttons); + "mousedown", + left, + top, + button, + clickCount, + modifiers, + false, + pressure, + inputSource, + isDOMEventSynthesized, + isWidgetEventSynthesized, + buttons + ); domutils.sendMouseEvent( - "mouseup", - left, - top, - button, - clickCount, - modifiers, - false, - pressure, - inputSource, - isDOMEventSynthesized, - isWidgetEventSynthesized, - buttons); + "mouseup", + left, + top, + button, + clickCount, + modifiers, + false, + pressure, + inputSource, + isDOMEventSynthesized, + isWidgetEventSynthesized, + buttons + ); } }; @@ -340,7 +352,7 @@ event.isKeypressFiredKey = function(key, win) { throw new TypeError("Unknown key: " + key); } - // if key generates a character, it must cause a keypress event + // if key generates a character, it must cause a keypress event } else { return true; } @@ -422,8 +434,9 @@ function getTIP_(win, callback) { if (TIPMap.has(win)) { tip = TIPMap.get(win); } else { - tip = Cc["@mozilla.org/text-input-processor;1"] - .createInstance(Ci.nsITextInputProcessor); + tip = Cc["@mozilla.org/text-input-processor;1"].createInstance( + Ci.nsITextInputProcessor + ); TIPMap.set(win, tip); } if (!tip.beginInputTransactionForTests(win, callback)) { @@ -443,19 +456,19 @@ function getKeyboardEvent_(win) { return KeyboardEvent; } catch (ex) {} } - if (typeof content != "undefined" && ("KeyboardEvent" in content)) { + if (typeof content != "undefined" && "KeyboardEvent" in content) { return content.KeyboardEvent; } return win.KeyboardEvent; } function createKeyboardEventDictionary_(key, keyEvent, win) { - let result = {dictionary: null, flags: 0}; - let keyCodeIsDefined = "keyCode" in keyEvent && - keyEvent.keyCode != undefined; + let result = { dictionary: null, flags: 0 }; + let keyCodeIsDefined = "keyCode" in keyEvent && keyEvent.keyCode != undefined; let keyCode = - (keyCodeIsDefined && keyEvent.keyCode >= 0 && keyEvent.keyCode <= 255) ? - keyEvent.keyCode : 0; + keyCodeIsDefined && keyEvent.keyCode >= 0 && keyEvent.keyCode <= 255 + ? keyEvent.keyCode + : 0; let keyName = "Unidentified"; let printable = false; @@ -516,22 +529,25 @@ function emulateToActivateModifiers_(TIP, keyEvent, win) { let modifiers = { normal: [ - {key: "Alt", attr: "altKey"}, - {key: "AltGraph", attr: "altGraphKey"}, - {key: "Control", attr: "ctrlKey"}, - {key: "Fn", attr: "fnKey"}, - {key: "Meta", attr: "metaKey"}, - {key: "OS", attr: "osKey"}, - {key: "Shift", attr: "shiftKey"}, - {key: "Symbol", attr: "symbolKey"}, - {key: Services.appinfo.OS === "Darwin" ? "Meta" : "Control", attr: "accelKey"}, + { key: "Alt", attr: "altKey" }, + { key: "AltGraph", attr: "altGraphKey" }, + { key: "Control", attr: "ctrlKey" }, + { key: "Fn", attr: "fnKey" }, + { key: "Meta", attr: "metaKey" }, + { key: "OS", attr: "osKey" }, + { key: "Shift", attr: "shiftKey" }, + { key: "Symbol", attr: "symbolKey" }, + { + key: Services.appinfo.OS === "Darwin" ? "Meta" : "Control", + attr: "accelKey", + }, ], lockable: [ - {key: "CapsLock", attr: "capsLockKey"}, - {key: "FnLock", attr: "fnLockKey"}, - {key: "NumLock", attr: "numLockKey"}, - {key: "ScrollLock", attr: "scrollLockKey"}, - {key: "SymbolLock", attr: "symbolLockKey"}, + { key: "CapsLock", attr: "capsLockKey" }, + { key: "FnLock", attr: "fnLockKey" }, + { key: "NumLock", attr: "numLockKey" }, + { key: "ScrollLock", attr: "scrollLockKey" }, + { key: "SymbolLock", attr: "symbolLockKey" }, ], }; @@ -542,9 +558,11 @@ function emulateToActivateModifiers_(TIP, keyEvent, win) { if (TIP.getModifierState(modifiers.normal[i].key)) { continue; // already activated. } - let event = new KeyboardEvent("", {key: modifiers.normal[i].key}); - TIP.keydown(event, - TIP.KEY_NON_PRINTABLE_KEY | TIP.KEY_DONT_DISPATCH_MODIFIER_KEY_EVENT); + let event = new KeyboardEvent("", { key: modifiers.normal[i].key }); + TIP.keydown( + event, + TIP.KEY_NON_PRINTABLE_KEY | TIP.KEY_DONT_DISPATCH_MODIFIER_KEY_EVENT + ); modifiers.normal[i].activated = true; } @@ -555,11 +573,15 @@ function emulateToActivateModifiers_(TIP, keyEvent, win) { if (TIP.getModifierState(modifiers.lockable[j].key)) { continue; // already activated. } - let event = new KeyboardEvent("", {key: modifiers.lockable[j].key}); - TIP.keydown(event, - TIP.KEY_NON_PRINTABLE_KEY | TIP.KEY_DONT_DISPATCH_MODIFIER_KEY_EVENT); - TIP.keyup(event, - TIP.KEY_NON_PRINTABLE_KEY | TIP.KEY_DONT_DISPATCH_MODIFIER_KEY_EVENT); + let event = new KeyboardEvent("", { key: modifiers.lockable[j].key }); + TIP.keydown( + event, + TIP.KEY_NON_PRINTABLE_KEY | TIP.KEY_DONT_DISPATCH_MODIFIER_KEY_EVENT + ); + TIP.keyup( + event, + TIP.KEY_NON_PRINTABLE_KEY | TIP.KEY_DONT_DISPATCH_MODIFIER_KEY_EVENT + ); modifiers.lockable[j].activated = true; } @@ -575,9 +597,11 @@ function emulateToInactivateModifiers_(TIP, modifiers, win) { if (!modifiers.normal[i].activated) { continue; } - let event = new KeyboardEvent("", {key: modifiers.normal[i].key}); - TIP.keyup(event, - TIP.KEY_NON_PRINTABLE_KEY | TIP.KEY_DONT_DISPATCH_MODIFIER_KEY_EVENT); + let event = new KeyboardEvent("", { key: modifiers.normal[i].key }); + TIP.keyup( + event, + TIP.KEY_NON_PRINTABLE_KEY | TIP.KEY_DONT_DISPATCH_MODIFIER_KEY_EVENT + ); } for (let j = 0; j < modifiers.lockable.length; j++) { if (!modifiers.lockable[j].activated) { @@ -586,11 +610,15 @@ function emulateToInactivateModifiers_(TIP, modifiers, win) { if (!TIP.getModifierState(modifiers.lockable[j].key)) { continue; // who already inactivated this? } - let event = new KeyboardEvent("", {key: modifiers.lockable[j].key}); - TIP.keydown(event, - TIP.KEY_NON_PRINTABLE_KEY | TIP.KEY_DONT_DISPATCH_MODIFIER_KEY_EVENT); - TIP.keyup(event, - TIP.KEY_NON_PRINTABLE_KEY | TIP.KEY_DONT_DISPATCH_MODIFIER_KEY_EVENT); + let event = new KeyboardEvent("", { key: modifiers.lockable[j].key }); + TIP.keydown( + event, + TIP.KEY_NON_PRINTABLE_KEY | TIP.KEY_DONT_DISPATCH_MODIFIER_KEY_EVENT + ); + TIP.keyup( + event, + TIP.KEY_NON_PRINTABLE_KEY | TIP.KEY_DONT_DISPATCH_MODIFIER_KEY_EVENT + ); } } @@ -778,9 +806,13 @@ function expectEvent_(expectedTarget, expectedEvent, testName) { * be removed. */ function checkExpectedEvent_( - expectedTarget, expectedEvent, eventHandler, testName) { + expectedTarget, + expectedEvent, + eventHandler, + testName +) { if (eventHandler) { - let expectEvent = (expectedEvent.charAt(0) != "!"); + let expectEvent = expectedEvent.charAt(0) != "!"; let type = expectEvent; if (!type) { type = expectedEvent.substring(1); @@ -824,25 +856,25 @@ function checkExpectedEvent_( * Window object. */ event.synthesizeMouseExpectEvent = function( - target, offsetX, offsetY, ev, expectedTarget, expectedEvent, - testName, win) { - let eventHandler = expectEvent_( - expectedTarget, - expectedEvent, - testName); + target, + offsetX, + offsetY, + ev, + expectedTarget, + expectedEvent, + testName, + win +) { + let eventHandler = expectEvent_(expectedTarget, expectedEvent, testName); event.synthesizeMouse(target, offsetX, offsetY, ev, win); - checkExpectedEvent_( - expectedTarget, - expectedEvent, - eventHandler, - testName); + checkExpectedEvent_(expectedTarget, expectedEvent, eventHandler, testName); }; const MODIFIER_KEYCODES_LOOKUP = { - "VK_SHIFT": "shiftKey", - "VK_CONTROL": "ctrlKey", - "VK_ALT": "altKey", - "VK_META": "metaKey", + VK_SHIFT: "shiftKey", + VK_CONTROL: "ctrlKey", + VK_ALT: "altKey", + VK_META: "metaKey", }; const VIRTUAL_KEYCODE_LOOKUP = { @@ -858,7 +890,7 @@ const VIRTUAL_KEYCODE_LOOKUP = { "\uE00A": "VK_ALT", "\uE00B": "VK_PAUSE", "\uE00C": "VK_ESCAPE", - "\uE00D": "VK_SPACE", // printable + "\uE00D": "VK_SPACE", // printable "\uE00E": "VK_PAGE_UP", "\uE00F": "VK_PAGE_DOWN", "\uE010": "VK_END", @@ -996,7 +1028,7 @@ function isPrintable(c, win) { KeyboardEvent.DOM_VK_PLAY, KeyboardEvent.DOM_VK_RETURN, ]; - return !(NON_PRINT_KEYS.includes(c)); + return !NON_PRINT_KEYS.includes(c); } event.sendKeyDown = function(keyToSend, modifiers, win) { diff --git a/testing/marionette/format.js b/testing/marionette/format.js index caf844eb8fd6..80c339d81b36 100644 --- a/testing/marionette/format.js +++ b/testing/marionette/format.js @@ -4,10 +4,15 @@ "use strict"; -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); -const {Log} = ChromeUtils.import("chrome://marionette/content/log.js"); -const {MarionettePrefs} = ChromeUtils.import("chrome://marionette/content/prefs.js", null); +const { Log } = ChromeUtils.import("chrome://marionette/content/log.js"); +const { MarionettePrefs } = ChromeUtils.import( + "chrome://marionette/content/prefs.js", + null +); XPCOMUtils.defineLazyGetter(this, "log", Log.get); @@ -36,8 +41,12 @@ const MAX_STRING_LENGTH = 250; function pprint(ss, ...values) { function pretty(val) { let proto = Object.prototype.toString.call(val); - if (typeof val == "object" && val !== null && - "nodeType" in val && val.nodeType === ELEMENT_NODE) { + if ( + typeof val == "object" && + val !== null && + "nodeType" in val && + val.nodeType === ELEMENT_NODE + ) { return prettyElement(val); } else if (["[object Window]", "[object ChromeWindow]"].includes(proto)) { return prettyWindowGlobal(val); @@ -138,8 +147,8 @@ function truncate(strings, ...values) { case "[object String]": if (MarionettePrefs.truncateLog) { if (obj.length > MAX_STRING_LENGTH) { - let s1 = obj.substring(0, (MAX_STRING_LENGTH / 2)); - let s2 = obj.substring(obj.length - (MAX_STRING_LENGTH / 2)); + let s1 = obj.substring(0, MAX_STRING_LENGTH / 2); + let s2 = obj.substring(obj.length - MAX_STRING_LENGTH / 2); return `${s1} ... ${s2}`; } } @@ -150,8 +159,10 @@ function truncate(strings, ...values) { // arbitrary object default: - if (Object.getOwnPropertyNames(obj).includes("toString") && - typeof obj.toString == "function") { + if ( + Object.getOwnPropertyNames(obj).includes("toString") && + typeof obj.toString == "function" + ) { return walk(obj.toString()); } diff --git a/testing/marionette/interaction.js b/testing/marionette/interaction.js index df74e34688f4..70b7392a49f3 100644 --- a/testing/marionette/interaction.js +++ b/testing/marionette/interaction.js @@ -5,21 +5,31 @@ "use strict"; /* eslint-disable no-restricted-globals */ -const {Preferences} = ChromeUtils.import("resource://gre/modules/Preferences.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { Preferences } = ChromeUtils.import( + "resource://gre/modules/Preferences.jsm" +); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); -const {accessibility} = ChromeUtils.import("chrome://marionette/content/accessibility.js"); -const {atom} = ChromeUtils.import("chrome://marionette/content/atom.js"); -const {element} = ChromeUtils.import("chrome://marionette/content/element.js"); +const { accessibility } = ChromeUtils.import( + "chrome://marionette/content/accessibility.js" +); +const { atom } = ChromeUtils.import("chrome://marionette/content/atom.js"); +const { element } = ChromeUtils.import( + "chrome://marionette/content/element.js" +); const { ElementClickInterceptedError, ElementNotInteractableError, InvalidArgumentError, InvalidElementStateError, } = ChromeUtils.import("chrome://marionette/content/error.js"); -const {event} = ChromeUtils.import("chrome://marionette/content/event.js"); -const {pprint} = ChromeUtils.import("chrome://marionette/content/format.js"); -const {TimedPromise} = ChromeUtils.import("chrome://marionette/content/sync.js"); +const { event } = ChromeUtils.import("chrome://marionette/content/event.js"); +const { pprint } = ChromeUtils.import("chrome://marionette/content/format.js"); +const { TimedPromise } = ChromeUtils.import( + "chrome://marionette/content/sync.js" +); XPCOMUtils.defineLazyGlobalGetters(this, ["File"]); @@ -62,11 +72,7 @@ const DISABLED_ATTRIBUTE_SUPPORTED_XUL = new Set([ * Common form controls that user can change the value property * interactively. */ -const COMMON_FORM_CONTROLS = new Set([ - "input", - "textarea", - "select", -]); +const COMMON_FORM_CONTROLS = new Set(["input", "textarea", "select"]); /** * Input elements that do not fire input and change @@ -123,7 +129,10 @@ this.interaction = {}; * If el is not enabled. */ interaction.clickElement = async function( - el, strict = false, specCompat = false) { + el, + strict = false, + specCompat = false +) { const a11y = accessibility.get(strict); if (element.isXULElement(el)) { await chromeClick(el, a11y); @@ -139,8 +148,7 @@ async function webdriverClickElement(el, a11y) { // step 3 if (el.localName == "input" && el.type == "file") { - throw new InvalidArgumentError( - "Cannot click elements"); + throw new InvalidArgumentError("Cannot click elements"); } let containerEl = element.getContainer(el); @@ -158,7 +166,8 @@ async function webdriverClickElement(el, a11y) { // there is no point in checking if it is pointer-interactable if (!element.isInView(containerEl)) { throw new ElementNotInteractableError( - pprint`Element ${el} could not be scrolled into view`); + pprint`Element ${el} could not be scrolled into view` + ); } // step 7 @@ -209,7 +218,7 @@ async function chromeClick(el, a11y) { async function seleniumClickElement(el, a11y) { let win = getWindow(el); - let visibilityCheckEl = el; + let visibilityCheckEl = el; if (el.localName == "option") { visibilityCheckEl = element.getContainer(el); } @@ -319,7 +328,8 @@ interaction.clearElement = function(el) { } if (!element.isEditable(el)) { throw new InvalidElementStateError( - pprint`Unable to clear element that cannot be edited: ${el}`); + pprint`Unable to clear element that cannot be edited: ${el}` + ); } if (!element.isInView(el)) { @@ -327,7 +337,8 @@ interaction.clearElement = function(el) { } if (!element.isInView(el)) { throw new ElementNotInteractableError( - pprint`Element ${el} could not be scrolled into view`); + pprint`Element ${el} could not be scrolled into view` + ); } if (element.isEditingHost(el)) { @@ -349,7 +360,9 @@ function clearContentEditableElement(el) { function clearResettableElement(el) { if (!element.isMutableFormControl(el)) { - throw new InvalidElementStateError(pprint`Not an editable form control: ${el}`); + throw new InvalidElementStateError( + pprint`Not an editable form control: ${el}` + ); } let isEmpty; @@ -400,8 +413,8 @@ interaction.flushEventLoop = async function(el) { } }; - win.addEventListener("unload", unloadEv, {mozSystemGroup: true}); - el.addEventListener("click", clickEv, {mozSystemGroup: true}); + win.addEventListener("unload", unloadEv, { mozSystemGroup: true }); + el.addEventListener("click", clickEv, { mozSystemGroup: true }); }; let removeListeners = () => { // only one event fires @@ -409,8 +422,9 @@ interaction.flushEventLoop = async function(el) { el.removeEventListener("click", clickEv); }; - return new TimedPromise(spinEventLoop, {timeout: 500, throws: null}) - .then(removeListeners); + return new TimedPromise(spinEventLoop, { timeout: 500, throws: null }).then( + removeListeners + ); }; /** @@ -489,7 +503,8 @@ interaction.uploadFiles = async function(el, paths) { files = Array.prototype.slice.call(el.files); } else if (paths.length > 1) { throw new InvalidArgumentError( - pprint`Element ${el} doesn't accept multiple files`); + pprint`Element ${el} doesn't accept multiple files` + ); } for (let path of paths) { @@ -547,24 +562,35 @@ interaction.setFormControlValue = function(el, value) { * @param {boolean=} webdriverClick * Use WebDriver specification compatible interactability definition. */ -interaction.sendKeysToElement = async function(el, value, - { - strictFileInteractability = false, - accessibilityChecks = false, - webdriverClick = false, - } = {}) { +interaction.sendKeysToElement = async function( + el, + value, + { + strictFileInteractability = false, + accessibilityChecks = false, + webdriverClick = false, + } = {} +) { const a11y = accessibility.get(accessibilityChecks); if (webdriverClick) { await webdriverSendKeysToElement( - el, value, a11y, strictFileInteractability); + el, + value, + a11y, + strictFileInteractability + ); } else { await legacySendKeysToElement(el, value, a11y); } }; -async function webdriverSendKeysToElement(el, value, - a11y, strictFileInteractability) { +async function webdriverSendKeysToElement( + el, + value, + a11y, + strictFileInteractability +) { const win = getWindow(el); if (el.type != "file" || strictFileInteractability) { @@ -573,7 +599,8 @@ async function webdriverSendKeysToElement(el, value, // TODO: Wait for element to be keyboard-interactible if (!interaction.isKeyboardInteractable(containerEl)) { throw new ElementNotInteractableError( - pprint`Element ${el} is not reachable by keyboard`); + pprint`Element ${el} is not reachable by keyboard` + ); } } @@ -589,8 +616,10 @@ async function webdriverSendKeysToElement(el, value, event.input(el); event.change(el); - } else if ((el.type == "date" || el.type == "time") && - Preferences.get("dom.forms.datetime")) { + } else if ( + (el.type == "date" || el.type == "time") && + Preferences.get("dom.forms.datetime") + ) { interaction.setFormControlValue(el, value); } else { event.sendKeysToElement(value, el, win); @@ -606,11 +635,13 @@ async function legacySendKeysToElement(el, value, a11y) { event.input(el); event.change(el); - } else if ((el.type == "date" || el.type == "time") && - Preferences.get("dom.forms.datetime")) { + } else if ( + (el.type == "date" || el.type == "time") && + Preferences.get("dom.forms.datetime") + ) { interaction.setFormControlValue(el, value); } else { - let visibilityCheckEl = el; + let visibilityCheckEl = el; if (el.localName == "option") { visibilityCheckEl = element.getContainer(el); } @@ -666,14 +697,19 @@ interaction.isElementEnabled = function(el, strict = false) { if (element.isXULElement(el)) { // check if XUL element supports disabled attribute if (DISABLED_ATTRIBUTE_SUPPORTED_XUL.has(el.tagName.toUpperCase())) { - if (el.hasAttribute("disabled") && el.getAttribute("disabled") === "true") { + if ( + el.hasAttribute("disabled") && + el.getAttribute("disabled") === "true" + ) { enabled = false; } } - } else if (["application/xml", "text/xml"].includes(win.document.contentType)) { + } else if ( + ["application/xml", "text/xml"].includes(win.document.contentType) + ) { enabled = false; } else { - enabled = atom.isElementEnabled(el, {frame: win}); + enabled = atom.isElementEnabled(el, { frame: win }); } let a11y = accessibility.get(strict); diff --git a/testing/marionette/l10n.js b/testing/marionette/l10n.js index f6d3243e402b..ebbe071f483b 100644 --- a/testing/marionette/l10n.js +++ b/testing/marionette/l10n.js @@ -15,14 +15,17 @@ * content retrieved. */ -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); XPCOMUtils.defineLazyGlobalGetters(this, ["DOMParser"]); XPCOMUtils.defineLazyGetter(this, "domParser", () => new DOMParser()); -const {NoSuchElementError} = - ChromeUtils.import("chrome://marionette/content/error.js"); +const { NoSuchElementError } = ChromeUtils.import( + "chrome://marionette/content/error.js" +); this.EXPORTED_SYMBOLS = ["l10n"]; @@ -91,8 +94,7 @@ l10n.localizeProperty = function(urls, id) { } if (property === null) { - throw new NoSuchElementError( - `Property with ID '${id}' hasn't been found`); + throw new NoSuchElementError(`Property with ID '${id}' hasn't been found`); } return property; diff --git a/testing/marionette/listener.js b/testing/marionette/listener.js index 50da724acc15..c210e3a6ea85 100644 --- a/testing/marionette/listener.js +++ b/testing/marionette/listener.js @@ -10,21 +10,25 @@ const winUtil = content.windowUtils; -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); -const {accessibility} = ChromeUtils.import("chrome://marionette/content/accessibility.js"); -const {action} = ChromeUtils.import("chrome://marionette/content/action.js"); -const {atom} = ChromeUtils.import("chrome://marionette/content/atom.js"); -const { - Capabilities, - PageLoadStrategy, -} = ChromeUtils.import("chrome://marionette/content/capabilities.js"); -const {capture} = ChromeUtils.import("chrome://marionette/content/capture.js"); -const { - element, - WebElement, -} = ChromeUtils.import("chrome://marionette/content/element.js"); +const { accessibility } = ChromeUtils.import( + "chrome://marionette/content/accessibility.js" +); +const { action } = ChromeUtils.import("chrome://marionette/content/action.js"); +const { atom } = ChromeUtils.import("chrome://marionette/content/atom.js"); +const { Capabilities, PageLoadStrategy } = ChromeUtils.import( + "chrome://marionette/content/capabilities.js" +); +const { capture } = ChromeUtils.import( + "chrome://marionette/content/capture.js" +); +const { element, WebElement } = ChromeUtils.import( + "chrome://marionette/content/element.js" +); const { ElementNotInteractableError, InsecureCertificateError, @@ -35,21 +39,35 @@ const { TimeoutError, UnknownError, } = ChromeUtils.import("chrome://marionette/content/error.js"); -const {Sandboxes, evaluate, sandbox} = ChromeUtils.import("chrome://marionette/content/evaluate.js"); -const {event} = ChromeUtils.import("chrome://marionette/content/event.js"); -const {ContentEventObserverService} = ChromeUtils.import("chrome://marionette/content/dom.js"); -const {pprint, truncate} = ChromeUtils.import("chrome://marionette/content/format.js"); -const {interaction} = ChromeUtils.import("chrome://marionette/content/interaction.js"); -const {legacyaction} = ChromeUtils.import("chrome://marionette/content/legacyaction.js"); -const {Log} = ChromeUtils.import("chrome://marionette/content/log.js"); -const {navigate} = ChromeUtils.import("chrome://marionette/content/navigate.js"); -const {proxy} = ChromeUtils.import("chrome://marionette/content/proxy.js"); +const { Sandboxes, evaluate, sandbox } = ChromeUtils.import( + "chrome://marionette/content/evaluate.js" +); +const { event } = ChromeUtils.import("chrome://marionette/content/event.js"); +const { ContentEventObserverService } = ChromeUtils.import( + "chrome://marionette/content/dom.js" +); +const { pprint, truncate } = ChromeUtils.import( + "chrome://marionette/content/format.js" +); +const { interaction } = ChromeUtils.import( + "chrome://marionette/content/interaction.js" +); +const { legacyaction } = ChromeUtils.import( + "chrome://marionette/content/legacyaction.js" +); +const { Log } = ChromeUtils.import("chrome://marionette/content/log.js"); +const { navigate } = ChromeUtils.import( + "chrome://marionette/content/navigate.js" +); +const { proxy } = ChromeUtils.import("chrome://marionette/content/proxy.js"); -XPCOMUtils.defineLazyGetter(this, "logger", () => Log.getWithPrefix(outerWindowID)); +XPCOMUtils.defineLazyGetter(this, "logger", () => + Log.getWithPrefix(outerWindowID) +); XPCOMUtils.defineLazyGlobalGetters(this, ["URL"]); -let {outerWindowID} = winUtil; -let curContainer = {frame: content, shadowRoot: null}; +let { outerWindowID } = winUtil; +let curContainer = { frame: content, shadowRoot: null }; // Listen for click event to indicate one click has happened, so actions // code can send dblclick event @@ -86,7 +104,9 @@ let multiLast = {}; const sandboxes = new Sandboxes(() => curContainer.frame); const eventObservers = new ContentEventObserverService( - content, sendAsyncMessage.bind(this)); + content, + sendAsyncMessage.bind(this) +); /** * The load listener singleton helps to keep track of active page load @@ -124,8 +144,7 @@ const loadListener = { this.seenBeforeUnload = false; this.seenUnload = false; - this.timerPageLoad = Cc["@mozilla.org/timer;1"] - .createInstance(Ci.nsITimer); + this.timerPageLoad = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); this.timerPageUnload = null; // In case the frame script has been moved to a differnt process, @@ -165,7 +184,10 @@ const loadListener = { } this.timerPageLoad.initWithCallback( - this, timeout, Ci.nsITimer.TYPE_ONE_SHOT); + this, + timeout, + Ci.nsITimer.TYPE_ONE_SHOT + ); }, /** @@ -202,8 +224,10 @@ const loadListener = { handleEvent(event) { // Only care about events from the currently selected browsing context, // whereby some of those do not bubble up to the window. - if (event.target != curContainer.frame && - event.target != curContainer.frame.document) { + if ( + event.target != curContainer.frame && + event.target != curContainer.frame.document + ) { return; } @@ -239,8 +263,10 @@ const loadListener = { case "DOMContentLoaded": case "pageshow": - this.handleReadyState(event.target.readyState, - event.target.documentURI); + this.handleReadyState( + event.target.readyState, + event.target.documentURI + ); break; } }, @@ -270,19 +296,23 @@ const loadListener = { finished = true; } else if (/about:.*(error)\?/.exec(documentURI)) { this.stop(); - sendError(new UnknownError(`Reached error page: ${documentURI}`), - this.commandID); + sendError( + new UnknownError(`Reached error page: ${documentURI}`), + this.commandID + ); finished = true; - // Return early with a page load strategy of eager, and also - // special-case about:blocked pages which should be treated as - // non-error pages but do not raise a pageshow event. about:blank - // is also treaded specifically here, because it gets temporary - // loaded for new content processes, and we only want to rely on - // complete loads for it. - } else if ((capabilities.get("pageLoadStrategy") === PageLoadStrategy.Eager && + // Return early with a page load strategy of eager, and also + // special-case about:blocked pages which should be treated as + // non-error pages but do not raise a pageshow event. about:blank + // is also treaded specifically here, because it gets temporary + // loaded for new content processes, and we only want to rely on + // complete loads for it. + } else if ( + (capabilities.get("pageLoadStrategy") === PageLoadStrategy.Eager && documentURI != "about:blank") || - /about:blocked\?/.exec(documentURI)) { + /about:blocked\?/.exec(documentURI) + ) { this.stop(); sendOk(this.commandID); finished = true; @@ -318,13 +348,18 @@ const loadListener = { if (this.seenBeforeUnload) { this.seenBeforeUnload = null; this.timerPageUnload.initWithCallback( - this, 5000, Ci.nsITimer.TYPE_ONE_SHOT); + this, + 5000, + Ci.nsITimer.TYPE_ONE_SHOT + ); - // If no page unload has been detected, ensure to properly stop - // the load listener, and return from the currently active command. + // If no page unload has been detected, ensure to properly stop + // the load listener, and return from the currently active command. } else if (!this.seenUnload) { - logger.debug("Canceled page load listener because no navigation " + - "has been detected"); + logger.debug( + "Canceled page load listener because no navigation " + + "has been detected" + ); this.stop(); sendOk(this.commandID); } @@ -333,8 +368,9 @@ const loadListener = { case this.timerPageLoad: this.stop(); sendError( - new TimeoutError(`Timeout loading page after ${this.timeout}ms`), - this.commandID); + new TimeoutError(`Timeout loading page after ${this.timeout}ms`), + this.commandID + ); break; } }, @@ -392,11 +428,17 @@ const loadListener = { * @param {string=} url * Optional URL, which is used to check if a page load is expected. */ - navigate(trigger, commandID, timeout, loadEventExpected = true, - useUnloadTimer = false) { + navigate( + trigger, + commandID, + timeout, + loadEventExpected = true, + useUnloadTimer = false + ) { // Only wait if the page load strategy is not `none` - loadEventExpected = loadEventExpected && - (capabilities.get("pageLoadStrategy") !== PageLoadStrategy.None); + loadEventExpected = + loadEventExpected && + capabilities.get("pageLoadStrategy") !== PageLoadStrategy.None; if (loadEventExpected) { let startTime = new Date().getTime(); @@ -405,26 +447,32 @@ const loadListener = { return (async () => { await trigger(); - })().then(() => { - if (!loadEventExpected) { - sendOk(commandID); - return; - } + })() + .then(() => { + if (!loadEventExpected) { + sendOk(commandID); + return; + } - // If requested setup a timer to detect a possible page load - if (useUnloadTimer) { - this.timerPageUnload = Cc["@mozilla.org/timer;1"] - .createInstance(Ci.nsITimer); - this.timerPageUnload.initWithCallback( - this, 200, Ci.nsITimer.TYPE_ONE_SHOT); - } - }).catch(err => { - if (loadEventExpected) { - this.stop(); - } + // If requested setup a timer to detect a possible page load + if (useUnloadTimer) { + this.timerPageUnload = Cc["@mozilla.org/timer;1"].createInstance( + Ci.nsITimer + ); + this.timerPageUnload.initWithCallback( + this, + 200, + Ci.nsITimer.TYPE_ONE_SHOT + ); + } + }) + .catch(err => { + if (loadEventExpected) { + this.stop(); + } - sendError(err, commandID); - }); + sendError(err, commandID); + }); }, }; @@ -445,7 +493,7 @@ function registerSelf() { action.inputStateMap = new Map(); action.inputsToCancel = []; - let reply = sendSyncMessage("Marionette:Register", {outerWindowID}); + let reply = sendSyncMessage("Marionette:Register", { outerWindowID }); if (reply.length == 0) { logger.error("No reply from Marionette:Register"); return; @@ -454,7 +502,7 @@ function registerSelf() { if (reply[0].outerWindowID === outerWindowID) { logger.trace("Frame script registered"); startListeners(); - sendAsyncMessage("Marionette:ListenersAttached", {outerWindowID}); + sendAsyncMessage("Marionette:ListenersAttached", { outerWindowID }); } } @@ -484,8 +532,9 @@ function dispatch(fn) { resolve(rv); }); - req.then(rv => sendResponse(rv, id), err => sendError(err, id)) - .catch(err => sendError(err, id)); + req + .then(rv => sendResponse(rv, id), err => sendError(err, id)) + .catch(err => sendError(err, id)); }; } @@ -522,7 +571,10 @@ function startListeners() { addMessageListener("Marionette:clickElement", clickElement); addMessageListener("Marionette:Deregister", deregister); addMessageListener("Marionette:DOM:AddEventListener", domAddEventListener); - addMessageListener("Marionette:DOM:RemoveEventListener", domRemoveEventListener); + addMessageListener( + "Marionette:DOM:RemoveEventListener", + domRemoveEventListener + ); addMessageListener("Marionette:execute", executeFn); addMessageListener("Marionette:executeInSandbox", executeInSandboxFn); addMessageListener("Marionette:findElementContent", findElementContentFn); @@ -533,7 +585,10 @@ function startListeners() { addMessageListener("Marionette:getElementRect", getElementRectFn); addMessageListener("Marionette:getElementTagName", getElementTagNameFn); addMessageListener("Marionette:getElementText", getElementTextFn); - addMessageListener("Marionette:getElementValueOfCssProperty", getElementValueOfCssPropertyFn); + addMessageListener( + "Marionette:getElementValueOfCssProperty", + getElementValueOfCssPropertyFn + ); addMessageListener("Marionette:get", get); addMessageListener("Marionette:getPageSource", getPageSourceFn); addMessageListener("Marionette:goBack", goBack); @@ -565,14 +620,23 @@ function deregister() { removeMessageListener("Marionette:execute", executeFn); removeMessageListener("Marionette:executeInSandbox", executeInSandboxFn); removeMessageListener("Marionette:findElementContent", findElementContentFn); - removeMessageListener("Marionette:findElementsContent", findElementsContentFn); + removeMessageListener( + "Marionette:findElementsContent", + findElementsContentFn + ); removeMessageListener("Marionette:getActiveElement", getActiveElementFn); - removeMessageListener("Marionette:getElementAttribute", getElementAttributeFn); + removeMessageListener( + "Marionette:getElementAttribute", + getElementAttributeFn + ); removeMessageListener("Marionette:getElementProperty", getElementPropertyFn); removeMessageListener("Marionette:getElementRect", getElementRectFn); removeMessageListener("Marionette:getElementTagName", getElementTagNameFn); removeMessageListener("Marionette:getElementText", getElementTextFn); - removeMessageListener("Marionette:getElementValueOfCssProperty", getElementValueOfCssPropertyFn); + removeMessageListener( + "Marionette:getElementValueOfCssProperty", + getElementValueOfCssPropertyFn + ); removeMessageListener("Marionette:get", get); removeMessageListener("Marionette:getPageSource", getPageSourceFn); removeMessageListener("Marionette:goBack", goBack); @@ -597,7 +661,7 @@ function deregister() { function deleteSession() { seenEls.clear(); // reset container frame to the top-most frame - curContainer = {frame: content, shadowRoot: null}; + curContainer = { frame: content, shadowRoot: null }; curContainer.frame.focus(); legacyactions.touchIds = {}; if (action.inputStateMap !== undefined) { @@ -670,11 +734,13 @@ async function executeInSandbox(script, args, opts) { } function emitTouchEvent(type, touch) { - logger.info(`Emitting Touch event of type ${type} ` + + logger.info( + `Emitting Touch event of type ${type} ` + `to element with id: ${touch.target.id} ` + `and tag name: ${touch.target.tagName} ` + `at coordinates (${touch.clientX}), ` + - `${touch.clientY}) relative to the viewport`); + `${touch.clientY}) relative to the viewport` + ); const win = curContainer.frame; let docShell = win.docShell; @@ -699,15 +765,16 @@ function emitTouchEvent(type, touch) { // we get here if we're not in asyncPacZoomEnabled land, or if we're // the main process win.windowUtils.sendTouchEvent( - type, - [touch.identifier], - [touch.clientX], - [touch.clientY], - [touch.radiusX], - [touch.radiusY], - [touch.rotationAngle], - [touch.force], - 0); + type, + [touch.identifier], + [touch.clientX], + [touch.clientY], + [touch.radiusX], + [touch.radiusY], + [touch.rotationAngle], + [touch.force], + 0 + ); } /** @@ -718,7 +785,8 @@ async function singleTap(el, corx, cory) { let visible = element.isVisible(el, corx, cory); if (!visible) { throw new ElementNotInteractableError( - "Element is not currently visible and may not be manipulated"); + "Element is not currently visible and may not be manipulated" + ); } let a11y = accessibility.get(capabilities.get("moz:accessibilityChecks")); @@ -745,18 +813,25 @@ async function singleTap(el, corx, cory) { function createATouch(el, corx, cory, touchId) { let doc = el.ownerDocument; let win = doc.defaultView; - let [clientX, clientY, pageX, pageY, screenX, screenY] = - legacyactions.getCoordinateInfo(el, corx, cory); + let [ + clientX, + clientY, + pageX, + pageY, + screenX, + screenY, + ] = legacyactions.getCoordinateInfo(el, corx, cory); let atouch = doc.createTouch( - win, - el, - touchId, - pageX, - pageY, - screenX, - screenY, - clientX, - clientY); + win, + el, + touchId, + pageX, + pageY, + screenX, + screenY, + clientX, + clientY + ); return atouch; } @@ -769,8 +844,10 @@ function createATouch(el, corx, cory, touchId) { */ async function performActions(msg) { let chain = action.Chain.fromJSON(msg.actions); - await action.dispatch(chain, curContainer.frame, - !capabilities.get("moz:useNonSpecCompliantPointerOrigin"), + await action.dispatch( + chain, + curContainer.frame, + !capabilities.get("moz:useNonSpecCompliantPointerOrigin") ); } @@ -782,7 +859,10 @@ async function performActions(msg) { */ async function releaseActions() { await action.dispatchTickActions( - action.inputsToCancel.reverse(), 0, curContainer.frame); + action.inputsToCancel.reverse(), + 0, + curContainer.frame + ); action.inputsToCancel.length = 0; action.inputStateMap.clear(); @@ -798,11 +878,12 @@ function actionChain(chain, touchId) { touchProvider.emitTouchEvent = emitTouchEvent; return legacyactions.dispatchActions( - chain, - touchId, - curContainer, - seenEls, - touchProvider); + chain, + touchId, + curContainer, + seenEls, + touchProvider + ); } function emitMultiEvents(type, touch, touches) { @@ -810,27 +891,37 @@ function emitMultiEvents(type, touch, touches) { let doc = target.ownerDocument; let win = doc.defaultView; // touches that are in the same document - let documentTouches = doc.createTouchList(touches.filter(function(t) { - return ((t.target.ownerDocument === doc) && (type != "touchcancel")); - })); + let documentTouches = doc.createTouchList( + touches.filter(function(t) { + return t.target.ownerDocument === doc && type != "touchcancel"; + }) + ); // touches on the same target - let targetTouches = doc.createTouchList(touches.filter(function(t) { - return ((t.target === target) && - ((type != "touchcancel") || (type != "touchend"))); - })); + let targetTouches = doc.createTouchList( + touches.filter(function(t) { + return ( + t.target === target && (type != "touchcancel" || type != "touchend") + ); + }) + ); // Create changed touches let changedTouches = doc.createTouchList(touch); // Create the event object let event = doc.createEvent("TouchEvent"); - event.initTouchEvent(type, - true, - true, - win, - 0, - false, false, false, false, - documentTouches, - targetTouches, - changedTouches); + event.initTouchEvent( + type, + true, + true, + win, + 0, + false, + false, + false, + false, + documentTouches, + targetTouches, + changedTouches + ); target.dispatchEvent(event); } @@ -909,15 +1000,16 @@ function setDispatch(batches, touches, batchIndex = 0) { let screenX = clientX + win.mozInnerScreenX; let screenY = clientY + win.mozInnerScreenY; touch = doc.createTouch( - win, - el, - touchId, - pageX, - pageY, - screenX, - screenY, - clientX, - clientY); + win, + el, + touchId, + pageX, + pageY, + screenX, + screenY, + clientX, + clientY + ); touches[touchIndex] = touch; multiLast[touchId] = touch; emitMultiEvents("touchmove", touch, touches); @@ -936,9 +1028,13 @@ function setDispatch(batches, touches, batchIndex = 0) { if (maxTime != 0) { let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); - timer.initWithCallback(function() { - setDispatch(batches, touches, batchIndex); - }, maxTime, Ci.nsITimer.TYPE_ONE_SHOT); + timer.initWithCallback( + function() { + setDispatch(batches, touches, batchIndex); + }, + maxTime, + Ci.nsITimer.TYPE_ONE_SHOT + ); } else { setDispatch(batches, touches, batchIndex); } @@ -1003,9 +1099,12 @@ function cancelRequest() { * Unix timestap when the navitation request got triggered. */ function waitForPageLoaded(msg) { - let {commandID, pageTimeout, startTime} = msg.json; + let { commandID, pageTimeout, startTime } = msg.json; loadListener.waitForLoadAfterFramescriptReload( - commandID, pageTimeout, startTime); + commandID, + pageTimeout, + startTime + ); } /** @@ -1015,14 +1114,16 @@ function waitForPageLoaded(msg) { * (in chrome space). */ function get(msg) { - let {commandID, pageTimeout, url, loadEventExpected = null} = msg.json; + let { commandID, pageTimeout, url, loadEventExpected = null } = msg.json; try { if (typeof url == "string") { try { if (loadEventExpected === null) { loadEventExpected = navigate.isLoadEventExpected( - curContainer.frame.location, url); + curContainer.frame.location, + url + ); } } catch (e) { let err = new InvalidArgumentError("Malformed URL: " + e.message); @@ -1032,12 +1133,17 @@ function get(msg) { } // We need to move to the top frame before navigating - sendSyncMessage("Marionette:switchedToFrame", {frameValue: null}); + sendSyncMessage("Marionette:switchedToFrame", { frameValue: null }); curContainer.frame = content; - loadListener.navigate(() => { - curContainer.frame.location = url; - }, commandID, pageTimeout, loadEventExpected); + loadListener.navigate( + () => { + curContainer.frame.location = url; + }, + commandID, + pageTimeout, + loadEventExpected + ); } catch (e) { sendError(e, commandID); } @@ -1055,12 +1161,16 @@ function get(msg) { * finished loading. */ function goBack(msg) { - let {commandID, pageTimeout} = msg.json; + let { commandID, pageTimeout } = msg.json; try { - loadListener.navigate(() => { - curContainer.frame.history.back(); - }, commandID, pageTimeout); + loadListener.navigate( + () => { + curContainer.frame.history.back(); + }, + commandID, + pageTimeout + ); } catch (e) { sendError(e, commandID); } @@ -1078,12 +1188,16 @@ function goBack(msg) { * finished loading. */ function goForward(msg) { - let {commandID, pageTimeout} = msg.json; + let { commandID, pageTimeout } = msg.json; try { - loadListener.navigate(() => { - curContainer.frame.history.forward(); - }, commandID, pageTimeout); + loadListener.navigate( + () => { + curContainer.frame.history.forward(); + }, + commandID, + pageTimeout + ); } catch (e) { sendError(e, commandID); } @@ -1101,16 +1215,20 @@ function goForward(msg) { * finished loading. */ function refresh(msg) { - let {commandID, pageTimeout} = msg.json; + let { commandID, pageTimeout } = msg.json; try { // We need to move to the top frame before navigating - sendSyncMessage("Marionette:switchedToFrame", {frameValue: null}); + sendSyncMessage("Marionette:switchedToFrame", { frameValue: null }); curContainer.frame = content; - loadListener.navigate(() => { - curContainer.frame.location.reload(true); - }, commandID, pageTimeout); + loadListener.navigate( + () => { + curContainer.frame.location.reload(true); + }, + commandID, + pageTimeout + ); } catch (e) { sendError(e, commandID); } @@ -1184,7 +1302,7 @@ function getActiveElement() { * finished loading. */ function clickElement(msg) { - let {commandID, webElRef, pageTimeout} = msg.json; + let { commandID, webElRef, pageTimeout } = msg.json; try { let webEl = WebElement.fromJSON(webElRef); @@ -1197,13 +1315,19 @@ function clickElement(msg) { loadEventExpected = false; } - loadListener.navigate(() => { - return interaction.clickElement( + loadListener.navigate( + () => { + return interaction.clickElement( el, capabilities.get("moz:accessibilityChecks"), capabilities.get("moz:webdriverClick") - ); - }, commandID, pageTimeout, loadEventExpected, true); + ); + }, + commandID, + pageTimeout, + loadEventExpected, + true + ); } catch (e) { sendError(e, commandID); } @@ -1252,7 +1376,9 @@ function getElementTagName(el) { */ function isElementDisplayed(el) { return interaction.isElementDisplayed( - el, capabilities.get("moz:accessibilityChecks")); + el, + capabilities.get("moz:accessibilityChecks") + ); } /** @@ -1282,7 +1408,9 @@ function getElementRect(el) { function isElementEnabled(el) { return interaction.isElementEnabled( - el, capabilities.get("moz:accessibilityChecks")); + el, + capabilities.get("moz:accessibilityChecks") + ); } /** @@ -1293,7 +1421,9 @@ function isElementEnabled(el) { */ function isElementSelected(el) { return interaction.isElementSelected( - el, capabilities.get("moz:accessibilityChecks")); + el, + capabilities.get("moz:accessibilityChecks") + ); } async function sendKeysToElement(el, val) { @@ -1348,8 +1478,9 @@ function switchToParentFrame(msg) { curContainer.frame = curContainer.frame.parent; let parentElement = seenEls.add(curContainer.frame); - sendSyncMessage( - "Marionette:switchedToFrame", {frameValue: parentElement.uuid}); + sendSyncMessage("Marionette:switchedToFrame", { + frameValue: parentElement.uuid, + }); sendOk(msg.json.commandID); } @@ -1372,10 +1503,12 @@ function switchToFrame(msg) { msg.json.element = null; } - if ((msg.json.id === null || msg.json.id === undefined) && - (msg.json.element == null)) { + if ( + (msg.json.id === null || msg.json.id === undefined) && + msg.json.element == null + ) { // returning to root frame - sendSyncMessage("Marionette:switchedToFrame", {frameValue: null}); + sendSyncMessage("Marionette:switchedToFrame", { frameValue: null }); curContainer.frame = content; if (msg.json.focus) { @@ -1447,7 +1580,7 @@ function switchToFrame(msg) { } else { // If foundFrame is null at this point then we have the top // level browsing context so should treat it accordingly. - sendSyncMessage("Marionette:switchedToFrame", {frameValue: null}); + sendSyncMessage("Marionette:switchedToFrame", { frameValue: null }); curContainer.frame = content; if (msg.json.focus) { @@ -1481,7 +1614,9 @@ function switchToFrame(msg) { // send a synchronous message to let the server update the currently active // frame element (for getActiveFrame) let frameWebEl = seenEls.add(curContainer.frame.wrappedJSObject); - sendSyncMessage("Marionette:switchedToFrame", {"frameValue": frameWebEl.uuid}); + sendSyncMessage("Marionette:switchedToFrame", { + frameValue: frameWebEl.uuid, + }); curContainer.frame = curContainer.frame.contentWindow; if (msg.json.focus) { @@ -1527,14 +1662,14 @@ function takeScreenshot(format, opts = {}) { let canvas; let highlightEls = highlights - .map(ref => WebElement.fromUUID(ref, "content")) - .map(webEl => seenEls.get(webEl, win)); + .map(ref => WebElement.fromUUID(ref, "content")) + .map(webEl => seenEls.get(webEl, win)); // viewport if (!id && !full) { canvas = capture.viewport(win, highlightEls); - // element or full document element + // element or full document element } else { let el; if (id) { @@ -1592,10 +1727,14 @@ function flushRendering() { } flushWindow(content); - if (anyPendingPaintsGeneratedInDescendants && - !windowUtils.isMozAfterPaintPending) { - logger.error("Descendant frame generated a MozAfterPaint event, " + - "but the root document doesn't have one!"); + if ( + anyPendingPaintsGeneratedInDescendants && + !windowUtils.isMozAfterPaintPending + ) { + logger.error( + "Descendant frame generated a MozAfterPaint event, " + + "but the root document doesn't have one!" + ); } } @@ -1611,12 +1750,16 @@ async function reftestWait(url, remote) { logger.debug(truncate`Waiting for page load of ${url}`); await new Promise(resolve => { let maybeResolve = event => { - if (event.target === curContainer.frame.document && - event.target.location.href === url) { + if ( + event.target === curContainer.frame.document && + event.target.location.href === url + ) { win = curContainer.frame; document = curContainer.frame.document; - reftestWait = document.documentElement.classList.contains("reftest-wait"); - removeEventListener("load", maybeResolve, {once: true}); + reftestWait = document.documentElement.classList.contains( + "reftest-wait" + ); + removeEventListener("load", maybeResolve, { once: true }); win.setTimeout(resolve, 0); } }; @@ -1643,7 +1786,7 @@ async function reftestWait(url, remote) { win.setTimeout(resolve, 0); } }); - observer.observe(root, {attributes: true}); + observer.observe(root, { attributes: true }); }); } } @@ -1659,7 +1802,7 @@ async function reftestWait(url, remote) { } if (windowUtils.isMozAfterPaintPending) { logger.debug(`reftestWait: ${windowUtils.isMozAfterPaintPending}`); - win.addEventListener("MozAfterPaint", maybeResolve, {once: true}); + win.addEventListener("MozAfterPaint", maybeResolve, { once: true }); } else { // resolve at the start of the next frame in case of leftover paints win.requestAnimationFrame(() => { diff --git a/testing/marionette/log.js b/testing/marionette/log.js index cfc55bc10773..ea53d9a6e5c5 100644 --- a/testing/marionette/log.js +++ b/testing/marionette/log.js @@ -56,7 +56,10 @@ class Log { */ static getWithPrefix(prefix) { this.get(); - return StdLog.repository.getLoggerWithMessagePrefix("Marionette", `[${prefix}] `); + return StdLog.repository.getLoggerWithMessagePrefix( + "Marionette", + `[${prefix}] ` + ); } } diff --git a/testing/marionette/message.js b/testing/marionette/message.js index 5613659c15cb..ef43e2b3f539 100644 --- a/testing/marionette/message.js +++ b/testing/marionette/message.js @@ -4,15 +4,13 @@ "use strict"; -const {assert} = ChromeUtils.import("chrome://marionette/content/assert.js"); -const {error} = ChromeUtils.import("chrome://marionette/content/error.js"); -const {truncate} = ChromeUtils.import("chrome://marionette/content/format.js"); +const { assert } = ChromeUtils.import("chrome://marionette/content/assert.js"); +const { error } = ChromeUtils.import("chrome://marionette/content/error.js"); +const { truncate } = ChromeUtils.import( + "chrome://marionette/content/format.js" +); -this.EXPORTED_SYMBOLS = [ - "Command", - "Message", - "Response", -]; +this.EXPORTED_SYMBOLS = ["Command", "Message", "Response"]; /** Representation of the packets transproted over the wire. */ class Message { @@ -56,7 +54,8 @@ class Message { default: throw new TypeError( - "Unrecognised message type in packet: " + JSON.stringify(data)); + "Unrecognised message type in packet: " + JSON.stringify(data) + ); } } } @@ -165,12 +164,7 @@ class Command extends Message { * Packet. */ toPacket() { - return [ - Command.Type, - this.id, - this.name, - this.parameters, - ]; + return [Command.Type, this.id, this.name, this.parameters]; } /** @@ -234,7 +228,7 @@ class Response extends Message { this.respHandler_ = assert.callable(respHandler); this.error = null; - this.body = {value: null}; + this.body = { value: null }; this.origin = Message.Origin.Server; this.sent = false; @@ -299,12 +293,7 @@ class Response extends Message { * Packet. */ toPacket() { - return [ - Response.Type, - this.id, - this.error, - this.body, - ]; + return [Response.Type, this.id, this.error, this.body]; } /** diff --git a/testing/marionette/modal.js b/testing/marionette/modal.js index ecd9c20c995d..74db1b0da609 100644 --- a/testing/marionette/modal.js +++ b/testing/marionette/modal.js @@ -4,10 +4,12 @@ "use strict"; -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); -const {Log} = ChromeUtils.import("chrome://marionette/content/log.js"); +const { Log } = ChromeUtils.import("chrome://marionette/content/log.js"); XPCOMUtils.defineLazyGetter(this, "logger", Log.get); @@ -16,7 +18,7 @@ this.EXPORTED_SYMBOLS = ["modal"]; const COMMON_DIALOG = "chrome://global/content/commonDialog.xul"; const isFirefox = () => - Services.appinfo.ID == "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"; + Services.appinfo.ID == "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"; /** @namespace */ this.modal = { @@ -40,8 +42,11 @@ modal.findModalDialogs = function(context) { for (let win of Services.wm.getEnumerator(null)) { // TODO: Use BrowserWindowTracker.getTopWindow for modal dialogs without // an opener. - if (win.document.documentURI === COMMON_DIALOG && - win.opener && win.opener === context.window) { + if ( + win.document.documentURI === COMMON_DIALOG && + win.opener && + win.opener === context.window + ) { return new modal.Dialog(() => context, Cu.getWeakReference(win)); } } @@ -51,8 +56,7 @@ modal.findModalDialogs = function(context) { // TODO: Find an adequate implementation for Fennec. if (context.tab && context.tabBrowser.getTabModalPromptBox) { let contentBrowser = context.contentBrowser; - let promptManager = - context.tabBrowser.getTabModalPromptBox(contentBrowser); + let promptManager = context.tabBrowser.getTabModalPromptBox(contentBrowser); let prompts = promptManager.listPrompts(); if (prompts.length) { @@ -105,8 +109,9 @@ modal.DialogObserver = class { handleEvent(event) { logger.trace(`Received event ${event.type}`); - let chromeWin = event.target.opener ? event.target.opener.ownerGlobal : - event.target.ownerGlobal; + let chromeWin = event.target.opener + ? event.target.opener.ownerGlobal + : event.target.ownerGlobal; let targetRef = Cu.getWeakReference(event.target); @@ -121,8 +126,9 @@ modal.DialogObserver = class { switch (topic) { case "common-dialog-loaded": case "tabmodal-dialog-loaded": - let chromeWin = subject.opener ? subject.opener.ownerGlobal : - subject.ownerGlobal; + let chromeWin = subject.opener + ? subject.opener.ownerGlobal + : subject.ownerGlobal; // Always keep a weak reference to the current dialog let targetRef = Cu.getWeakReference(subject); @@ -179,7 +185,9 @@ modal.Dialog = class { this.win_ = winRef; } - get curBrowser_() { return this.curBrowserFn_(); } + get curBrowser_() { + return this.curBrowserFn_(); + } /** * Returns the ChromeWindow associated with an open dialog window if diff --git a/testing/marionette/navigate.js b/testing/marionette/navigate.js index dda32c1a8554..b4be9c1070d2 100644 --- a/testing/marionette/navigate.js +++ b/testing/marionette/navigate.js @@ -4,7 +4,9 @@ "use strict"; -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); XPCOMUtils.defineLazyGlobalGetters(this, ["URL"]); @@ -51,8 +53,11 @@ navigate.isLoadEventExpected = function(current, future = undefined) { } // If hashes are present and identical - if (cur.href.includes("#") && fut.href.includes("#") && - cur.hash === fut.hash) { + if ( + cur.href.includes("#") && + fut.href.includes("#") && + cur.hash === fut.hash + ) { return false; } diff --git a/testing/marionette/packets.js b/testing/marionette/packets.js index da0af2b8c7fd..eb90baab3623 100644 --- a/testing/marionette/packets.js +++ b/testing/marionette/packets.js @@ -24,11 +24,13 @@ * Called to clean up at the end of use */ -const {StreamUtils} = - ChromeUtils.import("chrome://marionette/content/stream-utils.js"); +const { StreamUtils } = ChromeUtils.import( + "chrome://marionette/content/stream-utils.js" +); -const unicodeConverter = Cc["@mozilla.org/intl/scriptableunicodeconverter"] - .createInstance(Ci.nsIScriptableUnicodeConverter); +const unicodeConverter = Cc[ + "@mozilla.org/intl/scriptableunicodeconverter" +].createInstance(Ci.nsIScriptableUnicodeConverter); unicodeConverter.charset = "UTF-8"; const defer = function() { @@ -72,20 +74,25 @@ function Packet(transport) { * Parsed packet of the matching type, or null if no types matched. */ Packet.fromHeader = function(header, transport) { - return JSONPacket.fromHeader(header, transport) || - BulkPacket.fromHeader(header, transport); + return ( + JSONPacket.fromHeader(header, transport) || + BulkPacket.fromHeader(header, transport) + ); }; Packet.prototype = { - get length() { return this._length; }, set length(length) { if (length > PACKET_LENGTH_MAX) { - throw new Error("Packet length " + length + - " exceeds the max length of " + PACKET_LENGTH_MAX); + throw new Error( + "Packet length " + + length + + " exceeds the max length of " + + PACKET_LENGTH_MAX + ); } this._length = length; }, @@ -172,8 +179,14 @@ JSONPacket.prototype.read = function(stream, scriptableStream) { json = unicodeConverter.ConvertToUnicode(json); this._object = JSON.parse(json); } catch (e) { - let msg = "Error parsing incoming packet: " + json + " (" + e + - " - " + e.stack + ")"; + let msg = + "Error parsing incoming packet: " + + json + + " (" + + e + + " - " + + e.stack + + ")"; console.error(msg); dump(msg + "\n"); return; @@ -184,8 +197,9 @@ JSONPacket.prototype.read = function(stream, scriptableStream) { JSONPacket.prototype._readData = function(stream, scriptableStream) { let bytesToRead = Math.min( - this.length - this._data.length, - stream.available()); + this.length - this._data.length, + stream.available() + ); this._data += scriptableStream.readBytes(bytesToRead); this._done = this._data.length === this.length; }; @@ -275,7 +289,7 @@ BulkPacket.prototype.read = function(stream) { actor: this.actor, type: this.type, length: this.length, - copyTo: (output) => { + copyTo: output => { let copying = StreamUtils.copyStream(stream, output, this.length); deferred.resolve(copying); return copying; @@ -299,14 +313,16 @@ BulkPacket.prototype.read = function(stream) { BulkPacket.prototype.write = function(stream) { if (this._outgoingHeader === undefined) { // Format the serialized packet header to a buffer - this._outgoingHeader = "bulk " + this.actor + " " + this.type + " " + - this.length + ":"; + this._outgoingHeader = + "bulk " + this.actor + " " + this.type + " " + this.length + ":"; } // Write the header, or whatever's left of it to write. if (this._outgoingHeader.length) { - let written = stream.write(this._outgoingHeader, - this._outgoingHeader.length); + let written = stream.write( + this._outgoingHeader, + this._outgoingHeader.length + ); this._outgoingHeader = this._outgoingHeader.slice(written); return; } @@ -317,7 +333,7 @@ BulkPacket.prototype.write = function(stream) { let deferred = defer(); this._readyForWriting.resolve({ - copyFrom: (input) => { + copyFrom: input => { let copying = StreamUtils.copyStream(input, stream, this.length); deferred.resolve(copying); return copying; diff --git a/testing/marionette/prefs.js b/testing/marionette/prefs.js index e4a7b1cdce83..5bce4c3018b7 100644 --- a/testing/marionette/prefs.js +++ b/testing/marionette/prefs.js @@ -4,25 +4,22 @@ "use strict"; -const {Log} = ChromeUtils.import("resource://gre/modules/Log.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { Log } = ChromeUtils.import("resource://gre/modules/Log.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); -XPCOMUtils.defineLazyServiceGetter(this, "env", - "@mozilla.org/process/environment;1", - "nsIEnvironment"); +XPCOMUtils.defineLazyServiceGetter( + this, + "env", + "@mozilla.org/process/environment;1", + "nsIEnvironment" +); -const { - PREF_BOOL, - PREF_INT, - PREF_INVALID, - PREF_STRING, -} = Ci.nsIPrefBranch; +const { PREF_BOOL, PREF_INT, PREF_INVALID, PREF_STRING } = Ci.nsIPrefBranch; -this.EXPORTED_SYMBOLS = [ - "Branch", - "MarionettePrefs", -]; +this.EXPORTED_SYMBOLS = ["Branch", "MarionettePrefs"]; class Branch { /** @@ -245,7 +242,7 @@ class EnvironmentPrefs { * * @return {Iterable. */ - static* from(key) { + static *from(key) { if (!env.exists(key)) { return; } diff --git a/testing/marionette/proxy.js b/testing/marionette/proxy.js index 5ad40f9796cb..3cdadd7dde96 100644 --- a/testing/marionette/proxy.js +++ b/testing/marionette/proxy.js @@ -4,25 +4,32 @@ "use strict"; -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); -const { - error, - WebDriverError, -} = ChromeUtils.import("chrome://marionette/content/error.js"); -const {evaluate} = ChromeUtils.import("chrome://marionette/content/evaluate.js"); -const {Log} = ChromeUtils.import("chrome://marionette/content/log.js"); -const {modal} = ChromeUtils.import("chrome://marionette/content/modal.js"); -const { - MessageManagerDestroyedPromise, -} = ChromeUtils.import("chrome://marionette/content/sync.js"); +const { error, WebDriverError } = ChromeUtils.import( + "chrome://marionette/content/error.js" +); +const { evaluate } = ChromeUtils.import( + "chrome://marionette/content/evaluate.js" +); +const { Log } = ChromeUtils.import("chrome://marionette/content/log.js"); +const { modal } = ChromeUtils.import("chrome://marionette/content/modal.js"); +const { MessageManagerDestroyedPromise } = ChromeUtils.import( + "chrome://marionette/content/sync.js" +); this.EXPORTED_SYMBOLS = ["proxy"]; XPCOMUtils.defineLazyGetter(this, "log", Log.get); XPCOMUtils.defineLazyServiceGetter( - this, "uuidgen", "@mozilla.org/uuid-generator;1", "nsIUUIDGenerator"); + this, + "uuidgen", + "@mozilla.org/uuid-generator;1", + "nsIUUIDGenerator" +); // Proxy handler that traps requests to get a property. Will prioritise // properties that exist on the object's own prototype. @@ -122,7 +129,7 @@ proxy.AsyncMessageChannel = class { let path = proxy.AsyncMessageChannel.makePath(uuid); let cb = msg => { this.activeMessageId = null; - let {data, type} = msg.json; + let { data, type } = msg.json; switch (msg.json.type) { case proxy.AsyncMessageChannel.ReplyType.Ok: @@ -143,7 +150,7 @@ proxy.AsyncMessageChannel = class { // The currently selected tab or window is closing. Make sure to wait // until it's fully gone. - this.closeHandler = async ({type, target}) => { + this.closeHandler = async ({ type, target }) => { log.trace(`Received DOM event ${type} for ${target}`); let messageManager; @@ -200,8 +207,9 @@ proxy.AsyncMessageChannel = class { this.browser.window.addEventListener("unload", this.closeHandler); if (this.browser.tab) { - let node = this.browser.tab.addEventListener ? - this.browser.tab : this.browser.contentBrowser; + let node = this.browser.tab.addEventListener + ? this.browser.tab + : this.browser.contentBrowser; node.addEventListener("TabClose", this.closeHandler); } } @@ -217,8 +225,9 @@ proxy.AsyncMessageChannel = class { this.browser.window.removeEventListener("unload", this.closeHandler); if (this.browser.tab) { - let node = this.browser.tab.addEventListener ? - this.browser.tab : this.browser.contentBrowser; + let node = this.browser.tab.addEventListener + ? this.browser.tab + : this.browser.contentBrowser; if (node) { node.removeEventListener("TabClose", this.closeHandler); } @@ -271,7 +280,7 @@ proxy.AsyncMessageChannel = class { const path = proxy.AsyncMessageChannel.makePath(uuid); let data = evaluate.toJSON(payload); - const msg = {type, data}; + const msg = { type, data }; // here sendAsync is actually the content frame's // sendAsyncMessage(path, message) global diff --git a/testing/marionette/reftest.js b/testing/marionette/reftest.js index f15a6e588f3d..de450f3aa4ab 100644 --- a/testing/marionette/reftest.js +++ b/testing/marionette/reftest.js @@ -4,14 +4,22 @@ "use strict"; -const {Preferences} = ChromeUtils.import("resource://gre/modules/Preferences.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { Preferences } = ChromeUtils.import( + "resource://gre/modules/Preferences.jsm" +); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); -const {assert} = ChromeUtils.import("chrome://marionette/content/assert.js"); -const {capture} = ChromeUtils.import("chrome://marionette/content/capture.js"); -const {InvalidArgumentError} = ChromeUtils.import("chrome://marionette/content/error.js"); -const {Log} = ChromeUtils.import("chrome://marionette/content/log.js"); +const { assert } = ChromeUtils.import("chrome://marionette/content/assert.js"); +const { capture } = ChromeUtils.import( + "chrome://marionette/content/capture.js" +); +const { InvalidArgumentError } = ChromeUtils.import( + "chrome://marionette/content/error.js" +); +const { Log } = ChromeUtils.import("chrome://marionette/content/log.js"); XPCOMUtils.defineLazyGetter(this, "logger", Log.get); @@ -71,13 +79,15 @@ reftest.Runner = class { * String enum representing when screenshots should be taken */ setup(urlCount, screenshotMode) { - this.parentWindow = assert.open(this.driver.getCurrentWindow()); + this.parentWindow = assert.open(this.driver.getCurrentWindow()); - this.screenshotMode = SCREENSHOT_MODE[screenshotMode] || - SCREENSHOT_MODE.unexpected; + this.screenshotMode = + SCREENSHOT_MODE[screenshotMode] || SCREENSHOT_MODE.unexpected; - this.urlCount = Object.keys(urlCount || {}) - .reduce((map, key) => map.set(key, urlCount[key]), new Map()); + this.urlCount = Object.keys(urlCount || {}).reduce( + (map, key) => map.set(key, urlCount[key]), + new Map() + ); } async ensureWindow(timeout, width, height) { @@ -99,7 +109,8 @@ reftest.Runner = class { commandID: this.driver.listener.activeMessageId, pageTimeout: timeout, url: "about:blank", - loadEventExpected: false}); + loadEventExpected: false, + }); } else { logger.debug("Using separate window"); if (this.reftestWin && !this.reftestWin.closed) { @@ -126,12 +137,13 @@ reftest.Runner = class { assert.positiveInteger(height); let reftestWin = this.parentWindow.open( - "chrome://marionette/content/reftest.xul", - "reftest", - `chrome,height=${height},width=${width}`); + "chrome://marionette/content/reftest.xul", + "reftest", + `chrome,height=${height},width=${width}` + ); await new Promise(resolve => { - reftestWin.addEventListener("load", resolve, {once: true}); + reftestWin.addEventListener("load", resolve, { once: true }); }); return reftestWin; } @@ -225,22 +237,33 @@ max-width: ${width}px; max-height: ${height}px`; * @return {Object} * Result object with fields status, message and extra. */ - async run(testUrl, references, expected, timeout, - width = DEFAULT_REFTEST_WIDTH, - height = DEFAULT_REFTEST_HEIGHT) { + async run( + testUrl, + references, + expected, + timeout, + width = DEFAULT_REFTEST_WIDTH, + height = DEFAULT_REFTEST_HEIGHT + ) { let timeoutHandle; let timeoutPromise = new Promise(resolve => { timeoutHandle = this.parentWindow.setTimeout(() => { - resolve({status: STATUS.TIMEOUT, message: null, extra: {}}); + resolve({ status: STATUS.TIMEOUT, message: null, extra: {} }); }, timeout); }); let testRunner = (async () => { let result; try { - result = await this.runTest(testUrl, references, expected, timeout, - width, height); + result = await this.runTest( + testUrl, + references, + expected, + timeout, + width, + height + ); } catch (e) { result = { status: STATUS.ERROR, @@ -293,9 +316,15 @@ max-width: ${width}px; max-height: ${height}px`; let comparison; try { comparison = await this.compareUrls( - win, lhsUrl, rhsUrl, relation, timeout, extras); + win, + lhsUrl, + rhsUrl, + relation, + timeout, + extras + ); } catch (e) { - comparison = {lhs: null, rhs: null, passed: false, error: e}; + comparison = { lhs: null, rhs: null, passed: false, error: e }; } if (comparison.error !== null) { result.status = STATUS.ERROR; @@ -306,9 +335,11 @@ max-width: ${width}px; max-height: ${height}px`; function recordScreenshot() { let encodedLHS = comparison.lhs ? toBase64(comparison.lhs) : ""; let encodedRHS = comparison.rhs ? toBase64(comparison.rhs) : ""; - screenshotData.push([{url: lhsUrl, screenshot: encodedLHS}, + screenshotData.push([ + { url: lhsUrl, screenshot: encodedLHS }, relation, - {url: rhsUrl, screenshot: encodedRHS}]); + { url: rhsUrl, screenshot: encodedRHS }, + ]); } if (this.screenshotMode === SCREENSHOT_MODE.always) { @@ -324,8 +355,10 @@ max-width: ${width}px; max-height: ${height}px`; } else { // Reached a leaf node so all of one reference chain passed result.status = STATUS.PASS; - if (this.screenshotMode <= SCREENSHOT_MODE.fail && - expected != result.status) { + if ( + this.screenshotMode <= SCREENSHOT_MODE.fail && + expected != result.status + ) { recordScreenshot(); } done = true; @@ -348,7 +381,9 @@ max-width: ${width}px; max-height: ${height}px`; canvasPool.push(screenshot.canvas); } }); - logger.debug(`Canvas pool (${cacheKey}) is of length ${canvasPool.length}`); + logger.debug( + `Canvas pool (${cacheKey}) is of length ${canvasPool.length}` + ); } if (screenshotData.length) { @@ -380,7 +415,10 @@ max-width: ${width}px; max-height: ${height}px`; try { pixelsDifferent = this.windowUtils.compareCanvases( - lhs.canvas, rhs.canvas, maxDifferences); + lhs.canvas, + rhs.canvas, + maxDifferences + ); } catch (e) { passed = false; error = e; @@ -388,22 +426,29 @@ max-width: ${width}px; max-height: ${height}px`; if (error === null) { passed = this.isAcceptableDifference( - maxDifferences.value, pixelsDifferent, extras.fuzzy); + maxDifferences.value, + pixelsDifferent, + extras.fuzzy + ); switch (relation) { case "==": if (!passed) { - logger.info(`Found ${pixelsDifferent} pixels different, ` + - `maximum difference per channel ${maxDifferences.value}`); + logger.info( + `Found ${pixelsDifferent} pixels different, ` + + `maximum difference per channel ${maxDifferences.value}` + ); } break; case "!=": passed = !passed; break; default: - throw new InvalidArgumentError("Reftest operator should be '==' or '!='"); + throw new InvalidArgumentError( + "Reftest operator should be '==' or '!='" + ); } } - return {lhs, rhs, passed, error}; + return { lhs, rhs, passed, error }; } isAcceptableDifference(maxDifference, pixelsDifferent, allowed) { @@ -412,14 +457,18 @@ max-width: ${width}px; max-height: ${height}px`; return pixelsDifferent === 0; } let [allowedDiff, allowedPixels] = allowed; - logger.info(`Allowed ${allowedPixels.join("-")} pixels different, ` + - `maximum difference per channel ${allowedDiff.join("-")}`); - return ((pixelsDifferent === 0 && allowedPixels[0] == 0) || - (maxDifference === 0 && allowedDiff[0] == 0) || - ((maxDifference >= allowedDiff[0] && - maxDifference <= allowedDiff[1]) && - (pixelsDifferent >= allowedPixels[0] || - pixelsDifferent <= allowedPixels[1]))); + logger.info( + `Allowed ${allowedPixels.join("-")} pixels different, ` + + `maximum difference per channel ${allowedDiff.join("-")}` + ); + return ( + (pixelsDifferent === 0 && allowedPixels[0] == 0) || + (maxDifference === 0 && allowedDiff[0] == 0) || + (maxDifference >= allowedDiff[0] && + maxDifference <= allowedDiff[1] && + (pixelsDifferent >= allowedPixels[0] || + pixelsDifferent <= allowedPixels[1])) + ); } ensureFocus(win) { @@ -439,8 +488,10 @@ max-width: ${width}px; max-height: ${height}px`; let remainingCount = this.urlCount.get(url) || 1; let cache = remainingCount > 1; let cacheKey = browserRect.width + "x" + browserRect.height; - logger.debug(`screenshot ${url} remainingCount: ` + - `${remainingCount} cache: ${cache} cacheKey: ${cacheKey}`); + logger.debug( + `screenshot ${url} remainingCount: ` + + `${remainingCount} cache: ${cache} cacheKey: ${cacheKey}` + ); let reuseCanvas = false; let sizedCache = this.canvasCache.get(cacheKey); if (sizedCache.has(url)) { @@ -461,14 +512,19 @@ max-width: ${width}px; max-height: ${height}px`; reuseCanvas = !cache; let ctxInterface = win.CanvasRenderingContext2D; - let flags = ctxInterface.DRAWWINDOW_DRAW_CARET | - ctxInterface.DRAWWINDOW_DRAW_VIEW | - ctxInterface.DRAWWINDOW_USE_WIDGET_LAYERS; + let flags = + ctxInterface.DRAWWINDOW_DRAW_CARET | + ctxInterface.DRAWWINDOW_DRAW_VIEW | + ctxInterface.DRAWWINDOW_USE_WIDGET_LAYERS; - if (!(0 <= browserRect.left && - 0 <= browserRect.top && - win.innerWidth >= browserRect.width && - win.innerHeight >= browserRect.height)) { + if ( + !( + 0 <= browserRect.left && + 0 <= browserRect.top && + win.innerWidth >= browserRect.width && + win.innerHeight >= browserRect.height + ) + ) { logger.error(`Invalid window dimensions: browserRect.left: ${browserRect.left} browserRect.top: ${browserRect.top} @@ -499,16 +555,21 @@ browserRect.height: ${browserRect.height}`); await this.driver.listener.reftestWait(url, this.remote); canvas = capture.canvas( - win, - 0, // left - 0, // top - browserRect.width, - browserRect.height, - {canvas, flags}); + win, + 0, // left + 0, // top + browserRect.width, + browserRect.height, + { canvas, flags } + ); } - if (canvas.width !== browserRect.width || - canvas.height !== browserRect.height) { - logger.warn(`Canvas dimensions changed to ${canvas.width}x${canvas.height}`); + if ( + canvas.width !== browserRect.width || + canvas.height !== browserRect.height + ) { + logger.warn( + `Canvas dimensions changed to ${canvas.width}x${canvas.height}` + ); reuseCanvas = false; cache = false; } @@ -516,7 +577,7 @@ browserRect.height: ${browserRect.height}`); sizedCache.set(url, canvas); } this.urlCount.set(url, remainingCount - 1); - return {canvas, reuseCanvas}; + return { canvas, reuseCanvas }; } }; diff --git a/testing/marionette/server.js b/testing/marionette/server.js index 076324644989..c51a7baeb59a 100644 --- a/testing/marionette/server.js +++ b/testing/marionette/server.js @@ -7,36 +7,43 @@ const CC = Components.Constructor; const ServerSocket = CC( - "@mozilla.org/network/server-socket;1", - "nsIServerSocket", - "initSpecialConnection"); + "@mozilla.org/network/server-socket;1", + "nsIServerSocket", + "initSpecialConnection" +); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); -const {assert} = ChromeUtils.import("chrome://marionette/content/assert.js"); -const {GeckoDriver} = ChromeUtils.import("chrome://marionette/content/driver.js"); -const {WebElement} = ChromeUtils.import("chrome://marionette/content/element.js"); -const { - error, - UnknownCommandError, -} = ChromeUtils.import("chrome://marionette/content/error.js"); -const { - Command, - Message, - Response, -} = ChromeUtils.import("chrome://marionette/content/message.js"); -const {Log} = ChromeUtils.import("chrome://marionette/content/log.js"); -const {MarionettePrefs} = ChromeUtils.import("chrome://marionette/content/prefs.js", null); -const {DebuggerTransport} = ChromeUtils.import("chrome://marionette/content/transport.js", null); +const { assert } = ChromeUtils.import("chrome://marionette/content/assert.js"); +const { GeckoDriver } = ChromeUtils.import( + "chrome://marionette/content/driver.js" +); +const { WebElement } = ChromeUtils.import( + "chrome://marionette/content/element.js" +); +const { error, UnknownCommandError } = ChromeUtils.import( + "chrome://marionette/content/error.js" +); +const { Command, Message, Response } = ChromeUtils.import( + "chrome://marionette/content/message.js" +); +const { Log } = ChromeUtils.import("chrome://marionette/content/log.js"); +const { MarionettePrefs } = ChromeUtils.import( + "chrome://marionette/content/prefs.js", + null +); +const { DebuggerTransport } = ChromeUtils.import( + "chrome://marionette/content/transport.js", + null +); XPCOMUtils.defineLazyGetter(this, "logger", Log.get); -const {KeepWhenOffline, LoopbackOnly} = Ci.nsIServerSocket; +const { KeepWhenOffline, LoopbackOnly } = Ci.nsIServerSocket; -this.EXPORTED_SYMBOLS = [ - "TCPConnection", - "TCPListener", -]; +this.EXPORTED_SYMBOLS = ["TCPConnection", "TCPListener"]; /** @namespace */ this.server = {}; @@ -135,12 +142,17 @@ class TCPListener { let transport = new DebuggerTransport(input, output); let conn = new TCPConnection( - this.nextConnID++, transport, this.driverFactory.bind(this)); + this.nextConnID++, + transport, + this.driverFactory.bind(this) + ); conn.onclose = this.onConnectionClosed.bind(this); this.conns.add(conn); - logger.debug(`Accepted connection ${conn.id} ` + - `from ${clientSocket.host}:${clientSocket.port}`); + logger.debug( + `Accepted connection ${conn.id} ` + + `from ${clientSocket.host}:${clientSocket.port}` + ); conn.sayHello(); transport.ready(); } @@ -212,7 +224,8 @@ class TCPConnection { // unable to determine how to respond if (!Array.isArray(data)) { let e = new TypeError( - "Unable to unmarshal packet data: " + JSON.stringify(data)); + "Unable to unmarshal packet data: " + JSON.stringify(data) + ); error.report(e); return; } @@ -260,7 +273,8 @@ class TCPConnection { let sendError = resp.sendError.bind(resp); await this.despatch(cmd, resp) - .then(sendResponse, sendError).catch(error.report); + .then(sendResponse, sendError) + .catch(error.report); } /** @@ -282,15 +296,17 @@ class TCPConnection { } if (cmd.name != "WebDriver:NewSession") { - assert.session(this.driver, - "Tried to run command without establishing a connection"); + assert.session( + this.driver, + "Tried to run command without establishing a connection" + ); } let rv = await fn.bind(this.driver)(cmd); if (rv != null) { if (rv instanceof WebElement || typeof rv != "object") { - resp.body = {value: rv}; + resp.body = { value: rv }; } else { resp.body = rv; } @@ -392,7 +408,7 @@ class TCPConnection { } log_(msg) { - let dir = (msg.origin == Message.Origin.Client ? "->" : "<-"); + let dir = msg.origin == Message.Origin.Client ? "->" : "<-"; logger.debug(`${this.id} ${dir} ${msg}`); } diff --git a/testing/marionette/stream-utils.js b/testing/marionette/stream-utils.js index 26bd5de12159..5988226f6f8b 100644 --- a/testing/marionette/stream-utils.js +++ b/testing/marionette/stream-utils.js @@ -6,12 +6,17 @@ const CC = Components.Constructor; -const {EventEmitter} = ChromeUtils.import("resource://gre/modules/EventEmitter.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { EventEmitter } = ChromeUtils.import( + "resource://gre/modules/EventEmitter.jsm" +); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const IOUtil = Cc["@mozilla.org/io-util;1"].getService(Ci.nsIIOUtil); -const ScriptableInputStream = CC("@mozilla.org/scriptableinputstream;1", - "nsIScriptableInputStream", "init"); +const ScriptableInputStream = CC( + "@mozilla.org/scriptableinputstream;1", + "nsIScriptableInputStream", + "init" +); this.EXPORTED_SYMBOLS = ["StreamUtils"]; @@ -68,8 +73,9 @@ function StreamCopier(input, output, length) { if (IOUtil.outputStreamIsBuffered(output)) { this.output = output; } else { - this.output = Cc["@mozilla.org/network/buffered-output-stream;1"] - .createInstance(Ci.nsIBufferedOutputStream); + this.output = Cc[ + "@mozilla.org/network/buffered-output-stream;1" + ].createInstance(Ci.nsIBufferedOutputStream); this.output.init(output, BUFFER_SIZE); } this._length = length; @@ -100,7 +106,6 @@ function StreamCopier(input, output, length) { StreamCopier._nextId = 0; StreamCopier.prototype = { - copy() { // Dispatch to the next tick so that it's possible to attach a progress // event listener, even for extremely fast copies (like when testing). @@ -133,8 +138,7 @@ StreamCopier.prototype = { } this._amountLeft -= bytesCopied; - this._debug("Copied: " + bytesCopied + - ", Left: " + this._amountLeft); + this._debug("Copied: " + bytesCopied + ", Left: " + this._amountLeft); this._emitProgress(); if (this._amountLeft === 0) { @@ -158,8 +162,10 @@ StreamCopier.prototype = { try { this.output.flush(); } catch (e) { - if (e.result == Cr.NS_BASE_STREAM_WOULD_BLOCK || - e.result == Cr.NS_ERROR_FAILURE) { + if ( + e.result == Cr.NS_BASE_STREAM_WOULD_BLOCK || + e.result == Cr.NS_ERROR_FAILURE + ) { this._debug("Flush would block, will retry"); this._streamReadyCallback = this._flush; this._debug("Waiting for output stream"); @@ -189,9 +195,7 @@ StreamCopier.prototype = { this._streamReadyCallback(); }, - _debug() { - }, - + _debug() {}, }; /** diff --git a/testing/marionette/sync.js b/testing/marionette/sync.js index ee361e4dc4b6..df8f993da48b 100644 --- a/testing/marionette/sync.js +++ b/testing/marionette/sync.js @@ -4,17 +4,21 @@ "use strict"; -const {AppConstants} = ChromeUtils.import("resource://gre/modules/AppConstants.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { AppConstants } = ChromeUtils.import( + "resource://gre/modules/AppConstants.jsm" +); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); -const { - error, - stack, - TimeoutError, -} = ChromeUtils.import("chrome://marionette/content/error.js"); -const {truncate} = ChromeUtils.import("chrome://marionette/content/format.js"); -const {Log} = ChromeUtils.import("chrome://marionette/content/log.js"); +const { error, stack, TimeoutError } = ChromeUtils.import( + "chrome://marionette/content/error.js" +); +const { truncate } = ChromeUtils.import( + "chrome://marionette/content/format.js" +); +const { Log } = ChromeUtils.import("chrome://marionette/content/log.js"); XPCOMUtils.defineLazyGetter(this, "log", Log.get); @@ -31,11 +35,10 @@ this.EXPORTED_SYMBOLS = [ "waitForObserverTopic", ]; -const {TYPE_ONE_SHOT, TYPE_REPEATING_SLACK} = Ci.nsITimer; +const { TYPE_ONE_SHOT, TYPE_REPEATING_SLACK } = Ci.nsITimer; const PROMISE_TIMEOUT = AppConstants.DEBUG ? 4500 : 1500; - /** * Dispatch a function to be executed on the main thread. * @@ -115,7 +118,7 @@ function executeSoon(func) { * @throws {RangeError} * If `timeout` or `interval` are not unsigned integers. */ -function PollPromise(func, {timeout = null, interval = 10} = {}) { +function PollPromise(func, { timeout = null, interval = 10 } = {}) { const timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); if (typeof func != "function") { @@ -127,8 +130,10 @@ function PollPromise(func, {timeout = null, interval = 10} = {}) { if (typeof interval != "number") { throw new TypeError(); } - if ((timeout && (!Number.isInteger(timeout) || timeout < 0)) || - (!Number.isInteger(interval) || interval < 0)) { + if ( + (timeout && (!Number.isInteger(timeout) || timeout < 0)) || + (!Number.isInteger(interval) || interval < 0) + ) { throw new RangeError(); } @@ -141,18 +146,22 @@ function PollPromise(func, {timeout = null, interval = 10} = {}) { } let evalFn = () => { - new Promise(func).then(resolve, rejected => { - if (error.isError(rejected)) { - throw rejected; - } + new Promise(func) + .then(resolve, rejected => { + if (error.isError(rejected)) { + throw rejected; + } - // return if there is a timeout and set to 0, - // allowing |func| to be evaluated at least once - if (typeof end != "undefined" && - (start == end || new Date().getTime() >= end)) { - resolve(rejected); - } - }).catch(reject); + // return if there is a timeout and set to 0, + // allowing |func| to be evaluated at least once + if ( + typeof end != "undefined" && + (start == end || new Date().getTime() >= end) + ) { + resolve(rejected); + } + }) + .catch(reject); }; // the repeating slack timer waits |interval| @@ -160,13 +169,16 @@ function PollPromise(func, {timeout = null, interval = 10} = {}) { evalFn(); timer.init(evalFn, interval, TYPE_REPEATING_SLACK); - }).then(res => { - timer.cancel(); - return res; - }, err => { - timer.cancel(); - throw err; - }); + }).then( + res => { + timer.cancel(); + return res; + }, + err => { + timer.cancel(); + throw err; + } + ); } /** @@ -198,8 +210,10 @@ function PollPromise(func, {timeout = null, interval = 10} = {}) { * @throws {RangeError} * If `timeout` is not an unsigned integer. */ -function TimedPromise(fn, - {timeout = PROMISE_TIMEOUT, throws = TimeoutError} = {}) { +function TimedPromise( + fn, + { timeout = PROMISE_TIMEOUT, throws = TimeoutError } = {} +) { const timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); if (typeof fn != "function") { @@ -225,20 +239,23 @@ function TimedPromise(fn, } }; - timer.initWithCallback({notify: bail}, timeout, TYPE_ONE_SHOT); + timer.initWithCallback({ notify: bail }, timeout, TYPE_ONE_SHOT); try { fn(resolve, reject); } catch (e) { reject(e); } - }).then(res => { - timer.cancel(); - return res; - }, err => { - timer.cancel(); - throw err; - }); + }).then( + res => { + timer.cancel(); + return res; + }, + err => { + timer.cancel(); + throw err; + } + ); } /** @@ -259,7 +276,7 @@ function Sleep(timeout) { if (typeof timeout != "number") { throw new TypeError(); } - return new TimedPromise(() => {}, {timeout, throws: null}); + return new TimedPromise(() => {}, { timeout, throws: null }); } /** @@ -355,7 +372,7 @@ function IdlePromise(win) { * Time since last event firing, before `fn` will be invoked. */ class DebounceCallback { - constructor(fn, {timeout = 250} = {}) { + constructor(fn, { timeout = 250 } = {}) { if (typeof fn != "function" || typeof timeout != "number") { throw new TypeError(); } @@ -370,10 +387,14 @@ class DebounceCallback { handleEvent(ev) { this.timer.cancel(); - this.timer.initWithCallback(() => { - this.timer.cancel(); - this.fn(ev); - }, this.timeout, TYPE_ONE_SHOT); + this.timer.initWithCallback( + () => { + this.timer.cancel(); + this.fn(ev); + }, + this.timeout, + TYPE_ONE_SHOT + ); } } this.DebounceCallback = DebounceCallback; @@ -435,8 +456,11 @@ this.DebounceCallback = DebounceCallback; * Promise which resolves to the received ``Event`` object, or rejects * in case of a failure. */ -function waitForEvent(subject, eventName, - {capture = false, checkFn = null, wantsUntrusted = false} = {}) { +function waitForEvent( + subject, + eventName, + { capture = false, checkFn = null, wantsUntrusted = false } = {} +) { if (subject == null || !("addEventListener" in subject)) { throw new TypeError(); } @@ -454,23 +478,28 @@ function waitForEvent(subject, eventName, } return new Promise((resolve, reject) => { - subject.addEventListener(eventName, function listener(event) { - log.trace(`Received DOM event ${event.type} for ${event.target}`); - try { - if (checkFn && !checkFn(event)) { - return; - } - subject.removeEventListener(eventName, listener, capture); - executeSoon(() => resolve(event)); - } catch (ex) { + subject.addEventListener( + eventName, + function listener(event) { + log.trace(`Received DOM event ${event.type} for ${event.target}`); try { + if (checkFn && !checkFn(event)) { + return; + } subject.removeEventListener(eventName, listener, capture); - } catch (ex2) { - // Maybe the provided object does not support removeEventListener. + executeSoon(() => resolve(event)); + } catch (ex) { + try { + subject.removeEventListener(eventName, listener, capture); + } catch (ex2) { + // Maybe the provided object does not support removeEventListener. + } + executeSoon(() => reject(ex)); } - executeSoon(() => reject(ex)); - } - }, capture, wantsUntrusted); + }, + capture, + wantsUntrusted + ); }); } @@ -495,8 +524,11 @@ function waitForEvent(subject, eventName, * Promise which resolves to the data property of the received * ``Message``. */ -function waitForMessage(messageManager, messageName, - {checkFn = undefined} = {}) { +function waitForMessage( + messageManager, + messageName, + { checkFn = undefined } = {} +) { if (messageManager == null || !("addMessageListener" in messageManager)) { throw new TypeError(); } @@ -542,7 +574,7 @@ function waitForMessage(messageManager, messageName, * Promise which resolves to an array of ``subject``, and ``data`` from * the observed notification. */ -function waitForObserverTopic(topic, {checkFn = null} = {}) { +function waitForObserverTopic(topic, { checkFn = null } = {}) { if (typeof topic != "string") { throw new TypeError(); } @@ -558,7 +590,7 @@ function waitForObserverTopic(topic, {checkFn = null} = {}) { return; } Services.obs.removeObserver(observer, topic); - resolve({subject, data}); + resolve({ subject, data }); } catch (ex) { Services.obs.removeObserver(observer, topic); reject(ex); diff --git a/testing/marionette/test/unit/test_action.js b/testing/marionette/test/unit/test_action.js index c2c5c5947609..799e235b1c14 100644 --- a/testing/marionette/test/unit/test_action.js +++ b/testing/marionette/test/unit/test_action.js @@ -4,8 +4,10 @@ "use strict"; -const {action} = ChromeUtils.import("chrome://marionette/content/action.js"); -const {InvalidArgumentError} = ChromeUtils.import("chrome://marionette/content/error.js"); +const { action } = ChromeUtils.import("chrome://marionette/content/action.js"); +const { InvalidArgumentError } = ChromeUtils.import( + "chrome://marionette/content/error.js" +); const XHTMLNS = "http://www.w3.org/1999/xhtml"; @@ -18,48 +20,63 @@ const domEl = { action.inputStateMap = new Map(); add_test(function test_createAction() { - Assert.throws(() => new action.Action(), InvalidArgumentError, - "Missing Action constructor args"); - Assert.throws(() => new action.Action(1, 2), InvalidArgumentError, - "Missing Action constructor args"); Assert.throws( - () => new action.Action(1, 2, "sometype"), /Expected string/, "Non-string arguments."); + () => new action.Action(), + InvalidArgumentError, + "Missing Action constructor args" + ); + Assert.throws( + () => new action.Action(1, 2), + InvalidArgumentError, + "Missing Action constructor args" + ); + Assert.throws( + () => new action.Action(1, 2, "sometype"), + /Expected string/, + "Non-string arguments." + ); ok(new action.Action("id", "sometype", "sometype")); run_next_test(); }); add_test(function test_defaultPointerParameters() { - let defaultParameters = {pointerType: action.PointerType.Mouse}; + let defaultParameters = { pointerType: action.PointerType.Mouse }; deepEqual(action.PointerParameters.fromJSON(), defaultParameters); run_next_test(); }); add_test(function test_processPointerParameters() { - let check = (regex, message, arg) => checkErrors( - regex, action.PointerParameters.fromJSON, [arg], message); + let check = (regex, message, arg) => + checkErrors(regex, action.PointerParameters.fromJSON, [arg], message); let parametersData; for (let d of ["foo", "", "get", "Get"]) { - parametersData = {pointerType: d}; - let message = `parametersData: [pointerType: ${parametersData.pointerType}]`; + parametersData = { pointerType: d }; + let message = `parametersData: [pointerType: ${ + parametersData.pointerType + }]`; check(/Unknown pointerType/, message, parametersData); } parametersData.pointerType = "mouse"; // TODO "pen"; - deepEqual(action.PointerParameters.fromJSON(parametersData), - {pointerType: "mouse"}); // TODO action.PointerType.Pen}); + deepEqual(action.PointerParameters.fromJSON(parametersData), { + pointerType: "mouse", + }); // TODO action.PointerType.Pen}); run_next_test(); }); add_test(function test_processPointerUpDownAction() { - let actionItem = {type: "pointerDown"}; - let actionSequence = {type: "pointer", id: "some_id"}; + let actionItem = { type: "pointerDown" }; + let actionSequence = { type: "pointer", id: "some_id" }; for (let d of [-1, "a"]) { actionItem.button = d; checkErrors( - /Expected 'button' \(.*\) to be >= 0/, action.Action.fromJSON, [actionSequence, actionItem], - `button: ${actionItem.button}`); + /Expected 'button' \(.*\) to be >= 0/, + action.Action.fromJSON, + [actionSequence, actionItem], + `button: ${actionItem.button}` + ); } actionItem.button = 5; let act = action.Action.fromJSON(actionSequence, actionItem); @@ -70,13 +87,18 @@ add_test(function test_processPointerUpDownAction() { add_test(function test_validateActionDurationAndCoordinates() { let actionItem = {}; - let actionSequence = {id: "some_id"}; + let actionSequence = { id: "some_id" }; let check = function(type, subtype, message = undefined) { - message = message || `duration: ${actionItem.duration}, subtype: ${subtype}`; + message = + message || `duration: ${actionItem.duration}, subtype: ${subtype}`; actionItem.type = subtype; actionSequence.type = type; - checkErrors(/Expected '.*' \(.*\) to be >= 0/, - action.Action.fromJSON, [actionSequence, actionItem], message); + checkErrors( + /Expected '.*' \(.*\) to be >= 0/, + action.Action.fromJSON, + [actionSequence, actionItem], + message + ); }; for (let d of [-1, "a"]) { actionItem.duration = d; @@ -88,45 +110,52 @@ add_test(function test_validateActionDurationAndCoordinates() { actionItem[name] = "a"; actionItem.type = "pointerMove"; actionSequence.type = "pointer"; - checkErrors(/Expected '.*' \(.*\) to be an Integer/, - action.Action.fromJSON, [actionSequence, actionItem], - `duration: ${actionItem.duration}, subtype: pointerMove`); + checkErrors( + /Expected '.*' \(.*\) to be an Integer/, + action.Action.fromJSON, + [actionSequence, actionItem], + `duration: ${actionItem.duration}, subtype: pointerMove` + ); } run_next_test(); }); add_test(function test_processPointerMoveActionOriginValidation() { - let actionSequence = {type: "pointer", id: "some_id"}; - let actionItem = {duration: 5000, type: "pointerMove"}; - for (let d of [-1, {a: "blah"}, []]) { + let actionSequence = { type: "pointer", id: "some_id" }; + let actionItem = { duration: 5000, type: "pointerMove" }; + for (let d of [-1, { a: "blah" }, []]) { actionItem.origin = d; - checkErrors(/Expected \'origin\' to be undefined, "viewport", "pointer", or an element/, - action.Action.fromJSON, - [actionSequence, actionItem], - `actionItem.origin: (${getTypeString(d)})`); + checkErrors( + /Expected \'origin\' to be undefined, "viewport", "pointer", or an element/, + action.Action.fromJSON, + [actionSequence, actionItem], + `actionItem.origin: (${getTypeString(d)})` + ); } run_next_test(); }); add_test(function test_processPointerMoveActionOriginStringValidation() { - let actionSequence = {type: "pointer", id: "some_id"}; - let actionItem = {duration: 5000, type: "pointerMove"}; + let actionSequence = { type: "pointer", id: "some_id" }; + let actionItem = { duration: 5000, type: "pointerMove" }; for (let d of ["a", "", "get", "Get"]) { actionItem.origin = d; - checkErrors(/Unknown pointer-move origin/, - action.Action.fromJSON, - [actionSequence, actionItem], - `actionItem.origin: ${d}`); + checkErrors( + /Unknown pointer-move origin/, + action.Action.fromJSON, + [actionSequence, actionItem], + `actionItem.origin: ${d}` + ); } run_next_test(); }); add_test(function test_processPointerMoveActionElementOrigin() { - let actionSequence = {type: "pointer", id: "some_id"}; - let actionItem = {duration: 5000, type: "pointerMove"}; + let actionSequence = { type: "pointer", id: "some_id" }; + let actionItem = { duration: 5000, type: "pointerMove" }; actionItem.origin = domEl; let a = action.Action.fromJSON(actionSequence, actionItem); deepEqual(a.origin, actionItem.origin); @@ -134,16 +163,16 @@ add_test(function test_processPointerMoveActionElementOrigin() { }); add_test(function test_processPointerMoveActionDefaultOrigin() { - let actionSequence = {type: "pointer", id: "some_id"}; + let actionSequence = { type: "pointer", id: "some_id" }; // origin left undefined - let actionItem = {duration: 5000, type: "pointerMove"}; + let actionItem = { duration: 5000, type: "pointerMove" }; let a = action.Action.fromJSON(actionSequence, actionItem); deepEqual(a.origin, action.PointerOrigin.Viewport); run_next_test(); }); add_test(function test_processPointerMoveAction() { - let actionSequence = {id: "some_id", type: "pointer"}; + let actionSequence = { id: "some_id", type: "pointer" }; let actionItems = [ { duration: 5000, @@ -191,7 +220,7 @@ add_test(function test_processPointerMoveAction() { }); add_test(function test_computePointerDestinationViewport() { - let act = {type: "pointerMove", x: 100, y: 200, origin: "viewport"}; + let act = { type: "pointerMove", x: 100, y: 200, origin: "viewport" }; let inputState = new action.InputState.Pointer(action.PointerType.Mouse); // these values should not affect the outcome inputState.x = "99"; @@ -204,7 +233,7 @@ add_test(function test_computePointerDestinationViewport() { }); add_test(function test_computePointerDestinationPointer() { - let act = {type: "pointerMove", x: 100, y: 200, origin: "pointer"}; + let act = { type: "pointerMove", x: 100, y: 200, origin: "pointer" }; let inputState = new action.InputState.Pointer(action.PointerType.Mouse); inputState.x = 10; inputState.y = 99; @@ -212,29 +241,30 @@ add_test(function test_computePointerDestinationPointer() { equal(act.x + inputState.x, target.x); equal(act.y + inputState.y, target.y); - run_next_test(); }); add_test(function test_computePointerDestinationElement() { // origin represents a web element // using an object literal instead to test default case in computePointerDestination - let act = {type: "pointerMove", x: 100, y: 200, origin: {}}; + let act = { type: "pointerMove", x: 100, y: 200, origin: {} }; let inputState = new action.InputState.Pointer(action.PointerType.Mouse); - let elementCenter = {x: 10, y: 99}; + let elementCenter = { x: 10, y: 99 }; let target = action.computePointerDestination(act, inputState, elementCenter); equal(act.x + elementCenter.x, target.x); equal(act.y + elementCenter.y, target.y); Assert.throws( - () => action.computePointerDestination(act, inputState, {a: 1}), - InvalidArgumentError, - "Invalid element center coordinates."); + () => action.computePointerDestination(act, inputState, { a: 1 }), + InvalidArgumentError, + "Invalid element center coordinates." + ); Assert.throws( - () => action.computePointerDestination(act, inputState, undefined), - InvalidArgumentError, - "Undefined element center coordinates."); + () => action.computePointerDestination(act, inputState, undefined), + InvalidArgumentError, + "Undefined element center coordinates." + ); run_next_test(); }); @@ -280,8 +310,8 @@ add_test(function test_processPointerAction() { }); add_test(function test_processPauseAction() { - let actionItem = {type: "pause", duration: 5000}; - let actionSequence = {id: "some_id"}; + let actionItem = { type: "pause", duration: 5000 }; + let actionSequence = { id: "some_id" }; for (let type of ["none", "key", "pointer"]) { actionSequence.type = type; let act = action.Action.fromJSON(actionSequence, actionItem); @@ -299,11 +329,16 @@ add_test(function test_processPauseAction() { }); add_test(function test_processActionSubtypeValidation() { - let actionItem = {type: "dancing"}; - let actionSequence = {id: "some_id"}; + let actionItem = { type: "dancing" }; + let actionSequence = { id: "some_id" }; let check = function(regex) { let message = `type: ${actionSequence.type}, subtype: ${actionItem.type}`; - checkErrors(regex, action.Action.fromJSON, [actionSequence, actionItem], message); + checkErrors( + regex, + action.Action.fromJSON, + [actionSequence, actionItem], + message + ); }; for (let type of ["none", "key", "pointer"]) { actionSequence.type = type; @@ -313,16 +348,22 @@ add_test(function test_processActionSubtypeValidation() { }); add_test(function test_processKeyActionUpDown() { - let actionSequence = {type: "key", id: "some_id"}; - let actionItem = {type: "keyDown"}; + let actionSequence = { type: "key", id: "some_id" }; + let actionItem = { type: "keyDown" }; - for (let v of [-1, undefined, [], ["a"], {length: 1}, null]) { + for (let v of [-1, undefined, [], ["a"], { length: 1 }, null]) { actionItem.value = v; let message = `actionItem.value: (${getTypeString(v)})`; - Assert.throws(() => action.Action.fromJSON(actionSequence, actionItem), - InvalidArgumentError, message); - Assert.throws(() => action.Action.fromJSON(actionSequence, actionItem), - /Expected 'value' to be a string that represents single code point/, message); + Assert.throws( + () => action.Action.fromJSON(actionSequence, actionItem), + InvalidArgumentError, + message + ); + Assert.throws( + () => action.Action.fromJSON(actionSequence, actionItem), + /Expected 'value' to be a string that represents single code point/, + message + ); } actionItem.value = "\uE004"; @@ -337,40 +378,50 @@ add_test(function test_processKeyActionUpDown() { }); add_test(function test_processInputSourceActionSequenceValidation() { - let actionSequence = {type: "swim", id: "some id"}; - let check = (message, regex) => checkErrors( - regex, action.Sequence.fromJSON, [actionSequence], message); + let actionSequence = { type: "swim", id: "some id" }; + let check = (message, regex) => + checkErrors(regex, action.Sequence.fromJSON, [actionSequence], message); check(`actionSequence.type: ${actionSequence.type}`, /Unknown action type/); action.inputStateMap.clear(); actionSequence.type = "none"; actionSequence.id = -1; - check(`actionSequence.id: ${getTypeString(actionSequence.id)}`, - /Expected 'id' to be a string/); + check( + `actionSequence.id: ${getTypeString(actionSequence.id)}`, + /Expected 'id' to be a string/ + ); action.inputStateMap.clear(); actionSequence.id = undefined; - check(`actionSequence.id: ${getTypeString(actionSequence.id)}`, - /Expected 'id' to be defined/); + check( + `actionSequence.id: ${getTypeString(actionSequence.id)}`, + /Expected 'id' to be defined/ + ); action.inputStateMap.clear(); actionSequence.id = "some_id"; actionSequence.actions = -1; - check(`actionSequence.actions: ${getTypeString(actionSequence.actions)}`, - /Expected 'actionSequence.actions' to be an array/); + check( + `actionSequence.actions: ${getTypeString(actionSequence.actions)}`, + /Expected 'actionSequence.actions' to be an array/ + ); action.inputStateMap.clear(); run_next_test(); }); add_test(function test_processInputSourceActionSequence() { - let actionItem = {type: "pause", duration: 5}; + let actionItem = { type: "pause", duration: 5 }; let actionSequence = { type: "none", id: "some id", actions: [actionItem], }; - let expectedAction = new action.Action(actionSequence.id, "none", actionItem.type); + let expectedAction = new action.Action( + actionSequence.id, + "none", + actionItem.type + ); expectedAction.duration = actionItem.duration; let actions = action.Sequence.fromJSON(actionSequence); equal(actions.length, 1); @@ -380,7 +431,7 @@ add_test(function test_processInputSourceActionSequence() { }); add_test(function test_processInputSourceActionSequencePointer() { - let actionItem = {type: "pointerDown", button: 1}; + let actionItem = { type: "pointerDown", button: 1 }; let actionSequence = { type: "pointer", id: "9", @@ -390,7 +441,10 @@ add_test(function test_processInputSourceActionSequencePointer() { }, }; let expectedAction = new action.Action( - actionSequence.id, actionSequence.type, actionItem.type); + actionSequence.id, + actionSequence.type, + actionItem.type + ); expectedAction.pointerType = actionSequence.parameters.pointerType; expectedAction.button = actionItem.button; let actions = action.Sequence.fromJSON(actionSequence); @@ -401,14 +455,17 @@ add_test(function test_processInputSourceActionSequencePointer() { }); add_test(function test_processInputSourceActionSequenceKey() { - let actionItem = {type: "keyUp", value: "a"}; + let actionItem = { type: "keyUp", value: "a" }; let actionSequence = { type: "key", id: "9", actions: [actionItem], }; let expectedAction = new action.Action( - actionSequence.id, actionSequence.type, actionItem.type); + actionSequence.id, + actionSequence.type, + actionItem.type + ); expectedAction.value = actionItem.value; let actions = action.Sequence.fromJSON(actionSequence); equal(actions.length, 1); @@ -417,10 +474,9 @@ add_test(function test_processInputSourceActionSequenceKey() { run_next_test(); }); - add_test(function test_processInputSourceActionSequenceInputStateMap() { let id = "1"; - let actionItem = {type: "pause", duration: 5000}; + let actionItem = { type: "pause", duration: 5000 }; let actionSequence = { type: "key", id, @@ -428,8 +484,12 @@ add_test(function test_processInputSourceActionSequenceInputStateMap() { }; let wrongInputState = new action.InputState.Null(); action.inputStateMap.set(actionSequence.id, wrongInputState); - checkErrors(/to be mapped to/, action.Sequence.fromJSON, [actionSequence], - `${actionSequence.type} using ${wrongInputState}`); + checkErrors( + /to be mapped to/, + action.Sequence.fromJSON, + [actionSequence], + `${actionSequence.type} using ${wrongInputState}` + ); action.inputStateMap.clear(); let rightInputState = new action.InputState.Key(); action.inputStateMap.set(id, rightInputState); @@ -440,16 +500,18 @@ add_test(function test_processInputSourceActionSequenceInputStateMap() { }); add_test(function test_processPointerActionInputStateMap() { - let actionItem = {type: "pointerDown"}; + let actionItem = { type: "pointerDown" }; let id = "1"; - let parameters = {pointerType: "mouse"}; + let parameters = { pointerType: "mouse" }; let a = new action.Action(id, "pointer", actionItem.type); let wrongInputState = new action.InputState.Key(); action.inputStateMap.set(id, wrongInputState); checkErrors( - /to be mapped to InputState whose type is/, action.processPointerAction, - [id, parameters, a], - `type "pointer" with ${wrongInputState.type} in inputState`); + /to be mapped to InputState whose type is/, + action.processPointerAction, + [id, parameters, a], + `type "pointer" with ${wrongInputState.type} in inputState` + ); action.inputStateMap.clear(); // TODO - uncomment once pen is supported @@ -483,20 +545,32 @@ add_test(function test_createInputState() { equal(state.type, kind.toLowerCase()); } } - Assert.throws(() => new action.InputState.Pointer(), InvalidArgumentError, - "Missing InputState.Pointer constructor arg"); - Assert.throws(() => new action.InputState.Pointer("foo"), InvalidArgumentError, - "Invalid InputState.Pointer constructor arg"); + Assert.throws( + () => new action.InputState.Pointer(), + InvalidArgumentError, + "Missing InputState.Pointer constructor arg" + ); + Assert.throws( + () => new action.InputState.Pointer("foo"), + InvalidArgumentError, + "Invalid InputState.Pointer constructor arg" + ); run_next_test(); }); add_test(function test_extractActionChainValidation() { for (let actions of [-1, "a", undefined, null]) { let message = `actions: ${getTypeString(actions)}`; - Assert.throws(() => action.Chain.fromJSON(actions), - InvalidArgumentError, message); - Assert.throws(() => action.Chain.fromJSON(actions), - /Expected 'actions' to be an array/, message); + Assert.throws( + () => action.Chain.fromJSON(actions), + InvalidArgumentError, + message + ); + Assert.throws( + () => action.Chain.fromJSON(actions), + /Expected 'actions' to be an array/, + message + ); } run_next_test(); }); @@ -507,13 +581,17 @@ add_test(function test_extractActionChainEmpty() { }); add_test(function test_extractActionChain_oneTickOneInput() { - let actionItem = {type: "pause", duration: 5000}; + let actionItem = { type: "pause", duration: 5000 }; let actionSequence = { type: "none", id: "some id", actions: [actionItem], }; - let expectedAction = new action.Action(actionSequence.id, "none", actionItem.type); + let expectedAction = new action.Action( + actionSequence.id, + "none", + actionItem.type + ); expectedAction.duration = actionItem.duration; let actionsByTick = action.Chain.fromJSON([actionSequence]); equal(1, actionsByTick.length); @@ -561,20 +639,29 @@ add_test(function test_extractActionChain_twoAndThreeTicks() { id: "1", actions: keyActionItems, }; - let actionsByTick = action.Chain.fromJSON([keyActionSequence, mouseActionSequence]); + let actionsByTick = action.Chain.fromJSON([ + keyActionSequence, + mouseActionSequence, + ]); // number of ticks is same as longest action sequence equal(keyActionItems.length, actionsByTick.length); equal(2, actionsByTick[0].length); equal(2, actionsByTick[1].length); equal(1, actionsByTick[2].length); - let expectedAction = new action.Action(keyActionSequence.id, "key", keyActionItems[2].type); + let expectedAction = new action.Action( + keyActionSequence.id, + "key", + keyActionItems[2].type + ); expectedAction.value = keyActionItems[2].value; deepEqual(actionsByTick[2][0], expectedAction); action.inputStateMap.clear(); // one empty action sequence - actionsByTick = action.Chain.fromJSON( - [keyActionSequence, {type: "none", id: "some", actions: []}]); + actionsByTick = action.Chain.fromJSON([ + keyActionSequence, + { type: "none", id: "some", actions: [] }, + ]); equal(keyActionItems.length, actionsByTick.length); equal(1, actionsByTick[0].length); action.inputStateMap.clear(); @@ -584,13 +671,13 @@ add_test(function test_extractActionChain_twoAndThreeTicks() { add_test(function test_computeTickDuration() { let expected = 8000; let tickActions = [ - {type: "none", subtype: "pause", duration: 5000}, - {type: "key", subtype: "pause", duration: 1000}, - {type: "pointer", subtype: "pointerMove", duration: 6000}, + { type: "none", subtype: "pause", duration: 5000 }, + { type: "key", subtype: "pause", duration: 1000 }, + { type: "pointer", subtype: "pointerMove", duration: 6000 }, // invalid because keyDown should not have duration, so duration should be ignored. - {type: "key", subtype: "keyDown", duration: 100000}, - {type: "pointer", subtype: "pause", duration: expected}, - {type: "pointer", subtype: "pointerUp"}, + { type: "key", subtype: "keyDown", duration: 100000 }, + { type: "pointer", subtype: "pause", duration: expected }, + { type: "pointer", subtype: "pointerUp" }, ]; equal(expected, action.computeTickDuration(tickActions)); run_next_test(); @@ -604,19 +691,18 @@ add_test(function test_computeTickDuration_empty() { add_test(function test_computeTickDuration_noDurations() { let tickActions = [ // invalid because keyDown should not have duration, so duration should be ignored. - {type: "key", subtype: "keyDown", duration: 100000}, + { type: "key", subtype: "keyDown", duration: 100000 }, // undefined duration permitted - {type: "none", subtype: "pause"}, - {type: "pointer", subtype: "pointerMove"}, - {type: "pointer", subtype: "pointerDown"}, - {type: "key", subtype: "keyUp"}, + { type: "none", subtype: "pause" }, + { type: "pointer", subtype: "pointerMove" }, + { type: "pointer", subtype: "pointerDown" }, + { type: "key", subtype: "keyUp" }, ]; equal(0, action.computeTickDuration(tickActions)); run_next_test(); }); - // helpers function getTypeString(obj) { return Object.prototype.toString.call(obj); diff --git a/testing/marionette/test/unit/test_assert.js b/testing/marionette/test/unit/test_assert.js index b67d704c466c..2ce2ab986244 100644 --- a/testing/marionette/test/unit/test_assert.js +++ b/testing/marionette/test/unit/test_assert.js @@ -5,7 +5,7 @@ "use strict"; /* eslint-disable no-array-constructor, no-new-object */ -const {assert} = ChromeUtils.import("chrome://marionette/content/assert.js"); +const { assert } = ChromeUtils.import("chrome://marionette/content/assert.js"); const { InvalidArgumentError, InvalidSessionIDError, @@ -30,18 +30,24 @@ add_test(function test_acyclic() { cyclic.reference = cyclic; Assert.throws(() => assert.acyclic(cyclic, "", RangeError), RangeError); Assert.throws(() => assert.acyclic(cyclic, "foo"), /JavaScriptError: foo/); - Assert.throws(() => assert.acyclic(cyclic, "bar", RangeError), /RangeError: bar/); + Assert.throws( + () => assert.acyclic(cyclic, "bar", RangeError), + /RangeError: bar/ + ); run_next_test(); }); add_test(function test_session() { - assert.session({sessionID: "foo"}); + assert.session({ sessionID: "foo" }); for (let typ of [null, undefined, ""]) { - Assert.throws(() => assert.session({sessionId: typ}), InvalidSessionIDError); + Assert.throws( + () => assert.session({ sessionId: typ }), + InvalidSessionIDError + ); } - Assert.throws(() => assert.session({sessionId: null}, "custom"), /custom/); + Assert.throws(() => assert.session({ sessionId: null }, "custom"), /custom/); run_next_test(); }); @@ -152,9 +158,9 @@ add_test(function test_string() { }); add_test(function test_open() { - assert.open({closed: false}); + assert.open({ closed: false }); - for (let typ of [null, undefined, {closed: true}]) { + for (let typ of [null, undefined, { closed: true }]) { Assert.throws(() => assert.open(typ), NoSuchWindowError); } @@ -176,12 +182,12 @@ add_test(function test_object() { }); add_test(function test_in() { - assert.in("foo", {foo: 42}); + assert.in("foo", { foo: 42 }); for (let typ of [{}, 42, true, null, undefined]) { Assert.throws(() => assert.in("foo", typ), InvalidArgumentError); } - Assert.throws(() => assert.in("foo", {bar: 42}, "custom"), /custom/); + Assert.throws(() => assert.in("foo", { bar: 42 }, "custom"), /custom/); run_next_test(); }); @@ -201,8 +207,10 @@ add_test(function test_that() { equal(1, assert.that(n => n + 1)(1)); Assert.throws(() => assert.that(() => false)(), InvalidArgumentError); Assert.throws(() => assert.that(val => val)(false), InvalidArgumentError); - Assert.throws(() => assert.that(val => val, "foo", SessionNotCreatedError)(false), - SessionNotCreatedError); + Assert.throws( + () => assert.that(val => val, "foo", SessionNotCreatedError)(false), + SessionNotCreatedError + ); Assert.throws(() => assert.that(() => false, "custom")(), /custom/); diff --git a/testing/marionette/test/unit/test_browser.js b/testing/marionette/test/unit/test_browser.js index 6f7846f51374..3f89cd0b1a05 100644 --- a/testing/marionette/test/unit/test_browser.js +++ b/testing/marionette/test/unit/test_browser.js @@ -1,4 +1,6 @@ -const {Context} = ChromeUtils.import("chrome://marionette/content/browser.js"); +const { Context } = ChromeUtils.import( + "chrome://marionette/content/browser.js" +); add_test(function test_Context() { ok(Context.hasOwnProperty("Chrome")); diff --git a/testing/marionette/test/unit/test_capabilities.js b/testing/marionette/test/unit/test_capabilities.js index 887d40c2c68e..ccbf607135cc 100644 --- a/testing/marionette/test/unit/test_capabilities.js +++ b/testing/marionette/test/unit/test_capabilities.js @@ -4,9 +4,13 @@ "use strict"; -const {Preferences} = ChromeUtils.import("resource://gre/modules/Preferences.jsm"); +const { Preferences } = ChromeUtils.import( + "resource://gre/modules/Preferences.jsm" +); -const {InvalidArgumentError} = ChromeUtils.import("chrome://marionette/content/error.js"); +const { InvalidArgumentError } = ChromeUtils.import( + "chrome://marionette/content/error.js" +); const { Capabilities, PageLoadStrategy, @@ -32,7 +36,7 @@ add_test(function test_Timeouts_toString() { add_test(function test_Timeouts_toJSON() { let ts = new Timeouts(); - deepEqual(ts.toJSON(), {"implicit": 0, "pageLoad": 300000, "script": 30000}); + deepEqual(ts.toJSON(), { implicit: 0, pageLoad: 300000, script: 30000 }); run_next_test(); }); @@ -67,7 +71,10 @@ add_test(function test_Timeouts_fromJSON_unrecognised_field() { add_test(function test_Timeouts_fromJSON_invalid_types() { for (let value of [null, [], {}, false, "10", 2.5]) { - Assert.throws(() => Timeouts.fromJSON({"implicit": value}), /InvalidArgumentError/); + Assert.throws( + () => Timeouts.fromJSON({ implicit: value }), + /InvalidArgumentError/ + ); } run_next_test(); @@ -75,7 +82,10 @@ add_test(function test_Timeouts_fromJSON_invalid_types() { add_test(function test_Timeouts_fromJSON_bounds() { for (let value of [-1, Number.MAX_SAFE_INTEGER + 1]) { - Assert.throws(() => Timeouts.fromJSON({"script": value}), /InvalidArgumentError/); + Assert.throws( + () => Timeouts.fromJSON({ script: value }), + /InvalidArgumentError/ + ); } run_next_test(); @@ -121,8 +131,10 @@ add_test(function test_Proxy_init() { ok(p.init()); equal(Preferences.get("network.proxy.type"), 2); - equal(Preferences.get("network.proxy.autoconfig_url"), - "http://localhost:1234"); + equal( + Preferences.get("network.proxy.autoconfig_url"), + "http://localhost:1234" + ); // direct p = new Proxy(); @@ -187,15 +199,15 @@ add_test(function test_Proxy_toJSON() { p = new Proxy(); p.proxyType = "pac"; p.proxyAutoconfigUrl = "foo"; - deepEqual(p.toJSON(), {proxyType: "pac", proxyAutoconfigUrl: "foo"}); + deepEqual(p.toJSON(), { proxyType: "pac", proxyAutoconfigUrl: "foo" }); // manual proxy p = new Proxy(); p.proxyType = "manual"; - deepEqual(p.toJSON(), {proxyType: "manual"}); + deepEqual(p.toJSON(), { proxyType: "manual" }); for (let proxy of ["ftpProxy", "httpProxy", "sslProxy", "socksProxy"]) { - let expected = {proxyType: "manual"}; + let expected = { proxyType: "manual" }; p = new Proxy(); p.proxyType = "manual"; @@ -232,7 +244,7 @@ add_test(function test_Proxy_toJSON() { p = new Proxy(); p.proxyType = "manual"; p.noProxy = ["2001:db8::1"]; - let expected = {proxyType: "manual", noProxy: "[2001:db8::1]"}; + let expected = { proxyType: "manual", noProxy: "[2001:db8::1]" }; deepEqual(p.toJSON(), expected); run_next_test(); @@ -249,36 +261,49 @@ add_test(function test_Proxy_fromJSON() { // must contain a valid proxyType Assert.throws(() => Proxy.fromJSON({}), /InvalidArgumentError/); - Assert.throws(() => Proxy.fromJSON({proxyType: "foo"}), - /InvalidArgumentError/); + Assert.throws( + () => Proxy.fromJSON({ proxyType: "foo" }), + /InvalidArgumentError/ + ); // autoconfig url for (let url of [true, 42, [], {}]) { - Assert.throws(() => Proxy.fromJSON( - {proxyType: "pac", proxyAutoconfigUrl: url}), /InvalidArgumentError/); + Assert.throws( + () => Proxy.fromJSON({ proxyType: "pac", proxyAutoconfigUrl: url }), + /InvalidArgumentError/ + ); } p = new Proxy(); p.proxyType = "pac"; p.proxyAutoconfigUrl = "foo"; - deepEqual(p, - Proxy.fromJSON({proxyType: "pac", proxyAutoconfigUrl: "foo"})); + deepEqual(p, Proxy.fromJSON({ proxyType: "pac", proxyAutoconfigUrl: "foo" })); // manual proxy p = new Proxy(); p.proxyType = "manual"; - deepEqual(p, Proxy.fromJSON({proxyType: "manual"})); + deepEqual(p, Proxy.fromJSON({ proxyType: "manual" })); for (let proxy of ["httpProxy", "sslProxy", "ftpProxy", "socksProxy"]) { - let manual = {proxyType: "manual"}; + let manual = { proxyType: "manual" }; // invalid hosts - for (let host of [true, 42, [], {}, null, "http://foo", - "foo:-1", "foo:65536", "foo/test", "foo#42", "foo?foo=bar", - "2001:db8::1"]) { + for (let host of [ + true, + 42, + [], + {}, + null, + "http://foo", + "foo:-1", + "foo:65536", + "foo/test", + "foo#42", + "foo?foo=bar", + "2001:db8::1", + ]) { manual[proxy] = host; - Assert.throws(() => Proxy.fromJSON(manual), - /InvalidArgumentError/); + Assert.throws(() => Proxy.fromJSON(manual), /InvalidArgumentError/); } p = new Proxy(); @@ -289,13 +314,13 @@ add_test(function test_Proxy_fromJSON() { } let host_map = { - "foo:1": {hostname: "foo", port: 1}, - "foo:21": {hostname: "foo", port: 21}, - "foo:80": {hostname: "foo", port: 80}, - "foo:443": {hostname: "foo", port: 443}, - "foo:65535": {hostname: "foo", port: 65535}, - "127.0.0.1:42": {hostname: "127.0.0.1", port: 42}, - "[2001:db8::1]:42": {hostname: "2001:db8::1", port: "42"}, + "foo:1": { hostname: "foo", port: 1 }, + "foo:21": { hostname: "foo", port: 21 }, + "foo:80": { hostname: "foo", port: 80 }, + "foo:443": { hostname: "foo", port: 443 }, + "foo:65535": { hostname: "foo", port: 65535 }, + "127.0.0.1:42": { hostname: "127.0.0.1", port: 42 }, + "[2001:db8::1]:42": { hostname: "2001:db8::1", port: "42" }, }; // valid proxy hosts with port @@ -317,8 +342,7 @@ add_test(function test_Proxy_fromJSON() { if (proxy === "socksProxy") { p[`${proxy}Port`] = null; } else { - let default_ports = {"ftpProxy": 21, "httpProxy": 80, - "sslProxy": 443}; + let default_ports = { ftpProxy: 21, httpProxy: 80, sslProxy: 443 }; p[`${proxy}Port`] = default_ports[proxy]; } @@ -328,23 +352,24 @@ add_test(function test_Proxy_fromJSON() { } // missing required socks version - Assert.throws(() => Proxy.fromJSON( - {proxyType: "manual", socksProxy: "foo:1234"}), - /InvalidArgumentError/); + Assert.throws( + () => Proxy.fromJSON({ proxyType: "manual", socksProxy: "foo:1234" }), + /InvalidArgumentError/ + ); // noProxy: invalid settings - for (let noProxy of [true, 42, {}, null, "foo", - [true], [42], [{}], [null]]) { - Assert.throws(() => Proxy.fromJSON( - {proxyType: "manual", noProxy}), - /InvalidArgumentError/); + for (let noProxy of [true, 42, {}, null, "foo", [true], [42], [{}], [null]]) { + Assert.throws( + () => Proxy.fromJSON({ proxyType: "manual", noProxy }), + /InvalidArgumentError/ + ); } // noProxy: valid settings p = new Proxy(); p.proxyType = "manual"; for (let noProxy of [[], ["foo"], ["foo", "bar"], ["127.0.0.1"]]) { - let manual = {proxyType: "manual", "noProxy": noProxy}; + let manual = { proxyType: "manual", noProxy }; p.noProxy = noProxy; deepEqual(p, Proxy.fromJSON(manual)); } @@ -353,7 +378,7 @@ add_test(function test_Proxy_fromJSON() { p = new Proxy(); p.proxyType = "manual"; p.noProxy = ["2001:db8::1"]; - let manual = {proxyType: "manual", "noProxy": ["[2001:db8::1]"]}; + let manual = { proxyType: "manual", noProxy: ["[2001:db8::1]"] }; deepEqual(p, Proxy.fromJSON(manual)); run_next_test(); @@ -422,15 +447,17 @@ add_test(function test_Capabilities_toJSON() { equal(caps.get("moz:buildID"), json["moz:buildID"]); equal(caps.get("moz:processID"), json["moz:processID"]); equal(caps.get("moz:profile"), json["moz:profile"]); - equal(caps.get("moz:useNonSpecCompliantPointerOrigin"), - json["moz:useNonSpecCompliantPointerOrigin"]); + equal( + caps.get("moz:useNonSpecCompliantPointerOrigin"), + json["moz:useNonSpecCompliantPointerOrigin"] + ); equal(caps.get("moz:webdriverClick"), json["moz:webdriverClick"]); run_next_test(); }); add_test(function test_Capabilities_fromJSON() { - const {fromJSON} = Capabilities; + const { fromJSON } = Capabilities; // plain for (let typ of [{}, null, undefined]) { @@ -443,58 +470,83 @@ add_test(function test_Capabilities_fromJSON() { // matching let caps = new Capabilities(); - caps = fromJSON({acceptInsecureCerts: true}); + caps = fromJSON({ acceptInsecureCerts: true }); equal(true, caps.get("acceptInsecureCerts")); - caps = fromJSON({acceptInsecureCerts: false}); + caps = fromJSON({ acceptInsecureCerts: false }); equal(false, caps.get("acceptInsecureCerts")); - Assert.throws(() => fromJSON({acceptInsecureCerts: "foo"}), InvalidArgumentError); + Assert.throws( + () => fromJSON({ acceptInsecureCerts: "foo" }), + InvalidArgumentError + ); for (let strategy of Object.values(PageLoadStrategy)) { - caps = fromJSON({pageLoadStrategy: strategy}); + caps = fromJSON({ pageLoadStrategy: strategy }); equal(strategy, caps.get("pageLoadStrategy")); } - Assert.throws(() => fromJSON({pageLoadStrategy: "foo"}), InvalidArgumentError); - Assert.throws(() => fromJSON({pageLoadStrategy: null}), InvalidArgumentError); + Assert.throws( + () => fromJSON({ pageLoadStrategy: "foo" }), + InvalidArgumentError + ); + Assert.throws( + () => fromJSON({ pageLoadStrategy: null }), + InvalidArgumentError + ); - let proxyConfig = {proxyType: "manual"}; - caps = fromJSON({proxy: proxyConfig}); + let proxyConfig = { proxyType: "manual" }; + caps = fromJSON({ proxy: proxyConfig }); equal("manual", caps.get("proxy").proxyType); - let timeoutsConfig = {implicit: 123}; - caps = fromJSON({timeouts: timeoutsConfig}); + let timeoutsConfig = { implicit: 123 }; + caps = fromJSON({ timeouts: timeoutsConfig }); equal(123, caps.get("timeouts").implicit); - caps = fromJSON({setWindowRect: false}); + caps = fromJSON({ setWindowRect: false }); equal(false, caps.get("setWindowRect")); - Assert.throws(() => fromJSON({setWindowRect: true}), InvalidArgumentError); + Assert.throws(() => fromJSON({ setWindowRect: true }), InvalidArgumentError); - caps = fromJSON({strictFileInteractability: false}); + caps = fromJSON({ strictFileInteractability: false }); equal(false, caps.get("strictFileInteractability")); - caps = fromJSON({strictFileInteractability: true}); + caps = fromJSON({ strictFileInteractability: true }); equal(true, caps.get("strictFileInteractability")); - caps = fromJSON({"moz:accessibilityChecks": true}); + caps = fromJSON({ "moz:accessibilityChecks": true }); equal(true, caps.get("moz:accessibilityChecks")); - caps = fromJSON({"moz:accessibilityChecks": false}); + caps = fromJSON({ "moz:accessibilityChecks": false }); equal(false, caps.get("moz:accessibilityChecks")); - Assert.throws(() => fromJSON({"moz:accessibilityChecks": "foo"}), InvalidArgumentError); - Assert.throws(() => fromJSON({"moz:accessibilityChecks": 1}), InvalidArgumentError); + Assert.throws( + () => fromJSON({ "moz:accessibilityChecks": "foo" }), + InvalidArgumentError + ); + Assert.throws( + () => fromJSON({ "moz:accessibilityChecks": 1 }), + InvalidArgumentError + ); - caps = fromJSON({"moz:useNonSpecCompliantPointerOrigin": false}); + caps = fromJSON({ "moz:useNonSpecCompliantPointerOrigin": false }); equal(false, caps.get("moz:useNonSpecCompliantPointerOrigin")); - caps = fromJSON({"moz:useNonSpecCompliantPointerOrigin": true}); + caps = fromJSON({ "moz:useNonSpecCompliantPointerOrigin": true }); equal(true, caps.get("moz:useNonSpecCompliantPointerOrigin")); - Assert.throws(() => fromJSON({"moz:useNonSpecCompliantPointerOrigin": "foo"}), - InvalidArgumentError); - Assert.throws(() => fromJSON({"moz:useNonSpecCompliantPointerOrigin": 1}), - InvalidArgumentError); + Assert.throws( + () => fromJSON({ "moz:useNonSpecCompliantPointerOrigin": "foo" }), + InvalidArgumentError + ); + Assert.throws( + () => fromJSON({ "moz:useNonSpecCompliantPointerOrigin": 1 }), + InvalidArgumentError + ); - caps = fromJSON({"moz:webdriverClick": true}); + caps = fromJSON({ "moz:webdriverClick": true }); equal(true, caps.get("moz:webdriverClick")); - caps = fromJSON({"moz:webdriverClick": false}); + caps = fromJSON({ "moz:webdriverClick": false }); equal(false, caps.get("moz:webdriverClick")); - Assert.throws(() => fromJSON({"moz:webdriverClick": "foo"}), InvalidArgumentError); - Assert.throws(() => fromJSON({"moz:webdriverClick": 1}), InvalidArgumentError); + Assert.throws( + () => fromJSON({ "moz:webdriverClick": "foo" }), + InvalidArgumentError + ); + Assert.throws( + () => fromJSON({ "moz:webdriverClick": 1 }), + InvalidArgumentError + ); run_next_test(); }); @@ -506,26 +558,26 @@ add_test(function test_marshal() { // drop empty fields deepEqual({}, proxy.toJSON()); proxy.proxyType = "manual"; - deepEqual({proxyType: "manual"}, proxy.toJSON()); + deepEqual({ proxyType: "manual" }, proxy.toJSON()); proxy.proxyType = null; deepEqual({}, proxy.toJSON()); proxy.proxyType = undefined; deepEqual({}, proxy.toJSON()); // iterate over object literals - proxy.proxyType = {foo: "bar"}; - deepEqual({proxyType: {foo: "bar"}}, proxy.toJSON()); + proxy.proxyType = { foo: "bar" }; + deepEqual({ proxyType: { foo: "bar" } }, proxy.toJSON()); // iterate over complex object that implement toJSON proxy.proxyType = new Proxy(); deepEqual({}, proxy.toJSON()); proxy.proxyType.proxyType = "manual"; - deepEqual({proxyType: {proxyType: "manual"}}, proxy.toJSON()); + deepEqual({ proxyType: { proxyType: "manual" } }, proxy.toJSON()); // drop objects with no entries - proxy.proxyType = {foo: {}}; + proxy.proxyType = { foo: {} }; deepEqual({}, proxy.toJSON()); - proxy.proxyType = {foo: new Proxy()}; + proxy.proxyType = { foo: new Proxy() }; deepEqual({}, proxy.toJSON()); run_next_test(); diff --git a/testing/marionette/test/unit/test_cookie.js b/testing/marionette/test/unit/test_cookie.js index a40214fa25e9..689b6c7b89b2 100644 --- a/testing/marionette/test/unit/test_cookie.js +++ b/testing/marionette/test/unit/test_cookie.js @@ -2,14 +2,24 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -const {cookie} = ChromeUtils.import("chrome://marionette/content/cookie.js"); +const { cookie } = ChromeUtils.import("chrome://marionette/content/cookie.js"); /* eslint-disable mozilla/use-chromeutils-generateqi */ cookie.manager = { cookies: [], - add(domain, path, name, value, secure, httpOnly, session, expiry, originAttributes) { + add( + domain, + path, + name, + value, + secure, + httpOnly, + session, + expiry, + originAttributes + ) { if (name === "fail") { throw new Error("An error occurred while adding cookie"); } @@ -30,9 +40,11 @@ cookie.manager = { remove(host, name, path) { for (let i = 0; i < this.cookies.length; ++i) { let candidate = this.cookies[i]; - if (candidate.host === host && - candidate.name === name && - candidate.path === path) { + if ( + candidate.host === host && + candidate.name === name && + candidate.path === path + ) { return this.cookies.splice(i, 1); } } @@ -40,8 +52,9 @@ cookie.manager = { }, getCookiesFromHost(host) { - let hostCookies = this.cookies.filter(c => c.host === host || - c.host === "." + host); + let hostCookies = this.cookies.filter( + c => c.host === host || c.host === "." + host + ); return hostCookies; }, @@ -55,8 +68,14 @@ add_test(function test_fromJSON() { // name and value for (let invalidType of [42, true, [], {}, null, undefined]) { - Assert.throws(() => cookie.fromJSON({name: invalidType}), /Cookie name must be string/); - Assert.throws(() => cookie.fromJSON({name: "foo", value: invalidType}), /Cookie value must be string/); + Assert.throws( + () => cookie.fromJSON({ name: invalidType }), + /Cookie name must be string/ + ); + Assert.throws( + () => cookie.fromJSON({ name: "foo", value: invalidType }), + /Cookie value must be string/ + ); } // domain @@ -66,7 +85,10 @@ add_test(function test_fromJSON() { value: "bar", domain: invalidType, }; - Assert.throws(() => cookie.fromJSON(domainTest), /Cookie domain must be string/); + Assert.throws( + () => cookie.fromJSON(domainTest), + /Cookie domain must be string/ + ); } let domainTest = { name: "foo", @@ -83,7 +105,10 @@ add_test(function test_fromJSON() { value: "bar", path: invalidType, }; - Assert.throws(() => cookie.fromJSON(pathTest), /Cookie path must be string/); + Assert.throws( + () => cookie.fromJSON(pathTest), + /Cookie path must be string/ + ); } // secure @@ -93,7 +118,10 @@ add_test(function test_fromJSON() { value: "bar", secure: invalidType, }; - Assert.throws(() => cookie.fromJSON(secureTest), /Cookie secure flag must be boolean/); + Assert.throws( + () => cookie.fromJSON(secureTest), + /Cookie secure flag must be boolean/ + ); } // httpOnly @@ -103,21 +131,35 @@ add_test(function test_fromJSON() { value: "bar", httpOnly: invalidType, }; - Assert.throws(() => cookie.fromJSON(httpOnlyTest), /Cookie httpOnly flag must be boolean/); + Assert.throws( + () => cookie.fromJSON(httpOnlyTest), + /Cookie httpOnly flag must be boolean/ + ); } // expiry - for (let invalidType of [-1, Number.MAX_SAFE_INTEGER + 1, "foo", true, [], {}, null]) { + for (let invalidType of [ + -1, + Number.MAX_SAFE_INTEGER + 1, + "foo", + true, + [], + {}, + null, + ]) { let expiryTest = { name: "foo", value: "bar", expiry: invalidType, }; - Assert.throws(() => cookie.fromJSON(expiryTest), /Cookie expiry must be a positive integer/); + Assert.throws( + () => cookie.fromJSON(expiryTest), + /Cookie expiry must be a positive integer/ + ); } // bare requirements - let bare = cookie.fromJSON({name: "name", value: "value"}); + let bare = cookie.fromJSON({ name: "name", value: "value" }); equal("name", bare.name); equal("value", bare.value); for (let missing of ["path", "secure", "httpOnly", "session", "expiry"]) { @@ -150,14 +192,17 @@ add_test(function test_add() { for (let invalidType of [42, true, [], {}, null, undefined]) { Assert.throws( - () => cookie.add({name: invalidType}), - /Cookie name must be string/); + () => cookie.add({ name: invalidType }), + /Cookie name must be string/ + ); Assert.throws( - () => cookie.add({name: "name", value: invalidType}), - /Cookie value must be string/); + () => cookie.add({ name: "name", value: invalidType }), + /Cookie value must be string/ + ); Assert.throws( - () => cookie.add({name: "name", value: "value", domain: invalidType}), - /Cookie domain must be string/); + () => cookie.add({ name: "name", value: "value", domain: invalidType }), + /Cookie domain must be string/ + ); } cookie.add({ @@ -180,8 +225,8 @@ add_test(function test_add() { equal(2, cookie.manager.cookies.length); Assert.throws(() => { - let biscuit = {name: "name3", value: "value3", domain: "domain3"}; - cookie.add(biscuit, {restrictToHost: "other domain"}); + let biscuit = { name: "name3", value: "value3", domain: "domain3" }; + cookie.add(biscuit, { restrictToHost: "other domain" }); }, /Cookies may only be set for the current domain/); cookie.add({ @@ -207,7 +252,7 @@ add_test(function test_add() { equal(".domain", cookie.manager.cookies[4].host); Assert.throws(() => { - cookie.add({name: "fail", value: "value6", domain: "domain6"}); + cookie.add({ name: "fail", value: "value6", domain: "domain6" }); }, /UnableToSetCookieError/); run_next_test(); diff --git a/testing/marionette/test/unit/test_dom.js b/testing/marionette/test/unit/test_dom.js index 4c0fa49a51b3..81680efd50c2 100644 --- a/testing/marionette/test/unit/test_dom.js +++ b/testing/marionette/test/unit/test_dom.js @@ -14,7 +14,7 @@ class MessageSender { } sendAsyncMessage(name, data, objects) { - this.sent.push({name, data, objects}); + this.sent.push({ name, data, objects }); } } @@ -60,12 +60,11 @@ add_test(function test_addEventListener() { equal(eventTarget.listeners.click[0], listener); // should have sent a registration message - deepEqual( - ipc.sent[0], { - name: "Marionette:DOM:AddEventListener", - data: {type: "click"}, - objects: undefined, - }); + deepEqual(ipc.sent[0], { + name: "Marionette:DOM:AddEventListener", + data: { type: "click" }, + objects: undefined, + }); run_next_test(); }); @@ -86,17 +85,16 @@ add_test(function test_WebElementEventTarget_addEventListener_once() { let ipc = new MessageSender(); let eventTarget = new WebElementEventTarget(ipc); - eventTarget.addEventListener("click", () => {}, {once: true}); + eventTarget.addEventListener("click", () => {}, { once: true }); equal(eventTarget.listeners.click[0].once, true); - eventTarget.dispatchEvent({type: "click"}); + eventTarget.dispatchEvent({ type: "click" }); equal(eventTarget.listeners.click.length, 0); - deepEqual( - ipc.sent[1], { - name: "Marionette:DOM:RemoveEventListener", - data: {type: "click"}, - objects: undefined, - }); + deepEqual(ipc.sent[1], { + name: "Marionette:DOM:RemoveEventListener", + data: { type: "click" }, + objects: undefined, + }); run_next_test(); }); @@ -131,13 +129,11 @@ add_test(function test_WebElementEventTarget_removeEventListener() { eventTarget.removeEventListener("click", firstListener); equal(eventTarget.listeners.click.length, 0); - deepEqual( - ipc.sent[ipc.sent.length - 1], - { - name: "Marionette:DOM:RemoveEventListener", - data: {type: "click"}, - objects: undefined, - }); + deepEqual(ipc.sent[ipc.sent.length - 1], { + name: "Marionette:DOM:RemoveEventListener", + data: { type: "click" }, + objects: undefined, + }); run_next_test(); }); @@ -147,9 +143,9 @@ add_test(function test_WebElementEventTarget_dispatchEvent() { let eventTarget = new WebElementEventTarget(ipc); let listenerCalled = false; - let listener = () => listenerCalled = true; + let listener = () => (listenerCalled = true); eventTarget.addEventListener("click", listener); - eventTarget.dispatchEvent({type: "click"}); + eventTarget.dispatchEvent({ type: "click" }); ok(listenerCalled); run_next_test(); @@ -168,7 +164,7 @@ add_test(function test_WebElementEventTarget_dispatchEvent_multipleListeners() { eventTarget.addEventListener("click", listenerA); eventTarget.addEventListener("click", listenerA); eventTarget.addEventListener("click", listenerB); - eventTarget.dispatchEvent({type: "click"}); + eventTarget.dispatchEvent({ type: "click" }); equal(clicksA, 1); equal(clicksB, 1); @@ -179,7 +175,9 @@ add_test(function test_ContentEventObserverService_add() { let ipc = new MessageSender(); let win = new Window(); let obs = new ContentEventObserverService( - win, ipc.sendAsyncMessage.bind(ipc)); + win, + ipc.sendAsyncMessage.bind(ipc) + ); equal(obs.events.size, 0); equal(win.events.length, 0); @@ -201,7 +199,9 @@ add_test(function test_ContentEventObserverService_remove() { let ipc = new MessageSender(); let win = new Window(); let obs = new ContentEventObserverService( - win, ipc.sendAsyncMessage.bind(ipc)); + win, + ipc.sendAsyncMessage.bind(ipc) + ); obs.remove("foo"); equal(obs.events.size, 0); @@ -239,7 +239,9 @@ add_test(function test_ContentEventObserverService_clear() { let ipc = new MessageSender(); let win = new Window(); let obs = new ContentEventObserverService( - win, ipc.sendAsyncMessage.bind(ipc)); + win, + ipc.sendAsyncMessage.bind(ipc) + ); obs.clear(); equal(obs.events.size, 0); @@ -262,15 +264,16 @@ add_test(function test_ContentEventObserverService_handleEvent() { let ipc = new MessageSender(); let win = new Window(); let obs = new ContentEventObserverService( - win, ipc.sendAsyncMessage.bind(ipc)); + win, + ipc.sendAsyncMessage.bind(ipc) + ); - obs.handleEvent({type: "click", target: win}); - deepEqual( - ipc.sent[0], { - name: "Marionette:DOM:OnEvent", - data: {type: "click"}, - objects: {"target": win}, - }); + obs.handleEvent({ type: "click", target: win }); + deepEqual(ipc.sent[0], { + name: "Marionette:DOM:OnEvent", + data: { type: "click" }, + objects: { target: win }, + }); run_next_test(); }); diff --git a/testing/marionette/test/unit/test_element.js b/testing/marionette/test/unit/test_element.js index caeb06e647e5..d3759eca177f 100644 --- a/testing/marionette/test/unit/test_element.js +++ b/testing/marionette/test/unit/test_element.js @@ -10,7 +10,9 @@ const { element, WebElement, } = ChromeUtils.import("chrome://marionette/content/element.js"); -const {InvalidArgumentError} = ChromeUtils.import("chrome://marionette/content/error.js"); +const { InvalidArgumentError } = ChromeUtils.import( + "chrome://marionette/content/error.js" +); const SVGNS = "http://www.w3.org/2000/svg"; const XBLNS = "http://www.mozilla.org/xbl"; @@ -27,8 +29,12 @@ class Element { } } - get nodeType() { return 1; } - get ELEMENT_NODE() { return 1; } + get nodeType() { + return 1; + } + get ELEMENT_NODE() { + return 1; + } // this is a severely limited CSS selector // that only supports lists of tag names @@ -46,7 +52,7 @@ class DOMElement extends Element { this.namespaceURI = XHTMLNS; } if (typeof this.ownerDocument == "undefined") { - this.ownerDocument = {designMode: "off"}; + this.ownerDocument = { designMode: "off" }; } if (typeof this.type == "undefined") { this.type = "text"; @@ -56,7 +62,10 @@ class DOMElement extends Element { this.selected = false; } - if (this.localName == "input" && ["checkbox", "radio"].includes(this.type)) { + if ( + this.localName == "input" && + ["checkbox", "radio"].includes(this.type) + ) { this.checked = false; } } @@ -98,14 +107,22 @@ const xulEl = new XULElement("browser"); const xblEl = new XBLElement("framebox"); class WindowProxy { - get parent() { return this; } - get self() { return this; } - toString() { return "[object Window]"; } + get parent() { + return this; + } + get self() { + return this; + } + toString() { + return "[object Window]"; + } } const domWin = new WindowProxy(); -const domFrame = new class extends WindowProxy { - get parent() { return domWin; } -}; +const domFrame = new (class extends WindowProxy { + get parent() { + return domWin; + } +})(); add_test(function test_findClosest() { equal(element.findClosest(domEl, "foo"), null); @@ -119,7 +136,7 @@ add_test(function test_findClosest() { }); add_test(function test_isSelected() { - let checkbox = new DOMElement("input", {type: "checkbox"}); + let checkbox = new DOMElement("input", { type: "checkbox" }); ok(!element.isSelected(checkbox)); checkbox.checked = true; ok(element.isSelected(checkbox)); @@ -203,41 +220,45 @@ add_test(function test_isDOMWindow() { add_test(function test_isReadOnly() { ok(!element.isReadOnly(null)); ok(!element.isReadOnly(domEl)); - ok(!element.isReadOnly(new DOMElement("p", {readOnly: true}))); - ok(element.isReadOnly(new DOMElement("input", {readOnly: true}))); - ok(element.isReadOnly(new DOMElement("textarea", {readOnly: true}))); + ok(!element.isReadOnly(new DOMElement("p", { readOnly: true }))); + ok(element.isReadOnly(new DOMElement("input", { readOnly: true }))); + ok(element.isReadOnly(new DOMElement("textarea", { readOnly: true }))); run_next_test(); }); add_test(function test_isDisabled() { ok(!element.isDisabled(new DOMElement("p"))); - ok(!element.isDisabled(new SVGElement("rect", {disabled: true}))); - ok(!element.isDisabled(new XULElement("browser", {disabled: true}))); + ok(!element.isDisabled(new SVGElement("rect", { disabled: true }))); + ok(!element.isDisabled(new XULElement("browser", { disabled: true }))); - let select = new DOMElement("select", {disabled: true}); + let select = new DOMElement("select", { disabled: true }); let option = new DOMElement("option"); option.parentNode = select; ok(element.isDisabled(option)); - let optgroup = new DOMElement("optgroup", {disabled: true}); + let optgroup = new DOMElement("optgroup", { disabled: true }); option.parentNode = optgroup; optgroup.parentNode = select; select.disabled = false; ok(element.isDisabled(option)); - ok(element.isDisabled(new DOMElement("button", {disabled: true}))); - ok(element.isDisabled(new DOMElement("input", {disabled: true}))); - ok(element.isDisabled(new DOMElement("select", {disabled: true}))); - ok(element.isDisabled(new DOMElement("textarea", {disabled: true}))); + ok(element.isDisabled(new DOMElement("button", { disabled: true }))); + ok(element.isDisabled(new DOMElement("input", { disabled: true }))); + ok(element.isDisabled(new DOMElement("select", { disabled: true }))); + ok(element.isDisabled(new DOMElement("textarea", { disabled: true }))); run_next_test(); }); add_test(function test_isEditingHost() { ok(!element.isEditingHost(null)); - ok(element.isEditingHost(new DOMElement("p", {isContentEditable: true}))); - ok(element.isEditingHost(new DOMElement("p", {ownerDocument: {designMode: "on"}}))); + ok(element.isEditingHost(new DOMElement("p", { isContentEditable: true }))); + ok( + element.isEditingHost( + new DOMElement("p", { ownerDocument: { designMode: "on" } }) + ) + ); run_next_test(); }); @@ -245,26 +266,45 @@ add_test(function test_isEditingHost() { add_test(function test_isEditable() { ok(!element.isEditable(null)); ok(!element.isEditable(domEl)); - ok(!element.isEditable(new DOMElement("textarea", {readOnly: true}))); - ok(!element.isEditable(new DOMElement("textarea", {disabled: true}))); + ok(!element.isEditable(new DOMElement("textarea", { readOnly: true }))); + ok(!element.isEditable(new DOMElement("textarea", { disabled: true }))); - for (let type of ["checkbox", "radio", "hidden", "submit", "button", "image"]) { - ok(!element.isEditable(new DOMElement("input", {type}))); + for (let type of [ + "checkbox", + "radio", + "hidden", + "submit", + "button", + "image", + ]) { + ok(!element.isEditable(new DOMElement("input", { type }))); } - ok(element.isEditable(new DOMElement("input", {type: "text"}))); + ok(element.isEditable(new DOMElement("input", { type: "text" }))); ok(element.isEditable(new DOMElement("input"))); ok(element.isEditable(new DOMElement("textarea"))); - ok(element.isEditable(new DOMElement("p", {ownerDocument: {designMode: "on"}}))); - ok(element.isEditable(new DOMElement("p", {isContentEditable: true}))); + ok( + element.isEditable( + new DOMElement("p", { ownerDocument: { designMode: "on" } }) + ) + ); + ok(element.isEditable(new DOMElement("p", { isContentEditable: true }))); run_next_test(); }); add_test(function test_isMutableFormControlElement() { ok(!element.isMutableFormControl(null)); - ok(!element.isMutableFormControl(new DOMElement("textarea", {readOnly: true}))); - ok(!element.isMutableFormControl(new DOMElement("textarea", {disabled: true}))); + ok( + !element.isMutableFormControl( + new DOMElement("textarea", { readOnly: true }) + ) + ); + ok( + !element.isMutableFormControl( + new DOMElement("textarea", { disabled: true }) + ) + ); const mutableStates = new Set([ "color", @@ -283,14 +323,24 @@ add_test(function test_isMutableFormControlElement() { "week", ]); for (let type of mutableStates) { - ok(element.isMutableFormControl(new DOMElement("input", {type}))); + ok(element.isMutableFormControl(new DOMElement("input", { type }))); } ok(element.isMutableFormControl(new DOMElement("textarea"))); - ok(!element.isMutableFormControl(new DOMElement("input", {type: "hidden"}))); + ok( + !element.isMutableFormControl(new DOMElement("input", { type: "hidden" })) + ); ok(!element.isMutableFormControl(new DOMElement("p"))); - ok(!element.isMutableFormControl(new DOMElement("p", {isContentEditable: true}))); - ok(!element.isMutableFormControl(new DOMElement("p", {ownerDocument: {designMode: "on"}}))); + ok( + !element.isMutableFormControl( + new DOMElement("p", { isContentEditable: true }) + ) + ); + ok( + !element.isMutableFormControl( + new DOMElement("p", { ownerDocument: { designMode: "on" } }) + ) + ); run_next_test(); }); @@ -302,21 +352,48 @@ add_test(function test_coordinates() { equal("number", typeof p.x); equal("number", typeof p.y); - deepEqual({x: 50, y: 50}, element.coordinates(domEl)); - deepEqual({x: 10, y: 10}, element.coordinates(domEl, 10, 10)); - deepEqual({x: -5, y: -5}, element.coordinates(domEl, -5, -5)); + deepEqual({ x: 50, y: 50 }, element.coordinates(domEl)); + deepEqual({ x: 10, y: 10 }, element.coordinates(domEl, 10, 10)); + deepEqual({ x: -5, y: -5 }, element.coordinates(domEl, -5, -5)); Assert.throws(() => element.coordinates(null), /node is null/); - Assert.throws(() => element.coordinates(domEl, "string", undefined), /Offset must be a number/); - Assert.throws(() => element.coordinates(domEl, undefined, "string"), /Offset must be a number/); - Assert.throws(() => element.coordinates(domEl, "string", "string"), /Offset must be a number/); - Assert.throws(() => element.coordinates(domEl, {}, undefined), /Offset must be a number/); - Assert.throws(() => element.coordinates(domEl, undefined, {}), /Offset must be a number/); - Assert.throws(() => element.coordinates(domEl, {}, {}), /Offset must be a number/); - Assert.throws(() => element.coordinates(domEl, [], undefined), /Offset must be a number/); - Assert.throws(() => element.coordinates(domEl, undefined, []), /Offset must be a number/); - Assert.throws(() => element.coordinates(domEl, [], []), /Offset must be a number/); + Assert.throws( + () => element.coordinates(domEl, "string", undefined), + /Offset must be a number/ + ); + Assert.throws( + () => element.coordinates(domEl, undefined, "string"), + /Offset must be a number/ + ); + Assert.throws( + () => element.coordinates(domEl, "string", "string"), + /Offset must be a number/ + ); + Assert.throws( + () => element.coordinates(domEl, {}, undefined), + /Offset must be a number/ + ); + Assert.throws( + () => element.coordinates(domEl, undefined, {}), + /Offset must be a number/ + ); + Assert.throws( + () => element.coordinates(domEl, {}, {}), + /Offset must be a number/ + ); + Assert.throws( + () => element.coordinates(domEl, [], undefined), + /Offset must be a number/ + ); + Assert.throws( + () => element.coordinates(domEl, undefined, []), + /Offset must be a number/ + ); + Assert.throws( + () => element.coordinates(domEl, [], []), + /Offset must be a number/ + ); run_next_test(); }); @@ -358,9 +435,9 @@ add_test(function test_WebElement_from() { }); add_test(function test_WebElement_fromJSON_ContentWebElement() { - const {Identifier} = ContentWebElement; + const { Identifier } = ContentWebElement; - let ref = {[Identifier]: "foo"}; + let ref = { [Identifier]: "foo" }; let webEl = WebElement.fromJSON(ref); ok(webEl instanceof ContentWebElement); equal(webEl.uuid, "foo"); @@ -376,7 +453,7 @@ add_test(function test_WebElement_fromJSON_ContentWebElement() { }); add_test(function test_WebElement_fromJSON_ContentWebWindow() { - let ref = {[ContentWebWindow.Identifier]: "foo"}; + let ref = { [ContentWebWindow.Identifier]: "foo" }; let win = WebElement.fromJSON(ref); ok(win instanceof ContentWebWindow); equal(win.uuid, "foo"); @@ -385,7 +462,7 @@ add_test(function test_WebElement_fromJSON_ContentWebWindow() { }); add_test(function test_WebElement_fromJSON_ContentWebFrame() { - let ref = {[ContentWebFrame.Identifier]: "foo"}; + let ref = { [ContentWebFrame.Identifier]: "foo" }; let frame = WebElement.fromJSON(ref); ok(frame instanceof ContentWebFrame); equal(frame.uuid, "foo"); @@ -394,7 +471,7 @@ add_test(function test_WebElement_fromJSON_ContentWebFrame() { }); add_test(function test_WebElement_fromJSON_ChromeWebElement() { - let ref = {[ChromeWebElement.Identifier]: "foo"}; + let ref = { [ChromeWebElement.Identifier]: "foo" }; let el = WebElement.fromJSON(ref); ok(el instanceof ChromeWebElement); equal(el.uuid, "foo"); @@ -427,10 +504,10 @@ add_test(function test_WebElement_isReference() { ok(!WebElement.isReference(t)); } - ok(WebElement.isReference({[ContentWebElement.Identifier]: "foo"})); - ok(WebElement.isReference({[ContentWebWindow.Identifier]: "foo"})); - ok(WebElement.isReference({[ContentWebFrame.Identifier]: "foo"})); - ok(WebElement.isReference({[ChromeWebElement.Identifier]: "foo"})); + ok(WebElement.isReference({ [ContentWebElement.Identifier]: "foo" })); + ok(WebElement.isReference({ [ContentWebWindow.Identifier]: "foo" })); + ok(WebElement.isReference({ [ContentWebFrame.Identifier]: "foo" })); + ok(WebElement.isReference({ [ChromeWebElement.Identifier]: "foo" })); run_next_test(); }); @@ -441,7 +518,7 @@ add_test(function test_WebElement_generateUUID() { }); add_test(function test_ContentWebElement_toJSON() { - const {Identifier} = ContentWebElement; + const { Identifier } = ContentWebElement; let el = new ContentWebElement("foo"); let json = el.toJSON(); @@ -453,9 +530,9 @@ add_test(function test_ContentWebElement_toJSON() { }); add_test(function test_ContentWebElement_fromJSON() { - const {Identifier} = ContentWebElement; + const { Identifier } = ContentWebElement; - let el = ContentWebElement.fromJSON({[Identifier]: "foo"}); + let el = ContentWebElement.fromJSON({ [Identifier]: "foo" }); ok(el instanceof ContentWebElement); equal(el.uuid, "foo"); @@ -474,7 +551,7 @@ add_test(function test_ContentWebWindow_toJSON() { }); add_test(function test_ContentWebWindow_fromJSON() { - let ref = {[ContentWebWindow.Identifier]: "foo"}; + let ref = { [ContentWebWindow.Identifier]: "foo" }; let win = ContentWebWindow.fromJSON(ref); ok(win instanceof ContentWebWindow); equal(win.uuid, "foo"); @@ -492,7 +569,7 @@ add_test(function test_ContentWebFrame_toJSON() { }); add_test(function test_ContentWebFrame_fromJSON() { - let ref = {[ContentWebFrame.Identifier]: "foo"}; + let ref = { [ContentWebFrame.Identifier]: "foo" }; let win = ContentWebFrame.fromJSON(ref); ok(win instanceof ContentWebFrame); equal(win.uuid, "foo"); @@ -510,7 +587,7 @@ add_test(function test_ChromeWebElement_toJSON() { }); add_test(function test_ChromeWebElement_fromJSON() { - let ref = {[ChromeWebElement.Identifier]: "foo"}; + let ref = { [ChromeWebElement.Identifier]: "foo" }; let win = ChromeWebElement.fromJSON(ref); ok(win instanceof ChromeWebElement); equal(win.uuid, "foo"); diff --git a/testing/marionette/test/unit/test_error.js b/testing/marionette/test/unit/test_error.js index 36a575662d2d..f8abcbf71af8 100644 --- a/testing/marionette/test/unit/test_error.js +++ b/testing/marionette/test/unit/test_error.js @@ -33,7 +33,7 @@ const { } = ChromeUtils.import("chrome://marionette/content/error.js"); function notok(condition) { - ok(!(condition)); + ok(!condition); } add_test(function test_isError() { @@ -105,12 +105,16 @@ add_test(function test_stringify() { equal("", error.stringify()); equal("", error.stringify("foo")); equal("[object Object]", error.stringify({})); - equal("[object Object]\nfoo", error.stringify({stack: "foo"})); + equal("[object Object]\nfoo", error.stringify({ stack: "foo" })); equal("Error: foo", error.stringify(new Error("foo")).split("\n")[0]); - equal("WebDriverError: foo", - error.stringify(new WebDriverError("foo")).split("\n")[0]); - equal("InvalidArgumentError: foo", - error.stringify(new InvalidArgumentError("foo")).split("\n")[0]); + equal( + "WebDriverError: foo", + error.stringify(new WebDriverError("foo")).split("\n")[0] + ); + equal( + "InvalidArgumentError: foo", + error.stringify(new InvalidArgumentError("foo")).split("\n")[0] + ); run_next_test(); }); @@ -144,18 +148,23 @@ add_test(function test_toJSON() { }); add_test(function test_fromJSON() { - Assert.throws(() => WebDriverError.fromJSON({error: "foo"}), - /Not of WebDriverError descent/); - Assert.throws(() => WebDriverError.fromJSON({error: "Error"}), - /Not of WebDriverError descent/); - Assert.throws(() => WebDriverError.fromJSON({}), - /Undeserialisable error type/); - Assert.throws(() => WebDriverError.fromJSON(undefined), - /TypeError/); + Assert.throws( + () => WebDriverError.fromJSON({ error: "foo" }), + /Not of WebDriverError descent/ + ); + Assert.throws( + () => WebDriverError.fromJSON({ error: "Error" }), + /Not of WebDriverError descent/ + ); + Assert.throws( + () => WebDriverError.fromJSON({}), + /Undeserialisable error type/ + ); + Assert.throws(() => WebDriverError.fromJSON(undefined), /TypeError/); // stacks will be different let e1 = new WebDriverError("1"); - let e1r = WebDriverError.fromJSON({error: "webdriver error", message: "1"}); + let e1r = WebDriverError.fromJSON({ error: "webdriver error", message: "1" }); ok(e1r instanceof WebDriverError); equal(e1r.name, e1.name); equal(e1r.status, e1.status); @@ -163,7 +172,10 @@ add_test(function test_fromJSON() { // stacks will be different let e2 = new InvalidArgumentError("2"); - let e2r = WebDriverError.fromJSON({error: "invalid argument", message: "2"}); + let e2r = WebDriverError.fromJSON({ + error: "invalid argument", + message: "2", + }); ok(e2r instanceof WebDriverError); ok(e2r instanceof InvalidArgumentError); equal(e2r.name, e2.name); @@ -171,7 +183,7 @@ add_test(function test_fromJSON() { equal(e2r.message, e2.message); // test stacks - let e3j = {error: "no such element", message: "3", stacktrace: "4"}; + let e3j = { error: "no such element", message: "3", stacktrace: "4" }; let e3r = WebDriverError.fromJSON(e3j); ok(e3r instanceof WebDriverError); ok(e3r instanceof NoSuchElementError); @@ -203,13 +215,13 @@ add_test(function test_WebDriverError() { add_test(function test_ElementClickInterceptedError() { let otherEl = { hasAttribute: attr => attr in otherEl, - getAttribute: attr => attr in otherEl ? otherEl[attr] : null, + getAttribute: attr => (attr in otherEl ? otherEl[attr] : null), nodeType: 1, localName: "a", }; let obscuredEl = { hasAttribute: attr => attr in obscuredEl, - getAttribute: attr => attr in obscuredEl ? obscuredEl[attr] : null, + getAttribute: attr => (attr in obscuredEl ? obscuredEl[attr] : null), nodeType: 1, localName: "b", ownerDocument: { @@ -222,20 +234,24 @@ add_test(function test_ElementClickInterceptedError() { }, }; - let err1 = new ElementClickInterceptedError(obscuredEl, {x: 1, y: 2}); + let err1 = new ElementClickInterceptedError(obscuredEl, { x: 1, y: 2 }); equal("ElementClickInterceptedError", err1.name); - equal("Element is not clickable at point (1,2) " + + equal( + "Element is not clickable at point (1,2) " + "because another element obscures it", - err1.message); + err1.message + ); equal("element click intercepted", err1.status); ok(err1 instanceof WebDriverError); obscuredEl.style.pointerEvents = "none"; - let err2 = new ElementClickInterceptedError(obscuredEl, {x: 1, y: 2}); - equal("Element is not clickable at point (1,2) " + + let err2 = new ElementClickInterceptedError(obscuredEl, { x: 1, y: 2 }); + equal( + "Element is not clickable at point (1,2) " + "because it does not have pointer events enabled, " + "and element would receive the click instead", - err2.message); + err2.message + ); run_next_test(); }); diff --git a/testing/marionette/test/unit/test_evaluate.js b/testing/marionette/test/unit/test_evaluate.js index 2eafc7db91c7..3ee6f4f4da51 100644 --- a/testing/marionette/test/unit/test_evaluate.js +++ b/testing/marionette/test/unit/test_evaluate.js @@ -1,5 +1,9 @@ -const {element, WebElement} = ChromeUtils.import("chrome://marionette/content/element.js"); -const {evaluate} = ChromeUtils.import("chrome://marionette/content/evaluate.js"); +const { element, WebElement } = ChromeUtils.import( + "chrome://marionette/content/element.js" +); +const { evaluate } = ChromeUtils.import( + "chrome://marionette/content/evaluate.js" +); const SVGNS = "http://www.w3.org/2000/svg"; const XBLNS = "http://www.mozilla.org/xbl"; @@ -16,8 +20,12 @@ class Element { } } - get nodeType() { return 1; } - get ELEMENT_NODE() { return 1; } + get nodeType() { + return 1; + } + get ELEMENT_NODE() { + return 1; + } } class DOMElement extends Element { @@ -75,17 +83,34 @@ add_test(function test_toJSON_types() { ok(evaluate.toJSON(xblEl, seenEls) instanceof WebElement); // toJSON - equal("foo", evaluate.toJSON({toJSON() { return "foo"; }})); + equal( + "foo", + evaluate.toJSON({ + toJSON() { + return "foo"; + }, + }) + ); // arbitrary object - deepEqual({foo: "bar"}, evaluate.toJSON({foo: "bar"})); + deepEqual({ foo: "bar" }, evaluate.toJSON({ foo: "bar" })); run_next_test(); }); - add_test(function test_toJSON_sequences() { - let input = [null, true, [], domEl, {toJSON() { return "foo"; }}, {bar: "baz"}]; + let input = [ + null, + true, + [], + domEl, + { + toJSON() { + return "foo"; + }, + }, + { bar: "baz" }, + ]; let actual = evaluate.toJSON(input, seenEls); equal(null, actual[0]); @@ -93,19 +118,23 @@ add_test(function test_toJSON_sequences() { deepEqual([], actual[2]); ok(actual[3] instanceof WebElement); equal("foo", actual[4]); - deepEqual({bar: "baz"}, actual[5]); + deepEqual({ bar: "baz" }, actual[5]); run_next_test(); }); add_test(function test_toJSON_objects() { let input = { - "null": null, - "boolean": true, - "array": [], - "webElement": domEl, - "toJSON": {toJSON() { return "foo"; }}, - "object": {"bar": "baz"}, + null: null, + boolean: true, + array: [], + webElement: domEl, + toJSON: { + toJSON() { + return "foo"; + }, + }, + object: { bar: "baz" }, }; let actual = evaluate.toJSON(input, seenEls); @@ -114,7 +143,7 @@ add_test(function test_toJSON_objects() { deepEqual([], actual.array); ok(actual.webElement instanceof WebElement); equal("foo", actual.toJSON); - deepEqual({"bar": "baz"}, actual.object); + deepEqual({ bar: "baz" }, actual.object); run_next_test(); }); @@ -146,7 +175,7 @@ add_test(function test_isCyclic_array() { add_test(function test_isCyclic_arrayInObject() { let arr = []; arr.push(arr); - ok(evaluate.isCyclic({arr})); + ok(evaluate.isCyclic({ arr })); run_next_test(); }); diff --git a/testing/marionette/test/unit/test_format.js b/testing/marionette/test/unit/test_format.js index 30b00921c856..7cce50a23126 100644 --- a/testing/marionette/test/unit/test_format.js +++ b/testing/marionette/test/unit/test_format.js @@ -2,20 +2,22 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -const {pprint, truncate} = ChromeUtils.import("chrome://marionette/content/format.js"); +const { pprint, truncate } = ChromeUtils.import( + "chrome://marionette/content/format.js" +); const MAX_STRING_LENGTH = 250; const HALF = "x".repeat(MAX_STRING_LENGTH / 2); add_test(function test_pprint() { - equal('[object Object] {"foo":"bar"}', pprint`${{foo: "bar"}}`); + equal('[object Object] {"foo":"bar"}', pprint`${{ foo: "bar" }}`); equal("[object Number] 42", pprint`${42}`); equal("[object Boolean] true", pprint`${true}`); equal("[object Undefined] undefined", pprint`${undefined}`); equal("[object Null] null", pprint`${null}`); - let complexObj = {toJSON: () => "foo"}; + let complexObj = { toJSON: () => "foo" }; equal('[object Object] "foo"', pprint`${complexObj}`); let cyclic = {}; @@ -24,7 +26,7 @@ add_test(function test_pprint() { let el = { hasAttribute: attr => attr in el, - getAttribute: attr => attr in el ? el[attr] : null, + getAttribute: attr => (attr in el ? el[attr] : null), nodeType: 1, localName: "input", id: "foo", @@ -34,8 +36,10 @@ add_test(function test_pprint() { src: "s", type: "t", }; - equal('', - pprint`${el}`); + equal( + '', + pprint`${el}` + ); run_next_test(); }); @@ -75,25 +79,38 @@ add_test(function test_truncate_string() { add_test(function test_truncate_array() { equal(truncate`${["foo"]}`, JSON.stringify(["foo"])); equal(truncate`${"foo"} ${["bar"]}`, `foo ${JSON.stringify(["bar"])}`); - equal(truncate`${["x".repeat(260)]}`, JSON.stringify([`${HALF} ... ${HALF}`])); + equal( + truncate`${["x".repeat(260)]}`, + JSON.stringify([`${HALF} ... ${HALF}`]) + ); run_next_test(); }); add_test(function test_truncate_object() { equal(truncate`${{}}`, JSON.stringify({})); - equal(truncate`${{foo: "bar"}}`, JSON.stringify({foo: "bar"})); - equal(truncate`${{foo: "x".repeat(260)}}`, JSON.stringify({foo: `${HALF} ... ${HALF}`})); - equal(truncate`${{foo: ["bar"]}}`, JSON.stringify({foo: ["bar"]})); - equal(truncate`${{foo: ["bar", {baz: 42}]}}`, JSON.stringify({foo: ["bar", {baz: 42}]})); + equal(truncate`${{ foo: "bar" }}`, JSON.stringify({ foo: "bar" })); + equal( + truncate`${{ foo: "x".repeat(260) }}`, + JSON.stringify({ foo: `${HALF} ... ${HALF}` }) + ); + equal(truncate`${{ foo: ["bar"] }}`, JSON.stringify({ foo: ["bar"] })); + equal( + truncate`${{ foo: ["bar", { baz: 42 }] }}`, + JSON.stringify({ foo: ["bar", { baz: 42 }] }) + ); let complex = { - toString() { return "hello world"; }, + toString() { + return "hello world"; + }, }; equal(truncate`${complex}`, "hello world"); let longComplex = { - toString() { return "x".repeat(260); }, + toString() { + return "x".repeat(260); + }, }; equal(truncate`${longComplex}`, `${HALF} ... ${HALF}`); diff --git a/testing/marionette/test/unit/test_message.js b/testing/marionette/test/unit/test_message.js index 5371939edd25..a1164598508f 100644 --- a/testing/marionette/test/unit/test_message.js +++ b/testing/marionette/test/unit/test_message.js @@ -2,11 +2,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -const { - InvalidArgumentError, - WebDriverError, -} = ChromeUtils.import("chrome://marionette/content/error.js"); -const {Command, Message, Response} = ChromeUtils.import("chrome://marionette/content/message.js"); +const { InvalidArgumentError, WebDriverError } = ChromeUtils.import( + "chrome://marionette/content/error.js" +); +const { Command, Message, Response } = ChromeUtils.import( + "chrome://marionette/content/message.js" +); add_test(function test_Message_Origin() { equal(0, Message.Origin.Client); @@ -22,17 +23,19 @@ add_test(function test_Message_fromPacket() { ok(Message.fromPacket(cmd.toPacket()) instanceof Command); ok(Message.fromPacket(resp.toPacket()) instanceof Response); - Assert.throws(() => Message.fromPacket([3, 4, 5, 6]), - /Unrecognised message type in packet/); + Assert.throws( + () => Message.fromPacket([3, 4, 5, 6]), + /Unrecognised message type in packet/ + ); run_next_test(); }); add_test(function test_Command() { - let cmd = new Command(42, "foo", {bar: "baz"}); + let cmd = new Command(42, "foo", { bar: "baz" }); equal(42, cmd.id); equal("foo", cmd.name); - deepEqual({bar: "baz"}, cmd.parameters); + deepEqual({ bar: "baz" }, cmd.parameters); equal(null, cmd.onerror); equal(null, cmd.onresult); equal(Message.Origin.Client, cmd.origin); @@ -46,8 +49,8 @@ add_test(function test_Command_onresponse() { let onresultOk = false; let cmd = new Command(7, "foo"); - cmd.onerror = () => onerrorOk = true; - cmd.onresult = () => onresultOk = true; + cmd.onerror = () => (onerrorOk = true); + cmd.onresult = () => (onresultOk = true); let errorResp = new Response(8, () => {}); errorResp.error = new WebDriverError("foo"); @@ -66,7 +69,7 @@ add_test(function test_Command_onresponse() { }); add_test(function test_Command_ctor() { - let cmd = new Command(42, "bar", {bar: "baz"}); + let cmd = new Command(42, "bar", { bar: "baz" }); let msg = cmd.toPacket(); equal(Command.Type, msg[0]); @@ -78,14 +81,14 @@ add_test(function test_Command_ctor() { }); add_test(function test_Command_toString() { - let cmd = new Command(42, "foo", {bar: "baz"}); + let cmd = new Command(42, "foo", { bar: "baz" }); equal(JSON.stringify(cmd.toPacket()), cmd.toString()); run_next_test(); }); add_test(function test_Command_fromPacket() { - let c1 = new Command(42, "foo", {bar: "baz"}); + let c1 = new Command(42, "foo", { bar: "baz" }); let msg = c1.toPacket(); let c2 = Command.fromPacket(msg); @@ -94,14 +97,32 @@ add_test(function test_Command_fromPacket() { equal(c1.name, c2.name); equal(c1.parameters, c2.parameters); - Assert.throws(() => Command.fromPacket([null, 2, "foo", {}]), /InvalidArgumentError/); - Assert.throws(() => Command.fromPacket([1, 2, "foo", {}]), /InvalidArgumentError/); - Assert.throws(() => Command.fromPacket([0, null, "foo", {}]), /InvalidArgumentError/); - Assert.throws(() => Command.fromPacket([0, 2, null, {}]), /InvalidArgumentError/); - Assert.throws(() => Command.fromPacket([0, 2, "foo", false]), /InvalidArgumentError/); + Assert.throws( + () => Command.fromPacket([null, 2, "foo", {}]), + /InvalidArgumentError/ + ); + Assert.throws( + () => Command.fromPacket([1, 2, "foo", {}]), + /InvalidArgumentError/ + ); + Assert.throws( + () => Command.fromPacket([0, null, "foo", {}]), + /InvalidArgumentError/ + ); + Assert.throws( + () => Command.fromPacket([0, 2, null, {}]), + /InvalidArgumentError/ + ); + Assert.throws( + () => Command.fromPacket([0, 2, "foo", false]), + /InvalidArgumentError/ + ); let nullParams = Command.fromPacket([0, 2, "foo", null]); - equal("[object Object]", Object.prototype.toString.call(nullParams.parameters)); + equal( + "[object Object]", + Object.prototype.toString.call(nullParams.parameters) + ); run_next_test(); }); @@ -127,7 +148,7 @@ add_test(function test_Response_ctor() { add_test(function test_Response_sendConditionally() { let fired = false; - let resp = new Response(42, () => fired = true); + let resp = new Response(42, () => (fired = true)); resp.sendConditionally(() => false); equal(false, resp.sent); equal(false, fired); @@ -140,7 +161,7 @@ add_test(function test_Response_sendConditionally() { add_test(function test_Response_send() { let fired = false; - let resp = new Response(42, () => fired = true); + let resp = new Response(42, () => (fired = true)); resp.send(); equal(true, resp.sent); equal(true, fired); @@ -231,10 +252,22 @@ add_test(function test_Response_fromPacket() { equal(r1.error, r2.error); equal(r1.body, r2.body); - Assert.throws(() => Response.fromPacket([null, 2, "foo", {}]), InvalidArgumentError); - Assert.throws(() => Response.fromPacket([0, 2, "foo", {}]), InvalidArgumentError); - Assert.throws(() => Response.fromPacket([1, null, "foo", {}]), InvalidArgumentError); - Assert.throws(() => Response.fromPacket([1, 2, null, {}]), InvalidArgumentError); + Assert.throws( + () => Response.fromPacket([null, 2, "foo", {}]), + InvalidArgumentError + ); + Assert.throws( + () => Response.fromPacket([0, 2, "foo", {}]), + InvalidArgumentError + ); + Assert.throws( + () => Response.fromPacket([1, null, "foo", {}]), + InvalidArgumentError + ); + Assert.throws( + () => Response.fromPacket([1, 2, null, {}]), + InvalidArgumentError + ); Response.fromPacket([1, 2, "foo", null]); run_next_test(); diff --git a/testing/marionette/test/unit/test_modal.js b/testing/marionette/test/unit/test_modal.js index 248adaec3f28..deb9d9d564cb 100644 --- a/testing/marionette/test/unit/test_modal.js +++ b/testing/marionette/test/unit/test_modal.js @@ -4,8 +4,10 @@ "use strict"; -const {InvalidArgumentError} = ChromeUtils.import("chrome://marionette/content/error.js"); -const {modal} = ChromeUtils.import("chrome://marionette/content/modal.js"); +const { InvalidArgumentError } = ChromeUtils.import( + "chrome://marionette/content/error.js" +); +const { modal } = ChromeUtils.import("chrome://marionette/content/modal.js"); const mockModalDialog = { opener: { @@ -57,7 +59,11 @@ add_test(function test_registerDialogClosedEventHandler() { let observer = new modal.DialogObserver(); let mockChromeWindow = { addEventListener(event, cb) { - equal(event, "DOMModalDialogClosed", "registered event for closing modal"); + equal( + event, + "DOMModalDialogClosed", + "registered event for closing modal" + ); equal(cb, observer, "set itself as handler"); run_next_test(); }, @@ -71,8 +77,16 @@ add_test(function test_handleCallbackOpenModalDialog() { observer.add((action, target, win) => { equal(action, modal.ACTION_OPENED, "'opened' action has been passed"); - equal(target.get(), mockModalDialog, "weak reference has been created for target"); - equal(win, mockModalDialog.opener.ownerGlobal, "chrome window has been passed"); + equal( + target.get(), + mockModalDialog, + "weak reference has been created for target" + ); + equal( + win, + mockModalDialog.opener.ownerGlobal, + "chrome window has been passed" + ); run_next_test(); }); observer.observe(mockModalDialog, "common-dialog-loaded"); @@ -83,11 +97,22 @@ add_test(function test_handleCallbackCloseModalDialog() { observer.add((action, target, win) => { equal(action, modal.ACTION_CLOSED, "'closed' action has been passed"); - equal(target.get(), mockModalDialog, "weak reference has been created for target"); - equal(win, mockModalDialog.opener.ownerGlobal, "chrome window has been passed"); + equal( + target.get(), + mockModalDialog, + "weak reference has been created for target" + ); + equal( + win, + mockModalDialog.opener.ownerGlobal, + "chrome window has been passed" + ); run_next_test(); }); - observer.handleEvent({type: "DOMModalDialogClosed", target: mockModalDialog}); + observer.handleEvent({ + type: "DOMModalDialogClosed", + target: mockModalDialog, + }); }); add_test(function test_handleCallbackOpenTabModalDialog() { @@ -95,7 +120,11 @@ add_test(function test_handleCallbackOpenTabModalDialog() { observer.add((action, target, win) => { equal(action, modal.ACTION_OPENED, "'opened' action has been passed"); - equal(target.get(), mockTabModalDialog, "weak reference has been created for target"); + equal( + target.get(), + mockTabModalDialog, + "weak reference has been created for target" + ); equal(win, mockTabModalDialog.ownerGlobal, "chrome window has been passed"); run_next_test(); }); @@ -107,9 +136,16 @@ add_test(function test_handleCallbackCloseTabModalDialog() { observer.add((action, target, win) => { equal(action, modal.ACTION_CLOSED, "'closed' action has been passed"); - equal(target.get(), mockTabModalDialog, "weak reference has been created for target"); + equal( + target.get(), + mockTabModalDialog, + "weak reference has been created for target" + ); equal(win, mockTabModalDialog.ownerGlobal, "chrome window has been passed"); run_next_test(); }); - observer.handleEvent({type: "DOMModalDialogClosed", target: mockTabModalDialog}); + observer.handleEvent({ + type: "DOMModalDialogClosed", + target: mockTabModalDialog, + }); }); diff --git a/testing/marionette/test/unit/test_navigate.js b/testing/marionette/test/unit/test_navigate.js index 2fefead0833c..8c0d677258d7 100644 --- a/testing/marionette/test/unit/test_navigate.js +++ b/testing/marionette/test/unit/test_navigate.js @@ -2,11 +2,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -const {navigate} = ChromeUtils.import("chrome://marionette/content/navigate.js"); +const { navigate } = ChromeUtils.import( + "chrome://marionette/content/navigate.js" +); add_test(function test_isLoadEventExpected() { - Assert.throws(() => navigate.isLoadEventExpected(undefined), - /Expected at least one URL/); + Assert.throws( + () => navigate.isLoadEventExpected(undefined), + /Expected at least one URL/ + ); equal(true, navigate.isLoadEventExpected("http://a/")); equal(true, navigate.isLoadEventExpected("http://a/", "http://a/")); @@ -16,7 +20,10 @@ add_test(function test_isLoadEventExpected() { equal(true, navigate.isLoadEventExpected("http://a/#a", "http://a/#A")); equal(false, navigate.isLoadEventExpected("http://a/#a", "http://a/#a")); - equal(false, navigate.isLoadEventExpected("http://a/", "javascript:whatever")); + equal( + false, + navigate.isLoadEventExpected("http://a/", "javascript:whatever") + ); run_next_test(); }); diff --git a/testing/marionette/test/unit/test_prefs.js b/testing/marionette/test/unit/test_prefs.js index 43e104787213..4af4e95b31f1 100644 --- a/testing/marionette/test/unit/test_prefs.js +++ b/testing/marionette/test/unit/test_prefs.js @@ -4,18 +4,23 @@ "use strict"; -const {Log} = ChromeUtils.import("resource://gre/modules/Log.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { Log } = ChromeUtils.import("resource://gre/modules/Log.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); XPCOMUtils.defineLazyServiceGetter( - this, "env", "@mozilla.org/process/environment;1", "nsIEnvironment"); + this, + "env", + "@mozilla.org/process/environment;1", + "nsIEnvironment" +); -const { - Branch, - EnvironmentPrefs, - MarionettePrefs, -} = ChromeUtils.import("chrome://marionette/content/prefs.js", null); +const { Branch, EnvironmentPrefs, MarionettePrefs } = ChromeUtils.import( + "chrome://marionette/content/prefs.js", + null +); function reset() { Services.prefs.setBoolPref("test.bool", false); diff --git a/testing/marionette/test/unit/test_sync.js b/testing/marionette/test/unit/test_sync.js index 5d7dc6a66cb0..070e4d551236 100644 --- a/testing/marionette/test/unit/test_sync.js +++ b/testing/marionette/test/unit/test_sync.js @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { DebounceCallback, @@ -121,7 +121,9 @@ add_test(function test_executeSoon_callback() { } let a; - sync.executeSoon(() => { a = 1; }); + sync.executeSoon(() => { + a = 1; + }); executeSoon(() => equal(1, a)); run_next_test(); @@ -139,13 +141,13 @@ add_test(function test_PollPromise_funcTypes() { add_test(function test_PollPromise_timeoutTypes() { for (let timeout of ["foo", true, [], {}]) { - Assert.throws(() => new PollPromise(() => {}, {timeout}), /TypeError/); + Assert.throws(() => new PollPromise(() => {}, { timeout }), /TypeError/); } for (let timeout of [1.2, -1]) { - Assert.throws(() => new PollPromise(() => {}, {timeout}), /RangeError/); + Assert.throws(() => new PollPromise(() => {}, { timeout }), /RangeError/); } for (let timeout of [null, undefined, 42]) { - new PollPromise(resolve => resolve(1), {timeout}); + new PollPromise(resolve => resolve(1), { timeout }); } run_next_test(); @@ -153,12 +155,12 @@ add_test(function test_PollPromise_timeoutTypes() { add_test(function test_PollPromise_intervalTypes() { for (let interval of ["foo", null, true, [], {}]) { - Assert.throws(() => new PollPromise(() => {}, {interval}), /TypeError/); + Assert.throws(() => new PollPromise(() => {}, { interval }), /TypeError/); } for (let interval of [1.2, -1]) { - Assert.throws(() => new PollPromise(() => {}, {interval}), /RangeError/); + Assert.throws(() => new PollPromise(() => {}, { interval }), /RangeError/); } - new PollPromise(() => {}, {interval: 42}); + new PollPromise(() => {}, { interval: 42 }); run_next_test(); }); @@ -197,33 +199,42 @@ add_task(async function test_PollPromise_zeroTimeout() { // run at least once when timeout is 0 let nevals = 0; let start = new Date().getTime(); - await new PollPromise((resolve, reject) => { - ++nevals; - reject(); - }, {timeout: 0}); + await new PollPromise( + (resolve, reject) => { + ++nevals; + reject(); + }, + { timeout: 0 } + ); let end = new Date().getTime(); equal(1, nevals); - less((end - start), 500); + less(end - start, 500); }); add_task(async function test_PollPromise_timeoutElapse() { let nevals = 0; let start = new Date().getTime(); - await new PollPromise((resolve, reject) => { - ++nevals; - reject(); - }, {timeout: 100}); + await new PollPromise( + (resolve, reject) => { + ++nevals; + reject(); + }, + { timeout: 100 } + ); let end = new Date().getTime(); lessOrEqual(nevals, 11); - greaterOrEqual((end - start), 100); + greaterOrEqual(end - start, 100); }); add_task(async function test_PollPromise_interval() { let nevals = 0; - await new PollPromise((resolve, reject) => { - ++nevals; - reject(); - }, {timeout: 100, interval: 100}); + await new PollPromise( + (resolve, reject) => { + ++nevals; + reject(); + }, + { timeout: 100, interval: 100 } + ); equal(2, nevals); }); @@ -232,19 +243,27 @@ add_test(function test_TimedPromise_funcTypes() { Assert.throws(() => new TimedPromise(type), /TypeError/); } new TimedPromise(resolve => resolve()); - new TimedPromise(function(resolve) { resolve(); }); + new TimedPromise(function(resolve) { + resolve(); + }); run_next_test(); }); add_test(function test_TimedPromise_timeoutTypes() { for (let timeout of ["foo", null, true, [], {}]) { - Assert.throws(() => new TimedPromise(resolve => resolve(), {timeout}), /TypeError/); + Assert.throws( + () => new TimedPromise(resolve => resolve(), { timeout }), + /TypeError/ + ); } for (let timeout of [1.2, -1]) { - Assert.throws(() => new TimedPromise(resolve => resolve(), {timeout}), /RangeError/); + Assert.throws( + () => new TimedPromise(resolve => resolve(), { timeout }), + /RangeError/ + ); } - new TimedPromise(resolve => resolve(), {timeout: 42}); + new TimedPromise(resolve => resolve(), { timeout: 42 }); run_next_test(); }); @@ -275,10 +294,16 @@ add_test(function test_DebounceCallback_constructor() { Assert.throws(() => new DebounceCallback(cb), /TypeError/); } for (let timeout of ["foo", true, [], {}, () => {}]) { - Assert.throws(() => new DebounceCallback(() => {}, {timeout}), /TypeError/); + Assert.throws( + () => new DebounceCallback(() => {}, { timeout }), + /TypeError/ + ); } for (let timeout of [-1, 2.3, NaN]) { - Assert.throws(() => new DebounceCallback(() => {}, {timeout}), /RangeError/); + Assert.throws( + () => new DebounceCallback(() => {}, { timeout }), + /RangeError/ + ); } run_next_test(); @@ -326,15 +351,17 @@ add_task(async function test_waitForEvent_captureTypes() { let element = new MockElement(); for (let capture of ["foo", 42, [], {}]) { - Assert.throws(() => waitForEvent( - element, "click", {capture}), /TypeError/); + Assert.throws( + () => waitForEvent(element, "click", { capture }), + /TypeError/ + ); } for (let capture of [null, undefined, false, true]) { - let expected_capture = (capture == null) ? false : capture; + let expected_capture = capture == null ? false : capture; element = new MockElement(); - let clicked = waitForEvent(element, "click", {capture}); + let clicked = waitForEvent(element, "click", { capture }); element.click(); let event = await clicked; equal(element, event.target); @@ -346,17 +373,19 @@ add_task(async function test_waitForEvent_checkFnTypes() { let element = new MockElement(); for (let checkFn of ["foo", 42, true, [], {}]) { - Assert.throws(() => waitForEvent( - element, "click", {checkFn}), /TypeError/); + Assert.throws( + () => waitForEvent(element, "click", { checkFn }), + /TypeError/ + ); } let count; for (let checkFn of [null, undefined, event => count++ > 0]) { - let expected_count = (checkFn == null) ? 0 : 2; + let expected_count = checkFn == null ? 0 : 2; count = 0; element = new MockElement(); - let clicked = waitForEvent(element, "click", {checkFn}); + let clicked = waitForEvent(element, "click", { checkFn }); element.click(); element.click(); let event = await clicked; @@ -369,15 +398,17 @@ add_task(async function test_waitForEvent_wantsUntrustedTypes() { let element = new MockElement(); for (let wantsUntrusted of ["foo", 42, [], {}]) { - Assert.throws(() => waitForEvent( - element, "click", {wantsUntrusted}), /TypeError/); + Assert.throws( + () => waitForEvent(element, "click", { wantsUntrusted }), + /TypeError/ + ); } for (let wantsUntrusted of [null, undefined, false, true]) { - let expected_untrusted = (wantsUntrusted == null) ? false : wantsUntrusted; + let expected_untrusted = wantsUntrusted == null ? false : wantsUntrusted; element = new MockElement(); - let clicked = waitForEvent(element, "click", {wantsUntrusted}); + let clicked = waitForEvent(element, "click", { wantsUntrusted }); element.click(); let event = await clicked; equal(element, event.target); @@ -396,7 +427,7 @@ add_task(async function test_waitForMessage_messageManagerAndMessageTypes() { Assert.throws(() => waitForEvent(messageManager, message), /TypeError/); } - let data = {"foo": "bar"}; + let data = { foo: "bar" }; let sent = waitForMessage(messageManager, "message"); messageManager.send("message", data); equal(data, await sent); @@ -406,18 +437,20 @@ add_task(async function test_waitForMessage_checkFnTypes() { let messageManager = new MessageManager(); for (let checkFn of ["foo", 42, true, [], {}]) { - Assert.throws(() => waitForMessage( - messageManager, "message", {checkFn}), /TypeError/); + Assert.throws( + () => waitForMessage(messageManager, "message", { checkFn }), + /TypeError/ + ); } - let data1 = {"fo": "bar"}; - let data2 = {"foo": "bar"}; + let data1 = { fo: "bar" }; + let data2 = { foo: "bar" }; for (let checkFn of [null, undefined, msg => "foo" in msg.data]) { - let expected_data = (checkFn == null) ? data1 : data2; + let expected_data = checkFn == null ? data1 : data2; messageManager = new MessageManager(); - let sent = waitForMessage(messageManager, "message", {checkFn}); + let sent = waitForMessage(messageManager, "message", { checkFn }); messageManager.send("message", data1); messageManager.send("message", data2); equal(expected_data, await sent); @@ -429,7 +462,7 @@ add_task(async function test_waitForObserverTopic_topicTypes() { Assert.throws(() => waitForObserverTopic(topic), /TypeError/); } - let data = {"foo": "bar"}; + let data = { foo: "bar" }; let sent = waitForObserverTopic("message"); Services.obs.notifyObservers(this, "message", data); let result = await sent; @@ -439,15 +472,17 @@ add_task(async function test_waitForObserverTopic_topicTypes() { add_task(async function test_waitForObserverTopic_checkFnTypes() { for (let checkFn of ["foo", 42, true, [], {}]) { - Assert.throws(() => waitForObserverTopic( - "message", {checkFn}), /TypeError/); + Assert.throws( + () => waitForObserverTopic("message", { checkFn }), + /TypeError/ + ); } - let data1 = {"fo": "bar"}; - let data2 = {"foo": "bar"}; + let data1 = { fo: "bar" }; + let data2 = { foo: "bar" }; for (let checkFn of [null, undefined, (subject, data) => data == data2]) { - let expected_data = (checkFn == null) ? data1 : data2; + let expected_data = checkFn == null ? data1 : data2; let sent = waitForObserverTopic("message"); Services.obs.notifyObservers(this, "message", data1); diff --git a/testing/marionette/transport.js b/testing/marionette/transport.js index d9344a6bed9b..c6907c5d9f9d 100644 --- a/testing/marionette/transport.js +++ b/testing/marionette/transport.js @@ -8,30 +8,34 @@ const CC = Components.Constructor; -const {EventEmitter} = ChromeUtils.import("resource://gre/modules/EventEmitter.jsm"); -const { - StreamUtils, -} = ChromeUtils.import("chrome://marionette/content/stream-utils.js"); -const { - BulkPacket, - JSONPacket, - Packet, -} = ChromeUtils.import("chrome://marionette/content/packets.js"); -const { - executeSoon, -} = ChromeUtils.import("chrome://marionette/content/sync.js"); +const { EventEmitter } = ChromeUtils.import( + "resource://gre/modules/EventEmitter.jsm" +); +const { StreamUtils } = ChromeUtils.import( + "chrome://marionette/content/stream-utils.js" +); +const { BulkPacket, JSONPacket, Packet } = ChromeUtils.import( + "chrome://marionette/content/packets.js" +); +const { executeSoon } = ChromeUtils.import( + "chrome://marionette/content/sync.js" +); -const flags = {wantVerbose: false, wantLogging: false}; +const flags = { wantVerbose: false, wantLogging: false }; -const dumpv = - flags.wantVerbose ? - function(msg) { dump(msg + "\n"); } : - function() {}; +const dumpv = flags.wantVerbose + ? function(msg) { + dump(msg + "\n"); + } + : function() {}; const Pipe = CC("@mozilla.org/pipe;1", "nsIPipe", "init"); -const ScriptableInputStream = CC("@mozilla.org/scriptableinputstream;1", - "nsIScriptableInputStream", "init"); +const ScriptableInputStream = CC( + "@mozilla.org/scriptableinputstream;1", + "nsIScriptableInputStream", + "init" +); this.EXPORTED_SYMBOLS = ["DebuggerTransport"]; @@ -361,9 +365,12 @@ DebuggerTransport.prototype = { */ onInputStreamReady(stream) { try { - while (stream.available() && this._incomingEnabled && - this._processIncoming(stream, stream.available())) { - // Loop until there is nothing more to process + while ( + stream.available() && + this._incomingEnabled && + this._processIncoming(stream, stream.available()) + ) { + // Loop until there is nothing more to process } this._waitForIncoming(); } catch (e) { @@ -407,8 +414,9 @@ DebuggerTransport.prototype = { // header pattern. this._incoming = Packet.fromHeader(this._incomingHeader, this); if (!this._incoming) { - throw new Error("No packet types for header: " + - this._incomingHeader); + throw new Error( + "No packet types for header: " + this._incomingHeader + ); } } @@ -446,8 +454,11 @@ DebuggerTransport.prototype = { */ _readHeader() { let amountToRead = PACKET_HEADER_MAX - this._incomingHeader.length; - this._incomingHeader += - StreamUtils.delimitedRead(this._scriptableInput, ":", amountToRead); + this._incomingHeader += StreamUtils.delimitedRead( + this._scriptableInput, + ":", + amountToRead + ); if (flags.wantVerbose) { dumpv("Header read: " + this._incomingHeader); } @@ -486,7 +497,7 @@ DebuggerTransport.prototype = { */ _onJSONObjectReady(object) { executeSoon(() => { - // Ensure the transport is still alive by the time this runs. + // Ensure the transport is still alive by the time this runs. if (this.active) { this.emit("packet", object); this.hooks.onPacket(object); @@ -502,7 +513,7 @@ DebuggerTransport.prototype = { */ _onBulkReadReady(...args) { executeSoon(() => { - // Ensure the transport is still alive by the time this runs. + // Ensure the transport is still alive by the time this runs. if (this.active) { this.emit("bulkpacket", ...args); this.hooks.onBulkPacket(...args); diff --git a/testing/mochitest/BrowserTestUtils/BrowserTestUtils.jsm b/testing/mochitest/BrowserTestUtils/BrowserTestUtils.jsm index 08c47da6301d..d876211ca622 100644 --- a/testing/mochitest/BrowserTestUtils/BrowserTestUtils.jsm +++ b/testing/mochitest/BrowserTestUtils/BrowserTestUtils.jsm @@ -15,39 +15,52 @@ "use strict"; -var EXPORTED_SYMBOLS = [ - "BrowserTestUtils", -]; +var EXPORTED_SYMBOLS = ["BrowserTestUtils"]; -const {AppConstants} = ChromeUtils.import("resource://gre/modules/AppConstants.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {TestUtils} = ChromeUtils.import("resource://testing-common/TestUtils.jsm"); -const {ContentTask} = ChromeUtils.import("resource://testing-common/ContentTask.jsm"); +const { AppConstants } = ChromeUtils.import( + "resource://gre/modules/AppConstants.jsm" +); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { TestUtils } = ChromeUtils.import( + "resource://testing-common/TestUtils.jsm" +); +const { ContentTask } = ChromeUtils.import( + "resource://testing-common/ContentTask.jsm" +); -ChromeUtils.defineModuleGetter(this, "BrowserWindowTracker", - "resource:///modules/BrowserWindowTracker.jsm"); +ChromeUtils.defineModuleGetter( + this, + "BrowserWindowTracker", + "resource:///modules/BrowserWindowTracker.jsm" +); -Services - .mm - .loadFrameScript( - "chrome://mochikit/content/tests/BrowserTestUtils/content-utils.js", true); +Services.mm.loadFrameScript( + "chrome://mochikit/content/tests/BrowserTestUtils/content-utils.js", + true +); -ChromeUtils.defineModuleGetter(this, "E10SUtils", - "resource://gre/modules/E10SUtils.jsm"); +ChromeUtils.defineModuleGetter( + this, + "E10SUtils", + "resource://gre/modules/E10SUtils.jsm" +); const PROCESSSELECTOR_CONTRACTID = "@mozilla.org/ipc/processselector;1"; -const OUR_PROCESSSELECTOR_CID = - Components.ID("{f9746211-3d53-4465-9aeb-ca0d96de0253}"); +const OUR_PROCESSSELECTOR_CID = Components.ID( + "{f9746211-3d53-4465-9aeb-ca0d96de0253}" +); const EXISTING_JSID = Cc[PROCESSSELECTOR_CONTRACTID]; -const DEFAULT_PROCESSSELECTOR_CID = EXISTING_JSID ? - Components.ID(EXISTING_JSID.number) : null; +const DEFAULT_PROCESSSELECTOR_CID = EXISTING_JSID + ? Components.ID(EXISTING_JSID.number) + : null; let gListenerId = 0; // A process selector that always asks for a new process. -function NewProcessSelector() { -} +function NewProcessSelector() {} NewProcessSelector.prototype = { classID: OUR_PROCESSSELECTOR_CID, @@ -100,7 +113,7 @@ var BrowserTestUtils = { * @rejects Any exception from taskFn is propagated. */ async withNewTab(options, taskFn) { - if (typeof(options) == "string") { + if (typeof options == "string") { options = { gBrowser: Services.wm.getMostRecentWindow("navigator:browser").gBrowser, url: options, @@ -119,7 +132,8 @@ var BrowserTestUtils = { } else { Services.console.logStringMessage( "BrowserTestUtils.withNewTab: Tab was already closed before " + - "removeTab would have been called"); + "removeTab would have been called" + ); } return Promise.resolve(result); }, @@ -151,7 +165,10 @@ var BrowserTestUtils = { */ openNewForegroundTab(tabbrowser, ...args) { let options; - if (tabbrowser.ownerGlobal && tabbrowser === tabbrowser.ownerGlobal.gBrowser) { + if ( + tabbrowser.ownerGlobal && + tabbrowser === tabbrowser.ownerGlobal.gBrowser + ) { // tabbrowser is a tabbrowser, read the rest of the arguments from args. let [ opening = "about:blank", @@ -177,9 +194,10 @@ var BrowserTestUtils = { options = { opening, waitForLoad, waitForStateStop, forceNewProcess }; } - let { opening: opening, - waitForLoad: aWaitForLoad, - waitForStateStop: aWaitForStateStop, + let { + opening: opening, + waitForLoad: aWaitForLoad, + waitForStateStop: aWaitForStateStop, } = options; let promises, tab; @@ -190,8 +208,12 @@ var BrowserTestUtils = { // should skip this. if (options.forceNewProcess && DEFAULT_PROCESSSELECTOR_CID) { Services.ppmm.releaseCachedProcesses(); - registrar.registerFactory(OUR_PROCESSSELECTOR_CID, "", - PROCESSSELECTOR_CONTRACTID, null); + registrar.registerFactory( + OUR_PROCESSSELECTOR_CID, + "", + PROCESSSELECTOR_CONTRACTID, + null + ); } promises = [ @@ -200,7 +222,10 @@ var BrowserTestUtils = { opening(); tab = tabbrowser.selectedTab; } else { - tabbrowser.selectedTab = tab = BrowserTestUtils.addTab(tabbrowser, opening); + tabbrowser.selectedTab = tab = BrowserTestUtils.addTab( + tabbrowser, + opening + ); } }), ]; @@ -214,8 +239,12 @@ var BrowserTestUtils = { } finally { // Restore the original process selector, if needed. if (options.forceNewProcess && DEFAULT_PROCESSSELECTOR_CID) { - registrar.registerFactory(DEFAULT_PROCESSSELECTOR_CID, "", - PROCESSSELECTOR_CONTRACTID, null); + registrar.registerFactory( + DEFAULT_PROCESSSELECTOR_CID, + "", + PROCESSSELECTOR_CONTRACTID, + null + ); } } return Promise.all(promises).then(() => tab); @@ -231,16 +260,20 @@ var BrowserTestUtils = { */ is_hidden(element) { var style = element.ownerGlobal.getComputedStyle(element); - if (style.display == "none") + if (style.display == "none") { return true; - if (style.visibility != "visible") + } + if (style.visibility != "visible") { return true; - if (style.display == "-moz-popup") + } + if (style.display == "-moz-popup") { return ["hiding", "closed"].includes(element.state); + } // Hiding a parent element will hide all its children - if (element.parentNode != element.ownerDocument) + if (element.parentNode != element.ownerDocument) { return BrowserTestUtils.is_hidden(element.parentNode); + } return false; }, @@ -255,16 +288,20 @@ var BrowserTestUtils = { */ is_visible(element) { var style = element.ownerGlobal.getComputedStyle(element); - if (style.display == "none") + if (style.display == "none") { return false; - if (style.visibility != "visible") + } + if (style.visibility != "visible") { return false; - if (style.display == "-moz-popup" && element.state != "open") + } + if (style.display == "-moz-popup" && element.state != "open") { return false; + } // Hiding a parent element will hide all its children - if (element.parentNode != element.ownerDocument) + if (element.parentNode != element.ownerDocument) { return BrowserTestUtils.is_visible(element.parentNode); + } return true; }, @@ -283,9 +320,13 @@ var BrowserTestUtils = { */ switchTab(tabbrowser, tab) { let promise = new Promise(resolve => { - tabbrowser.addEventListener("TabSwitchDone", function() { - TestUtils.executeSoon(() => resolve(tabbrowser.selectedTab)); - }, {once: true}); + tabbrowser.addEventListener( + "TabSwitchDone", + function() { + TestUtils.executeSoon(() => resolve(tabbrowser.selectedTab)); + }, + { once: true } + ); }); if (typeof tab == "function") { @@ -321,11 +362,17 @@ var BrowserTestUtils = { * @return {Promise} * @resolves When a load event is triggered for the browser. */ - browserLoaded(browser, includeSubFrames = false, wantLoad = null, - maybeErrorPage = false) { + browserLoaded( + browser, + includeSubFrames = false, + wantLoad = null, + maybeErrorPage = false + ) { // Passing a url as second argument is a common mistake we should prevent. if (includeSubFrames && typeof includeSubFrames != "boolean") { - throw new Error("The second argument to browserLoaded should be a boolean."); + throw new Error( + "The second argument to browserLoaded should be a boolean." + ); } // If browser belongs to tabbrowser-tab, ensure it has been @@ -338,24 +385,26 @@ var BrowserTestUtils = { function isWanted(url) { if (!wantLoad) { return true; - } else if (typeof(wantLoad) == "function") { + } else if (typeof wantLoad == "function") { return wantLoad(url); } - // It's a string. - return wantLoad == url; + // It's a string. + return wantLoad == url; } return new Promise(resolve => { let mm = browser.ownerGlobal.messageManager; let eventName = maybeErrorPage - ? "browser-test-utils:DOMContentLoadedEvent" - : "browser-test-utils:loadEvent"; + ? "browser-test-utils:DOMContentLoadedEvent" + : "browser-test-utils:loadEvent"; mm.addMessageListener(eventName, function onLoad(msg) { // See testing/mochitest/BrowserTestUtils/content/content-utils.js for // the difference between visibleURL and internalURL. - if (msg.target == browser && (!msg.data.subframe || includeSubFrames) && - isWanted(maybeErrorPage - ? msg.data.visibleURL : msg.data.internalURL)) { + if ( + msg.target == browser && + (!msg.data.subframe || includeSubFrames) && + isWanted(maybeErrorPage ? msg.data.visibleURL : msg.data.internalURL) + ) { mm.removeMessageListener(eventName, onLoad); resolve(msg.data.internalURL); } @@ -384,14 +433,16 @@ var BrowserTestUtils = { */ firstBrowserLoaded(win, aboutBlank = true, checkFn = null) { let mm = win.messageManager; - return this.waitForMessage(mm, "browser-test-utils:loadEvent", (msg) => { + return this.waitForMessage(mm, "browser-test-utils:loadEvent", msg => { if (checkFn) { return checkFn(msg.target); } let selectedBrowser = win.gBrowser.selectedBrowser; - return msg.target == selectedBrowser && - (aboutBlank || selectedBrowser.currentURI.spec != "about:blank"); + return ( + msg.target == selectedBrowser && + (aboutBlank || selectedBrowser.currentURI.spec != "about:blank") + ); }); }, @@ -416,11 +467,19 @@ var BrowserTestUtils = { return new Promise(resolve => { let wpl = { onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) { - dump("Saw state " + aStateFlags.toString(16) + " and status " + aStatus.toString(16) + "\n"); - if (aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK && - aStateFlags & Ci.nsIWebProgressListener.STATE_STOP && - (checkAborts || aStatus != Cr.NS_BINDING_ABORTED) && - aWebProgress.isTopLevel) { + dump( + "Saw state " + + aStateFlags.toString(16) + + " and status " + + aStatus.toString(16) + + "\n" + ); + if ( + aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK && + aStateFlags & Ci.nsIWebProgressListener.STATE_STOP && + (checkAborts || aStatus != Cr.NS_BINDING_ABORTED) && + aWebProgress.isTopLevel + ) { let chan = aRequest.QueryInterface(Ci.nsIChannel); dump("Browser loaded " + chan.originalURI.spec + "\n"); if (!expectedURI || chan.originalURI.spec == expectedURI) { @@ -442,7 +501,11 @@ var BrowserTestUtils = { }; browser.addProgressListener(wpl); this._webProgressListeners.add(wpl); - dump("Waiting for browser load" + (expectedURI ? (" of " + expectedURI) : "") + "\n"); + dump( + "Waiting for browser load" + + (expectedURI ? " of " + expectedURI : "") + + "\n" + ); }); }, @@ -469,46 +532,59 @@ var BrowserTestUtils = { * and the tab does not load a URL, because no onLocationChange will fire. */ waitForNewTab(tabbrowser, url, waitForLoad = false, waitForAnyTab = false) { - let urlMatches = url ? (urlToMatch) => urlToMatch == url - : (urlToMatch) => urlToMatch != "about:blank"; + let urlMatches = url + ? urlToMatch => urlToMatch == url + : urlToMatch => urlToMatch != "about:blank"; return new Promise((resolve, reject) => { - tabbrowser.tabContainer.addEventListener("TabOpen", function tabOpenListener(openEvent) { - if (!waitForAnyTab) { - tabbrowser.tabContainer.removeEventListener("TabOpen", tabOpenListener); - } - let newTab = openEvent.target; - let newBrowser = newTab.linkedBrowser; - let result; - if (waitForLoad) { - // If waiting for load, resolve with promise for that, which when load - // completes resolves to the new tab. - result = BrowserTestUtils.browserLoaded(newBrowser, false, urlMatches) - .then(() => newTab); - } else { - // If not waiting for load, just resolve with the new tab. - result = newTab; - } + tabbrowser.tabContainer.addEventListener( + "TabOpen", + function tabOpenListener(openEvent) { + if (!waitForAnyTab) { + tabbrowser.tabContainer.removeEventListener( + "TabOpen", + tabOpenListener + ); + } + let newTab = openEvent.target; + let newBrowser = newTab.linkedBrowser; + let result; + if (waitForLoad) { + // If waiting for load, resolve with promise for that, which when load + // completes resolves to the new tab. + result = BrowserTestUtils.browserLoaded( + newBrowser, + false, + urlMatches + ).then(() => newTab); + } else { + // If not waiting for load, just resolve with the new tab. + result = newTab; + } - let progressListener = { - onLocationChange(aBrowser) { - // Only interested in location changes on our browser. - if (aBrowser != newBrowser) { - return; - } + let progressListener = { + onLocationChange(aBrowser) { + // Only interested in location changes on our browser. + if (aBrowser != newBrowser) { + return; + } - // Check that new location is the URL we want. - if (!urlMatches(aBrowser.currentURI.spec)) { - return; - } - if (waitForAnyTab) { - tabbrowser.tabContainer.removeEventListener("TabOpen", tabOpenListener); - } - tabbrowser.removeTabsProgressListener(progressListener); - TestUtils.executeSoon(() => resolve(result)); - }, - }; - tabbrowser.addTabsProgressListener(progressListener); - }); + // Check that new location is the URL we want. + if (!urlMatches(aBrowser.currentURI.spec)) { + return; + } + if (waitForAnyTab) { + tabbrowser.tabContainer.removeEventListener( + "TabOpen", + tabOpenListener + ); + } + tabbrowser.removeTabsProgressListener(progressListener); + TestUtils.executeSoon(() => resolve(result)); + }, + }; + tabbrowser.addTabsProgressListener(progressListener); + } + ); }); }, @@ -527,8 +603,10 @@ var BrowserTestUtils = { return new Promise((resolve, reject) => { let progressListener = { onLocationChange(aBrowser) { - if ((url && aBrowser.currentURI.spec != url) || - (!url && aBrowser.currentURI.spec == "about:blank")) { + if ( + (url && aBrowser.currentURI.spec != url) || + (!url && aBrowser.currentURI.spec == "about:blank") + ) { return; } @@ -558,11 +636,7 @@ var BrowserTestUtils = { * opens and the delayed startup observer notification fires. */ waitForNewWindow(aParams = {}) { - let { - url = null, - anyWindow = false, - maybeErrorPage = false, - } = aParams; + let { url = null, anyWindow = false, maybeErrorPage = false } = aParams; if (anyWindow && !url) { throw new Error("url should be specified if anyWindow is true"); @@ -593,19 +667,34 @@ var BrowserTestUtils = { } } - promises.push(TestUtils.topicObserved("browser-delayed-startup-finished", - subject => subject == win)); + promises.push( + TestUtils.topicObserved( + "browser-delayed-startup-finished", + subject => subject == win + ) + ); if (url) { let browser = win.gBrowser.selectedBrowser; - if (win.gMultiProcessBrowser && - !E10SUtils.canLoadURIInRemoteType(url, win.gFissionBrowser, browser.remoteType, - browser.remoteType /* aPreferredRemoteType */)) { + if ( + win.gMultiProcessBrowser && + !E10SUtils.canLoadURIInRemoteType( + url, + win.gFissionBrowser, + browser.remoteType, + browser.remoteType /* aPreferredRemoteType */ + ) + ) { await this.waitForEvent(browser, "XULFrameLoaderCreated"); } - let loadPromise = this.browserLoaded(browser, false, url, maybeErrorPage); + let loadPromise = this.browserLoaded( + browser, + false, + url, + maybeErrorPage + ); promises.push(loadPromise); } @@ -647,9 +736,13 @@ var BrowserTestUtils = { // If the new URI can't load in the browser's current process then we // should wait for the new frameLoader to be created. This will happen // asynchronously when the browser's remoteness changes. - if (!E10SUtils.canLoadURIInRemoteType(uri, - browser.ownerGlobal.gFissionBrowser, - browser.remoteType)) { + if ( + !E10SUtils.canLoadURIInRemoteType( + uri, + browser.ownerGlobal.gFissionBrowser, + browser.remoteType + ) + ) { await this.waitForEvent(browser, "XULFrameLoaderCreated"); } }, @@ -673,7 +766,7 @@ var BrowserTestUtils = { async function observer(subject, topic, data) { if (topic == "domwindowopened" && (!win || subject === win)) { let observedWindow = subject.QueryInterface(Ci.nsIDOMWindow); - if (checkFn && !await checkFn(observedWindow)) { + if (checkFn && !(await checkFn(observedWindow))) { return; } Services.ww.unregisterNotification(observer); @@ -694,7 +787,7 @@ var BrowserTestUtils = { * has been fired by the window watcher. */ domWindowClosed(win) { - return new Promise((resolve) => { + return new Promise(resolve => { function observer(subject, topic, data) { if (topic == "domwindowclosed" && (!win || subject === win)) { Services.ww.unregisterNotification(observer); @@ -720,26 +813,37 @@ var BrowserTestUtils = { * Resolves with the new window once it is loaded. */ async openNewBrowserWindow(options = {}) { - let currentWin = BrowserWindowTracker.getTopWindow({private: false}); + let currentWin = BrowserWindowTracker.getTopWindow({ private: false }); if (!currentWin) { - throw new Error("Can't open a new browser window from this helper if no non-private window is open."); + throw new Error( + "Can't open a new browser window from this helper if no non-private window is open." + ); } let win = currentWin.OpenBrowserWindow(options); - let promises = [this.waitForEvent(win, "focus", true), this.waitForEvent(win, "activate")]; + let promises = [ + this.waitForEvent(win, "focus", true), + this.waitForEvent(win, "activate"), + ]; // Wait for browser-delayed-startup-finished notification, it indicates // that the window has loaded completely and is ready to be used for // testing. promises.push( - TestUtils.topicObserved("browser-delayed-startup-finished", - subject => subject == win).then(() => win) + TestUtils.topicObserved( + "browser-delayed-startup-finished", + subject => subject == win + ).then(() => win) ); - - promises.push(this.firstBrowserLoaded(win, !options.waitForTabURL, browser => { - return !options.waitForTabURL || options.waitForTabURL == browser.currentURI.spec; - })); + promises.push( + this.firstBrowserLoaded(win, !options.waitForTabURL, browser => { + return ( + !options.waitForTabURL || + options.waitForTabURL == browser.currentURI.spec + ); + }) + ); await Promise.all(promises); @@ -780,27 +884,31 @@ var BrowserTestUtils = { let winType = win.document.documentElement.getAttribute("windowtype"); if (winType == "navigator:browser") { - let finalMsgsPromise = new Promise((resolve) => { + let finalMsgsPromise = new Promise(resolve => { let browserSet = new Set(win.gBrowser.browsers); // Ensure all browsers have been inserted or we won't get // messages back from them. - browserSet.forEach((browser) => { + browserSet.forEach(browser => { win.gBrowser._insertBrowser(win.gBrowser.getTabForBrowser(browser)); }); let mm = win.getGroupMessageManager("browsers"); - mm.addMessageListener("SessionStore:update", function onMessage(msg) { - if (browserSet.has(msg.target) && msg.data.isFinal) { - browserSet.delete(msg.target); - if (!browserSet.size) { - mm.removeMessageListener("SessionStore:update", onMessage); - // Give the TabStateFlusher a chance to react to this final - // update and for the TabStateFlusher.flushWindow promise - // to resolve before we resolve. - TestUtils.executeSoon(resolve); + mm.addMessageListener( + "SessionStore:update", + function onMessage(msg) { + if (browserSet.has(msg.target) && msg.data.isFinal) { + browserSet.delete(msg.target); + if (!browserSet.size) { + mm.removeMessageListener("SessionStore:update", onMessage); + // Give the TabStateFlusher a chance to react to this final + // update and for the TabStateFlusher.flushWindow promise + // to resolve before we resolve. + TestUtils.executeSoon(resolve); + } } - } - }, true); + }, + true + ); }); promises.push(finalMsgsPromise); @@ -820,15 +928,19 @@ var BrowserTestUtils = { */ waitForSessionStoreUpdate(tab) { return new Promise(resolve => { - let {messageManager: mm, frameLoader} = tab.linkedBrowser; - mm.addMessageListener("SessionStore:update", function onMessage(msg) { - if (msg.targetFrameLoader == frameLoader && msg.data.isFinal) { - mm.removeMessageListener("SessionStore:update", onMessage); - // Wait for the next event tick to make sure other listeners are - // called. - TestUtils.executeSoon(() => resolve()); - } - }, true); + let { messageManager: mm, frameLoader } = tab.linkedBrowser; + mm.addMessageListener( + "SessionStore:update", + function onMessage(msg) { + if (msg.targetFrameLoader == frameLoader && msg.data.isFinal) { + mm.removeMessageListener("SessionStore:update", onMessage); + // Wait for the next event tick to make sure other listeners are + // called. + TestUtils.executeSoon(() => resolve()); + } + }, + true + ); }); }, @@ -885,22 +997,27 @@ var BrowserTestUtils = { */ waitForEvent(subject, eventName, capture, checkFn, wantsUntrusted) { return new Promise((resolve, reject) => { - subject.addEventListener(eventName, function listener(event) { - try { - if (checkFn && !checkFn(event)) { - return; - } - subject.removeEventListener(eventName, listener, capture); - TestUtils.executeSoon(() => resolve(event)); - } catch (ex) { + subject.addEventListener( + eventName, + function listener(event) { try { + if (checkFn && !checkFn(event)) { + return; + } subject.removeEventListener(eventName, listener, capture); - } catch (ex2) { - // Maybe the provided object does not support removeEventListener. + TestUtils.executeSoon(() => resolve(event)); + } catch (ex) { + try { + subject.removeEventListener(eventName, listener, capture); + } catch (ex2) { + // Maybe the provided object does not support removeEventListener. + } + TestUtils.executeSoon(() => reject(ex)); } - TestUtils.executeSoon(() => reject(ex)); - } - }, capture, wantsUntrusted); + }, + capture, + wantsUntrusted + ); }); }, @@ -926,7 +1043,13 @@ var BrowserTestUtils = { * * @returns {Promise} */ - waitForContentEvent(browser, eventName, capture = false, checkFn, wantsUntrusted = false) { + waitForContentEvent( + browser, + eventName, + capture = false, + checkFn, + wantsUntrusted = false + ) { let parameters = { eventName, capture, @@ -934,27 +1057,36 @@ var BrowserTestUtils = { wantsUntrusted, }; /* eslint-disable no-eval */ - return ContentTask.spawn(browser, parameters, - function({ eventName, capture, checkFnSource, wantsUntrusted }) { - let checkFn; - if (checkFnSource) { - checkFn = eval(`(() => (${checkFnSource}))()`); - } - return new Promise((resolve, reject) => { - addEventListener(eventName, function listener(event) { - let completion = resolve; - try { - if (checkFn && !checkFn(event)) { - return; - } - } catch (e) { - completion = () => reject(e); + return ContentTask.spawn(browser, parameters, function({ + eventName, + capture, + checkFnSource, + wantsUntrusted, + }) { + let checkFn; + if (checkFnSource) { + checkFn = eval(`(() => (${checkFnSource}))()`); + } + return new Promise((resolve, reject) => { + addEventListener( + eventName, + function listener(event) { + let completion = resolve; + try { + if (checkFn && !checkFn(event)) { + return; } - removeEventListener(eventName, listener, capture); - completion(); - }, capture, wantsUntrusted); - }); - }); + } catch (e) { + completion = () => reject(e); + } + removeEventListener(eventName, listener, capture); + completion(); + }, + capture, + wantsUntrusted + ); + }); + }); /* eslint-enable no-eval */ }, @@ -969,7 +1101,7 @@ var BrowserTestUtils = { * @returns {Promise} */ waitForPopupEvent(popup, eventSuffix) { - let endState = {shown: "open", hidden: "closed"}[eventSuffix]; + let endState = { shown: "open", hidden: "closed" }[eventSuffix]; if (popup.state == endState) { return Promise.resolve(); @@ -1009,22 +1141,32 @@ var BrowserTestUtils = { * @returns function * If called, the return value will remove the event listener. */ - addContentEventListener(browser, - eventName, - listener, - useCapture = false, - checkFn, - wantsUntrusted = false, - autoremove = true) { + addContentEventListener( + browser, + eventName, + listener, + useCapture = false, + checkFn, + wantsUntrusted = false, + autoremove = true + ) { let id = gListenerId++; - let checkFnSource = checkFn ? encodeURIComponent(escape(checkFn.toSource())) : ""; + let checkFnSource = checkFn + ? encodeURIComponent(escape(checkFn.toSource())) + : ""; // To correctly handle frameloader swaps, we load a frame script // into all tabs but ignore messages from the ones not related to // |browser|. /* eslint-disable no-eval */ - function frameScript(id, eventName, useCapture, checkFnSource, wantsUntrusted) { + function frameScript( + id, + eventName, + useCapture, + checkFnSource, + wantsUntrusted + ) { let checkFn; if (checkFnSource) { checkFn = eval(`(() => (${unescape(checkFnSource)}))()`); @@ -1047,8 +1189,9 @@ var BrowserTestUtils = { } /* eslint-enable no-eval */ - let frameScriptSource = - `data:,(${frameScript.toString()})(${id}, "${eventName}", ${uneval(useCapture)}, "${checkFnSource}", ${wantsUntrusted})`; + let frameScriptSource = `data:,(${frameScript.toString()})(${id}, "${eventName}", ${uneval( + useCapture + )}, "${checkFnSource}", ${wantsUntrusted})`; let mm = Services.mm; @@ -1114,9 +1257,13 @@ var BrowserTestUtils = { // quite careful in order to make sure we're adding the listener in time to // get this event: return new Promise((resolve, reject) => { - tab.addEventListener("TabRemotenessChange", function() { - waitForLoad().then(resolve, reject); - }, {once: true}); + tab.addEventListener( + "TabRemotenessChange", + function() { + waitForLoad().then(resolve, reject); + }, + { once: true } + ); }); }, @@ -1138,7 +1285,11 @@ var BrowserTestUtils = { * progress listener callback. * @returns {Promise} */ - waitForDocLoadAndStopIt(expectedURL, browser, stopFromProgressListener = true) { + waitForDocLoadAndStopIt( + expectedURL, + browser, + stopFromProgressListener = true + ) { function content_script(contentStopFromProgressListener) { /* eslint-env mozilla/frame-script */ let wp = docShell.QueryInterface(Ci.nsIWebProgress); @@ -1158,10 +1309,16 @@ var BrowserTestUtils = { let progressListener = { onStateChange(webProgress, req, flags, status) { - dump(`waitForDocLoadAndStopIt: onStateChange ${flags.toString(16)}:${req.name}\n`); + dump( + `waitForDocLoadAndStopIt: onStateChange ${flags.toString(16)}:${ + req.name + }\n` + ); - if (webProgress.isTopLevel && - flags & Ci.nsIWebProgressListener.STATE_START) { + if ( + webProgress.isTopLevel && + flags & Ci.nsIWebProgressListener.STATE_START + ) { wp.removeProgressListener(progressListener); let chan = req.QueryInterface(Ci.nsIChannel); dump(`waitForDocLoadAndStopIt: Document start: ${chan.URI.spec}\n`); @@ -1180,7 +1337,9 @@ var BrowserTestUtils = { addEventListener("unload", function() { try { wp.removeProgressListener(progressListener); - } catch (e) { /* Will most likely fail. */ } + } catch (e) { + /* Will most likely fail. */ + } }); } @@ -1195,7 +1354,10 @@ var BrowserTestUtils = { } let mm = browser.messageManager; - mm.loadFrameScript(`data:,(${content_script.toString()})(${stopFromProgressListener});`, true); + mm.loadFrameScript( + `data:,(${content_script.toString()})(${stopFromProgressListener});`, + true + ); mm.addMessageListener("Test:WaitForDocLoadAndStopIt", complete); dump(`waitForDocLoadAndStopIt: Waiting for URL: ${expectedURL}\n`); }); @@ -1203,17 +1365,22 @@ var BrowserTestUtils = { let win = browser.ownerGlobal; let tab = win.gBrowser.getTabForBrowser(browser); - let { mustChangeProcess } = E10SUtils.shouldLoadURIInBrowser(browser, expectedURL); - if (!tab || - !win.gMultiProcessBrowser || - !mustChangeProcess) { + let { mustChangeProcess } = E10SUtils.shouldLoadURIInBrowser( + browser, + expectedURL + ); + if (!tab || !win.gMultiProcessBrowser || !mustChangeProcess) { return stoppedDocLoadPromise(); } return new Promise((resolve, reject) => { - tab.addEventListener("TabRemotenessChange", function() { - stoppedDocLoadPromise().then(resolve, reject); - }, {once: true}); + tab.addEventListener( + "TabRemotenessChange", + function() { + stoppedDocLoadPromise().then(resolve, reject); + }, + { once: true } + ); }); }, @@ -1249,7 +1416,9 @@ var BrowserTestUtils = { synthesizeMouse(target, offsetX, offsetY, event, browser) { return new Promise((resolve, reject) => { let mm = browser.messageManager; - mm.addMessageListener("Test:SynthesizeMouseDone", function mouseMsg(message) { + mm.addMessageListener("Test:SynthesizeMouseDone", function mouseMsg( + message + ) { mm.removeMessageListener("Test:SynthesizeMouseDone", mouseMsg); if (message.data.hasOwnProperty("defaultPrevented")) { resolve(message.data.defaultPrevented); @@ -1268,9 +1437,11 @@ var BrowserTestUtils = { target = null; } - mm.sendAsyncMessage("Test:SynthesizeMouse", - {target, targetFn, x: offsetX, y: offsetY, event}, - {object: cpowObject}); + mm.sendAsyncMessage( + "Test:SynthesizeMouse", + { target, targetFn, x: offsetX, y: offsetY, event }, + { object: cpowObject } + ); }); }, @@ -1306,7 +1477,9 @@ var BrowserTestUtils = { synthesizeTouch(target, offsetX, offsetY, event, browser) { return new Promise((resolve, reject) => { let mm = browser.messageManager; - mm.addMessageListener("Test:SynthesizeTouchDone", function touchMsg(message) { + mm.addMessageListener("Test:SynthesizeTouchDone", function touchMsg( + message + ) { mm.removeMessageListener("Test:SynthesizeTouchDone", touchMsg); if (message.data.hasOwnProperty("defaultPrevented")) { resolve(message.data.defaultPrevented); @@ -1325,9 +1498,11 @@ var BrowserTestUtils = { target = null; } - mm.sendAsyncMessage("Test:SynthesizeTouch", - {target, targetFn, x: offsetX, y: offsetY, event}, - {object: cpowObject}); + mm.sendAsyncMessage( + "Test:SynthesizeTouch", + { target, targetFn, x: offsetX, y: offsetY, event }, + { object: cpowObject } + ); }); }, @@ -1368,7 +1543,13 @@ var BrowserTestUtils = { * return value are the same as synthesizeMouse. */ synthesizeMouseAtPoint(offsetX, offsetY, event, browser) { - return BrowserTestUtils.synthesizeMouse(null, offsetX, offsetY, event, browser); + return BrowserTestUtils.synthesizeMouse( + null, + offsetX, + offsetY, + event, + browser + ); }, /** @@ -1413,12 +1594,18 @@ var BrowserTestUtils = { * @resolves An Object with key-value pairs representing the data from the * crash report's extra file (if applicable). */ - async crashBrowser(browser, shouldShowTabCrashPage = true, - shouldClearMinidumps = true) { + async crashBrowser( + browser, + shouldShowTabCrashPage = true, + shouldClearMinidumps = true + ) { let extra = {}; let KeyValueParser = {}; if (AppConstants.MOZ_CRASHREPORTER) { - ChromeUtils.import("resource://gre/modules/KeyValueParser.jsm", KeyValueParser); + ChromeUtils.import( + "resource://gre/modules/KeyValueParser.jsm", + KeyValueParser + ); } if (!browser.isRemoteBrowser) { @@ -1458,7 +1645,9 @@ var BrowserTestUtils = { // a bad pointer. The crash should happen immediately upon loading this // frame script. let frame_script = () => { - const {ctypes} = ChromeUtils.import("resource://gre/modules/ctypes.jsm"); + const { ctypes } = ChromeUtils.import( + "resource://gre/modules/ctypes.jsm" + ); let dies = function() { privateNoteIntentionalCrash(); @@ -1486,7 +1675,9 @@ var BrowserTestUtils = { // we might see this called as the process terminates due to previous tests. // We are only looking for "abnormal" exits... if (!subject.hasKey("abnormal")) { - dump("\nThis is a normal termination and isn't the one we are looking for...\n"); + dump( + "\nThis is a normal termination and isn't the one we are looking for...\n" + ); return; } @@ -1494,7 +1685,9 @@ var BrowserTestUtils = { if (AppConstants.MOZ_CRASHREPORTER) { dumpID = subject.getPropertyAsAString("dumpID"); if (!dumpID) { - reject("dumpID was not present despite crash reporting being enabled"); + reject( + "dumpID was not present despite crash reporting being enabled" + ); return; } } @@ -1502,25 +1695,28 @@ var BrowserTestUtils = { let removalPromise = Promise.resolve(); if (dumpID) { - removalPromise = Services.crashmanager.ensureCrashIsPresent(dumpID) - .then(() => { - let minidumpDirectory = getMinidumpDirectory(); - let extrafile = minidumpDirectory.clone(); - extrafile.append(dumpID + ".extra"); - if (extrafile.exists()) { - dump(`\nNo .extra file for dumpID: ${dumpID}\n`); - if (AppConstants.MOZ_CRASHREPORTER) { - extra = KeyValueParser.parseKeyValuePairsFromFile(extrafile); - } else { - dump("\nCrashReporter not enabled - will not return any extra data\n"); + removalPromise = Services.crashmanager + .ensureCrashIsPresent(dumpID) + .then(() => { + let minidumpDirectory = getMinidumpDirectory(); + let extrafile = minidumpDirectory.clone(); + extrafile.append(dumpID + ".extra"); + if (extrafile.exists()) { + dump(`\nNo .extra file for dumpID: ${dumpID}\n`); + if (AppConstants.MOZ_CRASHREPORTER) { + extra = KeyValueParser.parseKeyValuePairsFromFile(extrafile); + } else { + dump( + "\nCrashReporter not enabled - will not return any extra data\n" + ); + } } - } - if (shouldClearMinidumps) { - removeFile(minidumpDirectory, dumpID + ".dmp"); - removeFile(minidumpDirectory, dumpID + ".extra"); - } - }); + if (shouldClearMinidumps) { + removeFile(minidumpDirectory, dumpID + ".dmp"); + removeFile(minidumpDirectory, dumpID + ".extra"); + } + }); } removalPromise.then(() => { @@ -1539,13 +1735,20 @@ var BrowserTestUtils = { expectedPromises.push(crashCleanupPromise); if (shouldShowTabCrashPage) { - expectedPromises.push(new Promise((resolve, reject) => { - browser.addEventListener("AboutTabCrashedReady", function onCrash() { - browser.removeEventListener("AboutTabCrashedReady", onCrash); - dump("\nabout:tabcrashed loaded and ready\n"); - resolve(); - }, false, true); - })); + expectedPromises.push( + new Promise((resolve, reject) => { + browser.addEventListener( + "AboutTabCrashedReady", + function onCrash() { + browser.removeEventListener("AboutTabCrashedReady", onCrash); + dump("\nabout:tabcrashed loaded and ready\n"); + resolve(); + }, + false, + true + ); + }) + ); } // This frame script will crash the remote browser as soon as it is @@ -1582,14 +1785,16 @@ var BrowserTestUtils = { let MutationObserver = element.ownerGlobal.MutationObserver; return new Promise(resolve => { let mut = new MutationObserver(mutations => { - if ((!value && element.getAttribute(attr)) || - (value && element.getAttribute(attr) === value)) { + if ( + (!value && element.getAttribute(attr)) || + (value && element.getAttribute(attr) === value) + ) { resolve(); mut.disconnect(); } }); - mut.observe(element, {attributeFilter: [attr]}); + mut.observe(element, { attributeFilter: [attr] }); }); }, @@ -1613,8 +1818,9 @@ var BrowserTestUtils = { let mm = browser.messageManager; mm.addMessageListener("Test:SendCharDone", function charMsg(message) { - if (message.data.seq != seq) + if (message.data.seq != seq) { return; + } mm.removeMessageListener("Test:SendCharDone", charMsg); resolve(message.data.result); @@ -1648,8 +1854,9 @@ var BrowserTestUtils = { let mm = browser.messageManager; mm.addMessageListener("Test:SynthesizeKeyDone", function keyMsg(message) { - if (message.data.seq != seq) + if (message.data.seq != seq) { return; + } mm.removeMessageListener("Test:SynthesizeKeyDone", keyMsg); resolve(); @@ -1678,9 +1885,12 @@ var BrowserTestUtils = { let seq = ++gSynthesizeCompositionCount; let mm = browser.messageManager; - mm.addMessageListener("Test:SynthesizeCompositionDone", function compMsg(message) { - if (message.data.seq != seq) + mm.addMessageListener("Test:SynthesizeCompositionDone", function compMsg( + message + ) { + if (message.data.seq != seq) { return; + } mm.removeMessageListener("Test:SynthesizeCompositionDone", compMsg); resolve(message.data.result); @@ -1708,13 +1918,20 @@ var BrowserTestUtils = { let seq = ++gSynthesizeCompositionChangeCount; let mm = browser.messageManager; - mm.addMessageListener("Test:SynthesizeCompositionChangeDone", function compMsg(message) { - if (message.data.seq != seq) - return; + mm.addMessageListener( + "Test:SynthesizeCompositionChangeDone", + function compMsg(message) { + if (message.data.seq != seq) { + return; + } - mm.removeMessageListener("Test:SynthesizeCompositionChangeDone", compMsg); - resolve(); - }); + mm.removeMessageListener( + "Test:SynthesizeCompositionChangeDone", + compMsg + ); + resolve(); + } + ); mm.sendAsyncMessage("Test:SynthesizeCompositionChange", { event, seq }); }); @@ -1741,8 +1958,10 @@ var BrowserTestUtils = { */ waitForNotificationBar(tabbrowser, browser, notificationValue) { let notificationBox = tabbrowser.getNotificationBox(browser); - return this.waitForNotificationInNotificationBox(notificationBox, - notificationValue); + return this.waitForNotificationInNotificationBox( + notificationBox, + notificationValue + ); }, /** @@ -1760,17 +1979,23 @@ var BrowserTestUtils = { */ waitForGlobalNotificationBar(win, notificationValue) { return this.waitForNotificationInNotificationBox( - win.gHighPriorityNotificationBox, notificationValue); + win.gHighPriorityNotificationBox, + notificationValue + ); }, waitForNotificationInNotificationBox(notificationBox, notificationValue) { - return new Promise((resolve) => { - let check = (event) => { + return new Promise(resolve => { + let check = event => { return event.target.getAttribute("value") == notificationValue; }; - BrowserTestUtils.waitForEvent(notificationBox.stack, "AlertActive", - false, check).then((event) => { + BrowserTestUtils.waitForEvent( + notificationBox.stack, + "AlertActive", + false, + check + ).then(event => { // The originalTarget of the AlertActive on a notificationbox // will be the notification itself. resolve(event.originalTarget); @@ -1789,7 +2014,7 @@ var BrowserTestUtils = { */ contentPainted(browser) { return ContentTask.spawn(browser, null, async function() { - return new Promise((resolve) => { + return new Promise(resolve => { addEventListener("MozAfterPaint", function onPaint() { removeEventListener("MozAfterPaint", onPaint); resolve(); @@ -1819,18 +2044,24 @@ var BrowserTestUtils = { */ registerAboutPage(registerCleanupFunction, aboutModule, pageURI, flags) { // Return a promise that resolves when registration finished. - const kRegistrationMsgId = "browser-test-utils:about-registration:registered"; + const kRegistrationMsgId = + "browser-test-utils:about-registration:registered"; let rv = this.waitForMessage(Services.ppmm, kRegistrationMsgId, msg => { return msg.data == aboutModule; }); // Load a script that registers our page, then send it a message to execute the registration. if (!this._loadedAboutContentScript) { - Services.ppmm.loadProcessScript(kAboutPageRegistrationContentScript, true); + Services.ppmm.loadProcessScript( + kAboutPageRegistrationContentScript, + true + ); this._loadedAboutContentScript = true; registerCleanupFunction(this._removeAboutPageRegistrations.bind(this)); } - Services.ppmm.broadcastAsyncMessage("browser-test-utils:about-registration:register", - {aboutModule, pageURI, flags}); + Services.ppmm.broadcastAsyncMessage( + "browser-test-utils:about-registration:register", + { aboutModule, pageURI, flags } + ); return rv.then(() => { this._knownAboutPages.add(aboutModule); }); @@ -1838,14 +2069,19 @@ var BrowserTestUtils = { unregisterAboutPage(aboutModule) { if (!this._knownAboutPages.has(aboutModule)) { - return Promise.reject(new Error("We don't think this about page exists!")); + return Promise.reject( + new Error("We don't think this about page exists!") + ); } - const kUnregistrationMsgId = "browser-test-utils:about-registration:unregistered"; + const kUnregistrationMsgId = + "browser-test-utils:about-registration:unregistered"; let rv = this.waitForMessage(Services.ppmm, kUnregistrationMsgId, msg => { return msg.data == aboutModule; }); - Services.ppmm.broadcastAsyncMessage("browser-test-utils:about-registration:unregister", - aboutModule); + Services.ppmm.broadcastAsyncMessage( + "browser-test-utils:about-registration:unregister", + aboutModule + ); return rv.then(() => this._knownAboutPages.delete(aboutModule)); }, @@ -1853,7 +2089,9 @@ var BrowserTestUtils = { for (let aboutModule of this._knownAboutPages) { await this.unregisterAboutPage(aboutModule); } - Services.ppmm.removeDelayedProcessScript(kAboutPageRegistrationContentScript); + Services.ppmm.removeDelayedProcessScript( + kAboutPageRegistrationContentScript + ); }, /** @@ -1868,9 +2106,11 @@ var BrowserTestUtils = { * for a dialog has been fired by the window watcher and the * specified button is clicked. */ - async promiseAlertDialogOpen(buttonAction, - uri = "chrome://global/content/commonDialog.xul", - func) { + async promiseAlertDialogOpen( + buttonAction, + uri = "chrome://global/content/commonDialog.xul", + func + ) { let win = await this.domWindowOpened(null, async win => { // The test listens for the "load" event which guarantees that the alert // class has already been added (it is added when "DOMContentLoaded" is @@ -1904,9 +2144,11 @@ var BrowserTestUtils = { * for a dialog has been fired by the window watcher and the * specified button is clicked, and the dialog has been fully closed. */ - async promiseAlertDialog(buttonAction, - uri = "chrome://global/content/commonDialog.xul", - func) { + async promiseAlertDialog( + buttonAction, + uri = "chrome://global/content/commonDialog.xul", + func + ) { let win = await this.promiseAlertDialogOpen(buttonAction, uri, func); return this.windowClosed(win); }, @@ -1935,9 +2177,13 @@ var BrowserTestUtils = { } if (beforeLoadFunc) { let window = tabbrowser.ownerGlobal; - window.addEventListener("TabOpen", function(e) { - beforeLoadFunc(e.target); - }, {once: true}); + window.addEventListener( + "TabOpen", + function(e) { + beforeLoadFunc(e.target); + }, + { once: true } + ); } return tabbrowser.addTab(uri, params); }, diff --git a/testing/mochitest/BrowserTestUtils/ContentTask.jsm b/testing/mochitest/BrowserTestUtils/ContentTask.jsm index 32aa30c27280..0d7faa9da9e4 100644 --- a/testing/mochitest/BrowserTestUtils/ContentTask.jsm +++ b/testing/mochitest/BrowserTestUtils/ContentTask.jsm @@ -6,12 +6,10 @@ "use strict"; -var EXPORTED_SYMBOLS = [ - "ContentTask", -]; +var EXPORTED_SYMBOLS = ["ContentTask"]; -const {Promise} = ChromeUtils.import("resource://gre/modules/Promise.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Promise } = ChromeUtils.import("resource://gre/modules/Promise.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const FRAME_SCRIPT = "resource://testing-common/content-task.js"; @@ -77,13 +75,11 @@ var ContentTask = { let id = gMessageID++; gPromises.set(id, deferred); - browser.messageManager.sendAsyncMessage( - "content-task:spawn", - { - id, - runnable: task.toString(), - arg, - }); + browser.messageManager.sendAsyncMessage("content-task:spawn", { + id, + runnable: task.toString(), + arg, + }); return deferred.promise; }, @@ -113,19 +109,40 @@ var ContentMessageListener = { } } else if (aMessage.name == "content-task:test-result") { let data = aMessage.data; - ContentTask._testScope.record(data.condition, data.name, null, data.stack); + ContentTask._testScope.record( + data.condition, + data.name, + null, + data.stack + ); } else if (aMessage.name == "content-task:test-info") { ContentTask._testScope.info(aMessage.data.name); } else if (aMessage.name == "content-task:test-todo") { ContentTask._testScope.todo(aMessage.data.expr, aMessage.data.name); } else if (aMessage.name == "content-task:test-todo_is") { - ContentTask._testScope.todo_is(aMessage.data.a, aMessage.data.b, aMessage.data.name); + ContentTask._testScope.todo_is( + aMessage.data.a, + aMessage.data.b, + aMessage.data.name + ); } }, }; Services.mm.addMessageListener("content-task:complete", ContentMessageListener); -Services.mm.addMessageListener("content-task:test-result", ContentMessageListener); -Services.mm.addMessageListener("content-task:test-info", ContentMessageListener); -Services.mm.addMessageListener("content-task:test-todo", ContentMessageListener); -Services.mm.addMessageListener("content-task:test-todo_is", ContentMessageListener); +Services.mm.addMessageListener( + "content-task:test-result", + ContentMessageListener +); +Services.mm.addMessageListener( + "content-task:test-info", + ContentMessageListener +); +Services.mm.addMessageListener( + "content-task:test-todo", + ContentMessageListener +); +Services.mm.addMessageListener( + "content-task:test-todo_is", + ContentMessageListener +); diff --git a/testing/mochitest/BrowserTestUtils/ContentTaskUtils.jsm b/testing/mochitest/BrowserTestUtils/ContentTaskUtils.jsm index 598d03d4f7bd..0f8be4c7b400 100644 --- a/testing/mochitest/BrowserTestUtils/ContentTaskUtils.jsm +++ b/testing/mochitest/BrowserTestUtils/ContentTaskUtils.jsm @@ -12,12 +12,12 @@ "use strict"; -var EXPORTED_SYMBOLS = [ - "ContentTaskUtils", -]; +var EXPORTED_SYMBOLS = ["ContentTaskUtils"]; -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {clearInterval, setInterval, setTimeout} = ChromeUtils.import("resource://gre/modules/Timer.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { clearInterval, setInterval, setTimeout } = ChromeUtils.import( + "resource://gre/modules/Timer.jsm" +); var ContentTaskUtils = { /** @@ -30,14 +30,17 @@ var ContentTaskUtils = { */ is_hidden(element) { var style = element.ownerGlobal.getComputedStyle(element); - if (style.display == "none") + if (style.display == "none") { return true; - if (style.visibility != "visible") + } + if (style.visibility != "visible") { return true; + } // Hiding a parent element will hide all its children - if (element.parentNode != element.ownerDocument) + if (element.parentNode != element.ownerDocument) { return ContentTaskUtils.is_hidden(element.parentNode); + } return false; }, @@ -52,14 +55,17 @@ var ContentTaskUtils = { */ is_visible(element) { var style = element.ownerGlobal.getComputedStyle(element); - if (style.display == "none") + if (style.display == "none") { return false; - if (style.visibility != "visible") + } + if (style.visibility != "visible") { return false; + } // Hiding a parent element will hide all its children - if (element.parentNode != element.ownerDocument) + if (element.parentNode != element.ownerDocument) { return ContentTaskUtils.is_visible(element.parentNode); + } return true; }, @@ -146,22 +152,27 @@ var ContentTaskUtils = { */ waitForEvent(subject, eventName, capture, checkFn, wantsUntrusted = false) { return new Promise((resolve, reject) => { - subject.addEventListener(eventName, function listener(event) { - try { - if (checkFn && !checkFn(event)) { - return; - } - subject.removeEventListener(eventName, listener, capture); - setTimeout(() => resolve(event), 0); - } catch (ex) { + subject.addEventListener( + eventName, + function listener(event) { try { + if (checkFn && !checkFn(event)) { + return; + } subject.removeEventListener(eventName, listener, capture); - } catch (ex2) { - // Maybe the provided object does not support removeEventListener. + setTimeout(() => resolve(event), 0); + } catch (ex) { + try { + subject.removeEventListener(eventName, listener, capture); + } catch (ex2) { + // Maybe the provided object does not support removeEventListener. + } + setTimeout(() => reject(ex), 0); } - setTimeout(() => reject(ex), 0); - } - }, capture, wantsUntrusted); + }, + capture, + wantsUntrusted + ); }); }, @@ -179,7 +190,7 @@ var ContentTaskUtils = { return content._EventUtils; } - let EventUtils = content._EventUtils = {}; + let EventUtils = (content._EventUtils = {}); EventUtils.window = {}; EventUtils.parent = EventUtils.window; @@ -192,7 +203,9 @@ var ContentTaskUtils = { EventUtils.KeyboardEvent = content.KeyboardEvent; Services.scriptloader.loadSubScript( - "chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils); + "chrome://mochikit/content/tests/SimpleTest/EventUtils.js", + EventUtils + ); return EventUtils; }, diff --git a/testing/mochitest/BrowserTestUtils/content/content-about-page-utils.js b/testing/mochitest/BrowserTestUtils/content/content-about-page-utils.js index 07c45fe3dbf9..2cde458cc82c 100644 --- a/testing/mochitest/BrowserTestUtils/content/content-about-page-utils.js +++ b/testing/mochitest/BrowserTestUtils/content/content-about-page-utils.js @@ -4,9 +4,11 @@ var Cm = Components.manager; -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const { generateUUID } = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator); +const { generateUUID } = Cc["@mozilla.org/uuid-generator;1"].getService( + Ci.nsIUUIDGenerator +); function AboutPage(aboutHost, chromeURL, uriFlags) { this.chromeURL = chromeURL; @@ -18,14 +20,14 @@ function AboutPage(aboutHost, chromeURL, uriFlags) { AboutPage.prototype = { QueryInterface: ChromeUtils.generateQI([Ci.nsIAboutModule]), - getURIFlags(aURI) { // eslint-disable-line no-unused-vars + getURIFlags(aURI) { + // eslint-disable-line no-unused-vars return this.uriFlags; }, newChannel(aURI, aLoadInfo) { let newURI = Services.io.newURI(this.chromeURL); - let channel = Services.io.newChannelFromURIWithLoadInfo(newURI, - aLoadInfo); + let channel = Services.io.newChannelFromURIWithLoadInfo(newURI, aLoadInfo); channel.originalURI = aURI; if (this.uriFlags & Ci.nsIAboutModule.URI_SAFE_FOR_UNTRUSTED_CONTENT) { @@ -43,27 +45,35 @@ AboutPage.prototype = { register() { Cm.QueryInterface(Ci.nsIComponentRegistrar).registerFactory( - this.classID, this.description, - "@mozilla.org/network/protocol/about;1?what=" + this.aboutHost, this); + this.classID, + this.description, + "@mozilla.org/network/protocol/about;1?what=" + this.aboutHost, + this + ); }, unregister() { Cm.QueryInterface(Ci.nsIComponentRegistrar).unregisterFactory( - this.classID, this); + this.classID, + this + ); }, }; const gRegisteredPages = new Map(); addMessageListener("browser-test-utils:about-registration:register", msg => { - let {aboutModule, pageURI, flags} = msg.data; + let { aboutModule, pageURI, flags } = msg.data; if (gRegisteredPages.has(aboutModule)) { gRegisteredPages.get(aboutModule).unregister(); } let moduleObj = new AboutPage(aboutModule, pageURI, flags); moduleObj.register(); gRegisteredPages.set(aboutModule, moduleObj); - sendAsyncMessage("browser-test-utils:about-registration:registered", aboutModule); + sendAsyncMessage( + "browser-test-utils:about-registration:registered", + aboutModule + ); }); addMessageListener("browser-test-utils:about-registration:unregister", msg => { @@ -73,5 +83,8 @@ addMessageListener("browser-test-utils:about-registration:unregister", msg => { moduleObj.unregister(); gRegisteredPages.delete(aboutModule); } - sendAsyncMessage("browser-test-utils:about-registration:unregistered", aboutModule); + sendAsyncMessage( + "browser-test-utils:about-registration:unregistered", + aboutModule + ); }); diff --git a/testing/mochitest/BrowserTestUtils/content/content-task.js b/testing/mochitest/BrowserTestUtils/content/content-task.js index a55f121107a8..325f0c089f99 100644 --- a/testing/mochitest/BrowserTestUtils/content/content-task.js +++ b/testing/mochitest/BrowserTestUtils/content/content-task.js @@ -8,7 +8,10 @@ ChromeUtils.import("resource://testing-common/Task.jsm", this); ChromeUtils.import("resource://testing-common/ContentTaskUtils.jsm", this); -const AssertCls = ChromeUtils.import("resource://testing-common/Assert.jsm", null).Assert; +const AssertCls = ChromeUtils.import( + "resource://testing-common/Assert.jsm", + null +).Assert; addMessageListener("content-task:spawn", function(msg) { let id = msg.data.id; @@ -37,15 +40,15 @@ addMessageListener("content-task:spawn", function(msg) { var isnot = Assert.notEqual.bind(Assert); function todo(expr, name) { - sendAsyncMessage("content-task:test-todo", {id, expr, name}); + sendAsyncMessage("content-task:test-todo", { id, expr, name }); } function todo_is(a, b, name) { - sendAsyncMessage("content-task:test-todo_is", {id, a, b, name}); + sendAsyncMessage("content-task:test-todo_is", { id, a, b, name }); } function info(name) { - sendAsyncMessage("content-task:test-info", {id, name}); + sendAsyncMessage("content-task:test-info", { id, name }); } /* eslint-enable no-unused-vars */ @@ -58,17 +61,20 @@ addMessageListener("content-task:spawn", function(msg) { // eslint-disable-next-line no-eval let runnable = eval(runnablestr); let iterator = runnable.call(this, msg.data.arg); - Task.spawn(iterator).then((val) => { - sendAsyncMessage("content-task:complete", { - id, - result: val, - }); - }, (e) => { - sendAsyncMessage("content-task:complete", { - id, - error: e.toString(), - }); - }); + Task.spawn(iterator).then( + val => { + sendAsyncMessage("content-task:complete", { + id, + result: val, + }); + }, + e => { + sendAsyncMessage("content-task:complete", { + id, + error: e.toString(), + }); + } + ); } catch (e) { sendAsyncMessage("content-task:complete", { id, diff --git a/testing/mochitest/BrowserTestUtils/content/content-utils.js b/testing/mochitest/BrowserTestUtils/content/content-utils.js index b22194e3b1df..6bc2580433ed 100644 --- a/testing/mochitest/BrowserTestUtils/content/content-utils.js +++ b/testing/mochitest/BrowserTestUtils/content/content-utils.js @@ -6,18 +6,30 @@ "use strict"; -addEventListener("DOMContentLoaded", function(event) { - let subframe = event.target != content.document; - // For error page, internalURL is 'about:neterror?...', and visibleURL - // is the original URL. - sendAsyncMessage("browser-test-utils:DOMContentLoadedEvent", - {subframe, internalURL: event.target.documentURI, - visibleURL: content.document.location.href}); -}, true); +addEventListener( + "DOMContentLoaded", + function(event) { + let subframe = event.target != content.document; + // For error page, internalURL is 'about:neterror?...', and visibleURL + // is the original URL. + sendAsyncMessage("browser-test-utils:DOMContentLoadedEvent", { + subframe, + internalURL: event.target.documentURI, + visibleURL: content.document.location.href, + }); + }, + true +); -addEventListener("load", function(event) { - let subframe = event.target != content.document; - sendAsyncMessage("browser-test-utils:loadEvent", - {subframe, internalURL: event.target.documentURI, - visibleURL: content.document.location.href}); -}, true); +addEventListener( + "load", + function(event) { + let subframe = event.target != content.document; + sendAsyncMessage("browser-test-utils:loadEvent", { + subframe, + internalURL: event.target.documentURI, + visibleURL: content.document.location.href, + }); + }, + true +); diff --git a/testing/mochitest/ShutdownLeaksCollector.jsm b/testing/mochitest/ShutdownLeaksCollector.jsm index 954175252341..e6cd95831ddf 100644 --- a/testing/mochitest/ShutdownLeaksCollector.jsm +++ b/testing/mochitest/ShutdownLeaksCollector.jsm @@ -2,8 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {setTimeout} = ChromeUtils.import("resource://gre/modules/Timer.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { setTimeout } = ChromeUtils.import("resource://gre/modules/Timer.jsm"); var EXPORTED_SYMBOLS = ["ContentCollector"]; @@ -14,11 +14,11 @@ var EXPORTED_SYMBOLS = ["ContentCollector"]; var ContentCollector = { init() { - let processType = Services.appinfo.processType; - if (processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT) { - // In the main process, we handle triggering collections in browser-test.js - return; - } + let processType = Services.appinfo.processType; + if (processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT) { + // In the main process, we handle triggering collections in browser-test.js + return; + } Services.cpmm.addMessageListener("browser-test:collect-request", this); }, @@ -59,6 +59,5 @@ var ContentCollector = { Services.cpmm.removeMessageListener("browser-test:collect-request", this); }, - }; ContentCollector.init(); diff --git a/testing/mochitest/api.js b/testing/mochitest/api.js index 4ae6b00f4ea8..45576f1c37da 100644 --- a/testing/mochitest/api.js +++ b/testing/mochitest/api.js @@ -4,13 +4,24 @@ /* globals ExtensionAPI */ -const {AppConstants} = ChromeUtils.import("resource://gre/modules/AppConstants.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { AppConstants } = ChromeUtils.import( + "resource://gre/modules/AppConstants.jsm" +); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); function loadChromeScripts(win) { - Services.scriptloader.loadSubScript("chrome://mochikit/content/chrome-harness.js", win); - Services.scriptloader.loadSubScript("chrome://mochikit/content/mochitest-e10s-utils.js", win); - Services.scriptloader.loadSubScript("chrome://mochikit/content/browser-test.js", win); + Services.scriptloader.loadSubScript( + "chrome://mochikit/content/chrome-harness.js", + win + ); + Services.scriptloader.loadSubScript( + "chrome://mochikit/content/mochitest-e10s-utils.js", + win + ); + Services.scriptloader.loadSubScript( + "chrome://mochikit/content/browser-test.js", + win + ); } // ///// Android /////// @@ -23,10 +34,11 @@ const windowTracker = { async observe(window, topic, data) { if (topic === "chrome-document-global-created") { await new Promise(resolve => - window.addEventListener("DOMContentLoaded", resolve, {once: true})); + window.addEventListener("DOMContentLoaded", resolve, { once: true }) + ); - let {document} = window; - let {documentURI} = document; + let { document } = window; + let { documentURI } = document; if (documentURI !== AppConstants.BROWSER_CHROME_URL) { return; @@ -60,7 +72,8 @@ function androidStartup() { // ///// Desktop /////// // Special case for Thunderbird windows. -const IS_THUNDERBIRD = Services.appinfo.ID == "{3550f703-e582-4d05-9a08-453d09bdfdc6}"; +const IS_THUNDERBIRD = + Services.appinfo.ID == "{3550f703-e582-4d05-9a08-453d09bdfdc6}"; const WINDOW_TYPE = IS_THUNDERBIRD ? "mail:3pane" : "navigator:browser"; var WindowListener = { @@ -68,8 +81,11 @@ var WindowListener = { // needs to happen in all navigator:browser windows should go here. setupWindow(win) { win.nativeConsole = win.console; - ChromeUtils.defineModuleGetter(win, "console", - "resource://gre/modules/Console.jsm"); + ChromeUtils.defineModuleGetter( + win, + "console", + "resource://gre/modules/Console.jsm" + ); }, tearDownWindow(win) { @@ -82,11 +98,17 @@ var WindowListener = { onOpenWindow(xulWin) { let win = xulWin.docShell.domWindow; - win.addEventListener("load", function() { - if (win.document.documentElement.getAttribute("windowtype") == WINDOW_TYPE) { - WindowListener.setupWindow(win); - } - }, {once: true}); + win.addEventListener( + "load", + function() { + if ( + win.document.documentElement.getAttribute("windowtype") == WINDOW_TYPE + ) { + WindowListener.setupWindow(win); + } + }, + { once: true } + ); }, }; @@ -99,8 +121,17 @@ function loadMochitest(e) { // for mochitest-plain, navigating to the url is all we need if (!IS_THUNDERBIRD) { - win.loadURI(url, null, null, null, null, null, null, null, - Services.scriptSecurityManager.getSystemPrincipal()); + win.loadURI( + url, + null, + null, + null, + null, + null, + null, + null, + Services.scriptSecurityManager.getSystemPrincipal() + ); } if (flavor == "mochitest") { return; @@ -114,9 +145,14 @@ function loadMochitest(e) { this.mochikit = class extends ExtensionAPI { onStartup() { - let aomStartup = Cc["@mozilla.org/addons/addon-manager-startup;1"] - .getService(Ci.amIAddonManagerStartup); - const manifestURI = Services.io.newURI("manifest.json", null, this.extension.rootURI); + let aomStartup = Cc[ + "@mozilla.org/addons/addon-manager-startup;1" + ].getService(Ci.amIAddonManagerStartup); + const manifestURI = Services.io.newURI( + "manifest.json", + null, + this.extension.rootURI + ); const targetURL = this.extension.rootURI.resolve("content/"); this.chromeHandle = aomStartup.registerChrome(manifestURI, [ ["content", "mochikit", targetURL], diff --git a/testing/mochitest/baselinecoverage/browser_chrome/browser_baselinecoverage.js b/testing/mochitest/baselinecoverage/browser_chrome/browser_baselinecoverage.js index 427e6f39eced..b150a30a1d29 100644 --- a/testing/mochitest/baselinecoverage/browser_chrome/browser_baselinecoverage.js +++ b/testing/mochitest/baselinecoverage/browser_chrome/browser_baselinecoverage.js @@ -9,5 +9,5 @@ const { setTimeout } = ChromeUtils.import("resource://gre/modules/Timer.jsm"); add_task(async function() { requestLongerTimeout(2); ok(true, "Collecting baseline coverage for javascript (.js) file types."); - await new Promise((c) => setTimeout(c, 30 * 1000)); + await new Promise(c => setTimeout(c, 30 * 1000)); }); diff --git a/testing/mochitest/baselinecoverage/browser_chrome/browser_baselinecoverage_browser-chrome.js b/testing/mochitest/baselinecoverage/browser_chrome/browser_baselinecoverage_browser-chrome.js index 773b780d35e7..075bbd58a969 100644 --- a/testing/mochitest/baselinecoverage/browser_chrome/browser_baselinecoverage_browser-chrome.js +++ b/testing/mochitest/baselinecoverage/browser_chrome/browser_baselinecoverage_browser-chrome.js @@ -10,13 +10,16 @@ add_task(async function() { requestLongerTimeout(2); let newWin = await BrowserTestUtils.openNewBrowserWindow(); - await BrowserTestUtils.withNewTab({ - gBrowser, - url: "about:blank", - }, async function(browser) { - ok(true, "Collecting baseline coverage for browser-chrome tests."); - await new Promise((c) => setTimeout(c, 30 * 1000)); - }); + await BrowserTestUtils.withNewTab( + { + gBrowser, + url: "about:blank", + }, + async function(browser) { + ok(true, "Collecting baseline coverage for browser-chrome tests."); + await new Promise(c => setTimeout(c, 30 * 1000)); + } + ); await BrowserTestUtils.closeWindow(newWin); }); diff --git a/testing/mochitest/browser-test.js b/testing/mochitest/browser-test.js index 00dde20d6cb6..62ecbe93ffd0 100644 --- a/testing/mochitest/browser-test.js +++ b/testing/mochitest/browser-test.js @@ -9,16 +9,34 @@ var gTimeoutSeconds = 45; var gConfig; var gSaveInstrumentationData = null; -var {AppConstants} = ChromeUtils.import("resource://gre/modules/AppConstants.jsm"); -var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +var { AppConstants } = ChromeUtils.import( + "resource://gre/modules/AppConstants.jsm" +); +var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -ChromeUtils.defineModuleGetter(this, "AddonManager", - "resource://gre/modules/AddonManager.jsm"); -ChromeUtils.defineModuleGetter(this, "ContentSearch", - "resource:///modules/ContentSearch.jsm"); +ChromeUtils.defineModuleGetter( + this, + "AddonManager", + "resource://gre/modules/AddonManager.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "ContentSearch", + "resource:///modules/ContentSearch.jsm" +); -const SIMPLETEST_OVERRIDES = - ["ok", "record", "is", "isnot", "todo", "todo_is", "todo_isnot", "info", "expectAssertions", "requestCompleteLog"]; +const SIMPLETEST_OVERRIDES = [ + "ok", + "record", + "is", + "isnot", + "todo", + "todo_is", + "todo_isnot", + "info", + "expectAssertions", + "requestCompleteLog", +]; setTimeout(testInit, 0); @@ -52,7 +70,7 @@ var TabDestroyObserver = { return Promise.resolve(); } - return new Promise((resolve) => { + return new Promise(resolve => { this.promiseResolver = resolve; }); }, @@ -63,20 +81,28 @@ function testInit() { if (gConfig.testRoot == "browser") { // Make sure to launch the test harness for the first opened window only var prefs = Services.prefs; - if (prefs.prefHasUserValue("testing.browserTestHarness.running")) + if (prefs.prefHasUserValue("testing.browserTestHarness.running")) { return; + } prefs.setBoolPref("testing.browserTestHarness.running", true); - if (prefs.prefHasUserValue("testing.browserTestHarness.timeout")) + if (prefs.prefHasUserValue("testing.browserTestHarness.timeout")) { gTimeoutSeconds = prefs.getIntPref("testing.browserTestHarness.timeout"); + } - var sstring = Cc["@mozilla.org/supports-string;1"]. - createInstance(Ci.nsISupportsString); + var sstring = Cc["@mozilla.org/supports-string;1"].createInstance( + Ci.nsISupportsString + ); sstring.data = location.search; - Services.ww.openWindow(window, "chrome://mochikit/content/browser-harness.xul", "browserTest", - "chrome,centerscreen,dialog=no,resizable,titlebar,toolbar=no,width=800,height=600", sstring); + Services.ww.openWindow( + window, + "chrome://mochikit/content/browser-harness.xul", + "browserTest", + "chrome,centerscreen,dialog=no,resizable,titlebar,toolbar=no,width=800,height=600", + sstring + ); } else { // This code allows us to redirect without requiring specialpowers for chrome and a11y tests. let messageHandler = function(m) { @@ -87,15 +113,15 @@ function testInit() { // Window is the [ChromeWindow] for messageManager, so we need content.window // Currently chrome tests are run in a content window instead of a ChromeWindow // eslint-disable-next-line no-undef - var webNav = content.window.docShell - .QueryInterface(Ci.nsIWebNavigation); + var webNav = content.window.docShell.QueryInterface(Ci.nsIWebNavigation); let loadURIOptions = { triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(), }; webNav.loadURI(url, loadURIOptions); }; - var listener = 'data:,function doLoad(e) { var data=e.detail&&e.detail.data;removeEventListener("contentEvent", function (e) { doLoad(e); }, false, true);sendAsyncMessage("chromeEvent", {"data":data}); };addEventListener("contentEvent", function (e) { doLoad(e); }, false, true);'; + var listener = + 'data:,function doLoad(e) { var data=e.detail&&e.detail.data;removeEventListener("contentEvent", function (e) { doLoad(e); }, false, true);sendAsyncMessage("chromeEvent", {"data":data}); };addEventListener("contentEvent", function (e) { doLoad(e); }, false, true);'; // eslint-disable-next-line no-undef messageManager.addMessageListener("chromeEvent", messageHandler); // eslint-disable-next-line no-undef @@ -111,17 +137,23 @@ function testInit() { prefs.setIntPref("dom.ipc.keepProcessesAlive.web", processCount); } - Services.mm.loadFrameScript("chrome://mochikit/content/shutdown-leaks-collector.js", true); + Services.mm.loadFrameScript( + "chrome://mochikit/content/shutdown-leaks-collector.js", + true + ); } else { // In non-e10s, only run the ShutdownLeaksCollector in the parent process. ChromeUtils.import("chrome://mochikit/content/ShutdownLeaksCollector.jsm"); } - Services.mm.loadFrameScript("chrome://mochikit/content/tests/SimpleTest/AsyncUtilsContent.js", true); + Services.mm.loadFrameScript( + "chrome://mochikit/content/tests/SimpleTest/AsyncUtilsContent.js", + true + ); - var testSuite = Cc["@mozilla.org/process/environment;1"]. - getService(Ci.nsIEnvironment). - get("TEST_SUITE"); + var testSuite = Cc["@mozilla.org/process/environment;1"] + .getService(Ci.nsIEnvironment) + .get("TEST_SUITE"); if (testSuite == "browser-chrome-instrumentation") { takeInstrumentation(); } @@ -133,8 +165,9 @@ function takeInstrumentation() { }; function pad(str, length) { - if (str.length >= length) + if (str.length >= length) { return str; + } return str + " ".repeat(length - str.length); } @@ -171,7 +204,10 @@ function takeInstrumentation() { if (!localNameMap.has(element.localName)) { localNameMap.set(element.localName, 1); } else { - localNameMap.set(element.localName, localNameMap.get(element.localName) + 1); + localNameMap.set( + element.localName, + localNameMap.get(element.localName) + 1 + ); } } @@ -204,13 +240,16 @@ function takeInstrumentation() { // Saves instrumantation data function saveData() { - let path = Cc["@mozilla.org/process/environment;1"]. - getService(Ci.nsIEnvironment). - get("MOZ_UPLOAD_DIR"); + let path = Cc["@mozilla.org/process/environment;1"] + .getService(Ci.nsIEnvironment) + .get("MOZ_UPLOAD_DIR"); let encoder = new TextEncoder(); let instrumentPath = OS.Path.join(path, "xulinstrument.txt"); - OS.File.writeAtomic(instrumentPath, encoder.encode(JSON.stringify(instrumentData, null, 2))); + OS.File.writeAtomic( + instrumentPath, + encoder.encode(JSON.stringify(instrumentData, null, 2)) + ); let summaryPath = OS.Path.join(path, "xulsummary.txt"); OS.File.writeAtomic(summaryPath, encoder.encode(getSummaryText())); @@ -219,7 +258,7 @@ function takeInstrumentation() { // An iterator over an element and its ancestors function* elementPath(element) { yield element; - while ((element = element.parentNode) && (element instanceof Element)) { + while ((element = element.parentNode) && element instanceof Element) { yield element; } } @@ -232,20 +271,25 @@ function takeInstrumentation() { return { namespaceURI: element.namespaceURI, localName: element.localName, - binding: (binding && binding != "none") ? binding : null, + binding: binding && binding != "none" ? binding : null, }; } // The selector for just this element function immediateSelector(element) { - if (element.localName == "notificationbox" && - element.parentNode && - element.parentNode.id == "tabbrowser-tabpanels") { + if ( + element.localName == "notificationbox" && + element.parentNode && + element.parentNode.id == "tabbrowser-tabpanels" + ) { // Don't do a full selector for a tabpanel's notificationbox return element.localName; } - if (element.localName == "tab" && element.classList.contains("tabbrowser-tab")) { + if ( + element.localName == "tab" && + element.classList.contains("tabbrowser-tab") + ) { // Don't do a full selector for a tab return element.localName; } @@ -271,7 +315,10 @@ function takeInstrumentation() { // The selector chain for the element function elementSelector(element) { - return Array.from(elementPath(element)).reverse().map(immediateSelector).join(" > "); + return Array.from(elementPath(element)) + .reverse() + .map(immediateSelector) + .join(" > "); } // An iterator over all elements in the window @@ -281,8 +328,9 @@ function takeInstrumentation() { // An iterator over an element and all of its descendants function* elementDescendants(element) { - let walker = Cc["@mozilla.org/inspector/deep-tree-walker;1"]. - createInstance(Ci.inIDeepTreeWalker); + let walker = Cc["@mozilla.org/inspector/deep-tree-walker;1"].createInstance( + Ci.inIDeepTreeWalker + ); walker.showAnonymousContent = true; walker.showSubDocuments = false; walker.showDocumentsAsNodes = false; @@ -335,7 +383,7 @@ function takeInstrumentation() { } // Watches a window for new elements to instrument function observeWindow(win) { - let observer = new MutationObserver((mutations) => { + let observer = new MutationObserver(mutations => { mutations.forEach(handleMutation); }); @@ -344,9 +392,13 @@ function takeInstrumentation() { subtree: true, }); - win.addEventListener("unload", () => { - observer.takeRecords().forEach(handleMutation); - }, { once: true }); + win.addEventListener( + "unload", + () => { + observer.takeRecords().forEach(handleMutation); + }, + { once: true } + ); } scanWindow(window); @@ -358,14 +410,18 @@ function takeInstrumentation() { return; } - win.addEventListener("load", () => { - if (win.location.href != AppConstants.BROWSER_CHROME_URL) { - return; - } + win.addEventListener( + "load", + () => { + if (win.location.href != AppConstants.BROWSER_CHROME_URL) { + return; + } - scanWindow(win); - observeWindow(win); - }, { once: true }); + scanWindow(win); + observeWindow(win); + }, + { once: true } + ); }); } @@ -380,7 +436,10 @@ function Tester(aTests, structuredLogger, aCallback) { this._scriptLoader = Services.scriptloader; this.EventUtils = {}; - this._scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", this.EventUtils); + this._scriptLoader.loadSubScript( + "chrome://mochikit/content/tests/SimpleTest/EventUtils.js", + this.EventUtils + ); // In order to allow existing tests to continue using unsafe CPOWs // with EventUtils, we need to load a separate copy into a sandbox @@ -393,34 +452,73 @@ function Tester(aTests, structuredLogger, aCallback) { Cu.permitCPOWsInScope(this.cpowSandbox); this.cpowEventUtils = new this.cpowSandbox.Object(); - this._scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", this.cpowEventUtils); + this._scriptLoader.loadSubScript( + "chrome://mochikit/content/tests/SimpleTest/EventUtils.js", + this.cpowEventUtils + ); var simpleTestScope = {}; - this._scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/ChromePowers.js", simpleTestScope); - this._scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/SimpleTest.js", simpleTestScope); - this._scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/MemoryStats.js", simpleTestScope); - this._scriptLoader.loadSubScript("chrome://mochikit/content/chrome-harness.js", simpleTestScope); + this._scriptLoader.loadSubScript( + "chrome://mochikit/content/tests/SimpleTest/ChromePowers.js", + simpleTestScope + ); + this._scriptLoader.loadSubScript( + "chrome://mochikit/content/tests/SimpleTest/SimpleTest.js", + simpleTestScope + ); + this._scriptLoader.loadSubScript( + "chrome://mochikit/content/tests/SimpleTest/MemoryStats.js", + simpleTestScope + ); + this._scriptLoader.loadSubScript( + "chrome://mochikit/content/chrome-harness.js", + simpleTestScope + ); this.SimpleTest = simpleTestScope.SimpleTest; var extensionUtilsScope = { - registerCleanupFunction: (fn) => { + registerCleanupFunction: fn => { this.currentTest.scope.registerCleanupFunction(fn); }, }; extensionUtilsScope.SimpleTest = this.SimpleTest; - this._scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js", extensionUtilsScope); + this._scriptLoader.loadSubScript( + "chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js", + extensionUtilsScope + ); this.ExtensionTestUtils = extensionUtilsScope.ExtensionTestUtils; this.SimpleTest.harnessParameters = gConfig; this.MemoryStats = simpleTestScope.MemoryStats; - this.ContentTask = ChromeUtils.import("resource://testing-common/ContentTask.jsm", null).ContentTask; - this.BrowserTestUtils = ChromeUtils.import("resource://testing-common/BrowserTestUtils.jsm", null).BrowserTestUtils; - this.TestUtils = ChromeUtils.import("resource://testing-common/TestUtils.jsm", null).TestUtils; - this.Promise = ChromeUtils.import("resource://gre/modules/Promise.jsm", null).Promise; - this.PromiseTestUtils = ChromeUtils.import("resource://testing-common/PromiseTestUtils.jsm", null).PromiseTestUtils; - this.Assert = ChromeUtils.import("resource://testing-common/Assert.jsm", null).Assert; - this.PerTestCoverageUtils = ChromeUtils.import("resource://testing-common/PerTestCoverageUtils.jsm", null).PerTestCoverageUtils; + this.ContentTask = ChromeUtils.import( + "resource://testing-common/ContentTask.jsm", + null + ).ContentTask; + this.BrowserTestUtils = ChromeUtils.import( + "resource://testing-common/BrowserTestUtils.jsm", + null + ).BrowserTestUtils; + this.TestUtils = ChromeUtils.import( + "resource://testing-common/TestUtils.jsm", + null + ).TestUtils; + this.Promise = ChromeUtils.import( + "resource://gre/modules/Promise.jsm", + null + ).Promise; + this.PromiseTestUtils = ChromeUtils.import( + "resource://testing-common/PromiseTestUtils.jsm", + null + ).PromiseTestUtils; + this.Assert = ChromeUtils.import( + "resource://testing-common/Assert.jsm", + null + ).Assert; + this.PerTestCoverageUtils = ChromeUtils.import( + "resource://testing-common/PerTestCoverageUtils.jsm", + null + ).PerTestCoverageUtils; this.PromiseTestUtils.init(); @@ -431,7 +529,10 @@ function Tester(aTests, structuredLogger, aCallback) { this._coverageCollector = null; - const XPCOMUtilsMod = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm", null); + const XPCOMUtilsMod = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm", + null + ); // Avoid failing tests when XPCOMUtils.defineLazyScriptGetter is used. XPCOMUtilsMod.Services = Object.create(Services, { @@ -445,14 +546,21 @@ function Tester(aTests, structuredLogger, aCallback) { return this._scriptLoader.loadSubScript(url, obj); } finally { for (let property of Object.keys(window)) { - if (!before.includes(property) && !this._globalProperties.includes(property)) { + if ( + !before.includes(property) && + !this._globalProperties.includes(property) + ) { this._globalProperties.push(property); - this.SimpleTest.info("Global property added while loading " + url + ": " + property); + this.SimpleTest.info( + "Global property added while loading " + url + ": " + property + ); } } } }, - loadSubScriptWithOptions: this._scriptLoader.loadSubScriptWithOptions.bind(this._scriptLoader), + loadSubScriptWithOptions: this._scriptLoader.loadSubScriptWithOptions.bind( + this._scriptLoader + ), }, }, }); @@ -476,25 +584,30 @@ Tester.prototype = { return this.tests[this.currentTestIndex]; }, get done() { - return (this.currentTestIndex == this.tests.length - 1) && (this.repeat <= 0); + return this.currentTestIndex == this.tests.length - 1 && this.repeat <= 0; }, start: function Tester_start() { TabDestroyObserver.init(); // if testOnLoad was not called, then gConfig is not defined - if (!gConfig) + if (!gConfig) { gConfig = readConfig(); + } - if (gConfig.runUntilFailure) + if (gConfig.runUntilFailure) { this.runUntilFailure = true; + } - if (gConfig.repeat) + if (gConfig.repeat) { this.repeat = gConfig.repeat; + } if (gConfig.jscovDirPrefix) { let coveragePath = gConfig.jscovDirPrefix; - let {CoverageCollector} = ChromeUtils.import("resource://testing-common/CoverageUtils.jsm"); + let { CoverageCollector } = ChromeUtils.import( + "resource://testing-common/CoverageUtils.jsm" + ); this._coverageCollector = new CoverageCollector(coveragePath); } @@ -502,12 +615,16 @@ Tester.prototype = { Services.console.registerListener(this); this._globalProperties = Object.keys(window); this._globalPropertyWhitelist = [ - "navigator", "constructor", "top", + "navigator", + "constructor", + "top", "Application", - "__SS_tabsToRestore", "__SSi", + "__SS_tabsToRestore", + "__SSi", "webConsoleCommandController", // Thunderbird - "MailMigrator", "SearchIntegration", + "MailMigrator", + "SearchIntegration", ]; this.PerTestCoverageUtils.beforeTestSync(); @@ -523,7 +640,9 @@ Tester.prototype = { async waitForWindowsReady() { await this.setupDefaultTheme(); - await new Promise(resolve => this.waitForGraphicsTestWindowToBeGone(resolve)); + await new Promise(resolve => + this.waitForGraphicsTestWindowToBeGone(resolve) + ); await this.promiseMainWindowReady(); }, @@ -542,8 +661,12 @@ Tester.prototype = { waitForGraphicsTestWindowToBeGone(aCallback) { for (let win of Services.wm.getEnumerator(null)) { - if (win != window && !win.closed && - win.document.documentURI == "chrome://gfxsanity/content/sanityparent.html") { + if ( + win != window && + !win.closed && + win.document.documentURI == + "chrome://gfxsanity/content/sanityparent.html" + ) { this.BrowserTestUtils.domWindowClosed(win).then(aCallback); return; } @@ -555,9 +678,11 @@ Tester.prototype = { waitForWindowsState: function Tester_waitForWindowsState(aCallback) { let timedOut = this.currentTest && this.currentTest.timedOut; // eslint-disable-next-line no-nested-ternary - let baseMsg = timedOut ? "Found a {elt} after previous test timed out" - : this.currentTest ? "Found an unexpected {elt} at the end of test run" - : "Found an unexpected {elt}"; + let baseMsg = timedOut + ? "Found a {elt} after previous test timed out" + : this.currentTest + ? "Found an unexpected {elt} at the end of test run" + : "Found an unexpected {elt}"; // Remove stale tabs if (this.currentTest && window.gBrowser && gBrowser.tabs.length > 1) { @@ -566,11 +691,15 @@ Tester.prototype = { if (!lastTab.closing) { // Report the stale tab as an error only when they're not closing. // Tests can finish without waiting for the closing tabs. - this.currentTest.addResult(new testResult({ - name: baseMsg.replace("{elt}", "tab") + ": " + - lastTab.linkedBrowser.currentURI.spec, - allowFailure: this.currentTest.allowFailure, - })); + this.currentTest.addResult( + new testResult({ + name: + baseMsg.replace("{elt}", "tab") + + ": " + + lastTab.linkedBrowser.currentURI.spec, + allowFailure: this.currentTest.allowFailure, + }) + ); } gBrowser.removeTab(lastTab); } @@ -590,27 +719,36 @@ Tester.prototype = { this.structuredLogger.info("checking window state"); for (let win of Services.wm.getEnumerator(null)) { let type = win.document.documentElement.getAttribute("windowtype"); - if (win != window && !win.closed && - win.document.documentElement.getAttribute("id") != "browserTestHarness" && - type != "devtools:webconsole") { + if ( + win != window && + !win.closed && + win.document.documentElement.getAttribute("id") != + "browserTestHarness" && + type != "devtools:webconsole" + ) { switch (type) { - case "navigator:browser": - type = "browser window"; - break; - case "mail:3pane": - type = "mail window"; - break; - case null: - type = "unknown window with document URI: " + win.document.documentURI + - " and title: " + win.document.title; - break; + case "navigator:browser": + type = "browser window"; + break; + case "mail:3pane": + type = "mail window"; + break; + case null: + type = + "unknown window with document URI: " + + win.document.documentURI + + " and title: " + + win.document.title; + break; } let msg = baseMsg.replace("{elt}", type); if (this.currentTest) { - this.currentTest.addResult(new testResult({ - name: msg, - allowFailure: this.currentTest.allowFailure, - })); + this.currentTest.addResult( + new testResult({ + name: msg, + allowFailure: this.currentTest.allowFailure, + }) + ); } else { this.failuresFromInitialWindowState++; this.structuredLogger.error("browser-test.js | " + msg); @@ -652,7 +790,9 @@ Tester.prototype = { this.structuredLogger.info("Todo: " + todoCount); this.structuredLogger.info("Mode: " + e10sMode); } else { - this.structuredLogger.error("browser-test.js | No tests to run. Did you pass invalid test_paths?"); + this.structuredLogger.error( + "browser-test.js | No tests to run. Did you pass invalid test_paths?" + ); } this.structuredLogger.info("*** End BrowserChrome Test Results ***"); @@ -680,15 +820,19 @@ Tester.prototype = { onConsoleMessage: function Tester_onConsoleMessage(aConsoleMessage) { // Ignore empty messages. - if (!aConsoleMessage.message) + if (!aConsoleMessage.message) { return; + } try { var msg = "Console message: " + aConsoleMessage.message; - if (this.currentTest) + if (this.currentTest) { this.currentTest.addResult(new testMessage(msg)); - else - this.structuredLogger.info("TEST-INFO | (browser-test.js) | " + msg.replace(/\n$/, "") + "\n"); + } else { + this.structuredLogger.info( + "TEST-INFO | (browser-test.js) | " + msg.replace(/\n$/, "") + "\n" + ); + } } catch (ex) { // Swallow exception so we don't lead to another error being reported, // throwing us into an infinite loop @@ -714,38 +858,50 @@ Tester.prototype = { this.SimpleTest.ok(false, "Cleanup function returned a generator"); } } catch (ex) { - this.currentTest.addResult(new testResult({ - name: "Cleanup function threw an exception", - ex, - allowFailure: this.currentTest.allowFailure, - })); + this.currentTest.addResult( + new testResult({ + name: "Cleanup function threw an exception", + ex, + allowFailure: this.currentTest.allowFailure, + }) + ); } } - if (this.currentTest.passCount === 0 && - this.currentTest.failCount === 0 && - this.currentTest.todoCount === 0) { - this.currentTest.addResult(new testResult({ - name: "This test contains no passes, no fails and no todos. Maybe" + - " it threw a silent exception? Make sure you use" + - " waitForExplicitFinish() if you need it.", - })); + if ( + this.currentTest.passCount === 0 && + this.currentTest.failCount === 0 && + this.currentTest.todoCount === 0 + ) { + this.currentTest.addResult( + new testResult({ + name: + "This test contains no passes, no fails and no todos. Maybe" + + " it threw a silent exception? Make sure you use" + + " waitForExplicitFinish() if you need it.", + }) + ); } let winUtils = window.windowUtils; if (winUtils.isTestControllingRefreshes) { - this.currentTest.addResult(new testResult({ - name: "test left refresh driver under test control", - })); + this.currentTest.addResult( + new testResult({ + name: "test left refresh driver under test control", + }) + ); winUtils.restoreNormalRefresh(); } if (this.SimpleTest.isExpectingUncaughtException()) { - this.currentTest.addResult(new testResult({ - name: "expectUncaughtException was called but no uncaught" + - " exception was detected!", - allowFailure: this.currentTest.allowFailure, - })); + this.currentTest.addResult( + new testResult({ + name: + "expectUncaughtException was called but no uncaught" + + " exception was detected!", + allowFailure: this.currentTest.allowFailure, + }) + ); } this.PromiseTestUtils.ensureDOMPromiseRejectionsProcessed(); @@ -763,10 +919,12 @@ Tester.prototype = { if (!this._globalProperties.includes(prop)) { this._globalProperties.push(prop); if (!this._globalPropertyWhitelist.includes(prop)) { - this.currentTest.addResult(new testResult({ - name: "test left unexpected property on window: " + prop, - allowFailure: this.currentTest.allowFailure, - })); + this.currentTest.addResult( + new testResult({ + name: "test left unexpected property on window: " + prop, + allowFailure: this.currentTest.allowFailure, + }) + ); } } }, this); @@ -803,11 +961,14 @@ Tester.prototype = { // Notify a long running test problem if it didn't end up in a timeout. if (this.currentTest.unexpectedTimeouts && !this.currentTest.timedOut) { - this.currentTest.addResult(new testResult({ - name: "This test exceeded the timeout threshold. It should be" + - " rewritten or split up. If that's not possible, use" + - " requestLongerTimeout(N), but only as a last resort.", - })); + this.currentTest.addResult( + new testResult({ + name: + "This test exceeded the timeout threshold. It should be" + + " rewritten or split up. If that's not possible, use" + + " requestLongerTimeout(N), but only as a last resort.", + }) + ); } // If we're in a debug build, check assertion counts. This code @@ -823,70 +984,105 @@ Tester.prototype = { let min = testScope.__expectedMinAsserts; if (numAsserts > max) { // TEST-UNEXPECTED-FAIL - this.currentTest.addResult(new testResult({ - name: "Assertion count " + numAsserts + - " is greater than expected range " + - min + "-" + max + " assertions.", - pass: true, // TEMPORARILY TEST-KNOWN-FAIL - todo: true, - allowFailure: this.currentTest.allowFailure, - })); + this.currentTest.addResult( + new testResult({ + name: + "Assertion count " + + numAsserts + + " is greater than expected range " + + min + + "-" + + max + + " assertions.", + pass: true, // TEMPORARILY TEST-KNOWN-FAIL + todo: true, + allowFailure: this.currentTest.allowFailure, + }) + ); } else if (numAsserts < min) { // TEST-UNEXPECTED-PASS - this.currentTest.addResult(new testResult({ - name: "Assertion count " + numAsserts + - " is less than expected range " + - min + "-" + max + " assertions.", - todo: true, - allowFailure: this.currentTest.allowFailure, - })); + this.currentTest.addResult( + new testResult({ + name: + "Assertion count " + + numAsserts + + " is less than expected range " + + min + + "-" + + max + + " assertions.", + todo: true, + allowFailure: this.currentTest.allowFailure, + }) + ); } else if (numAsserts > 0) { // TEST-KNOWN-FAIL - this.currentTest.addResult(new testResult({ - name: "Assertion count " + numAsserts + - " is within expected range " + - min + "-" + max + " assertions.", - pass: true, - todo: true, - allowFailure: this.currentTest.allowFailure, - })); + this.currentTest.addResult( + new testResult({ + name: + "Assertion count " + + numAsserts + + " is within expected range " + + min + + "-" + + max + + " assertions.", + pass: true, + todo: true, + allowFailure: this.currentTest.allowFailure, + }) + ); } } if (this.currentTest.allowFailure) { if (this.currentTest.expectedAllowedFailureCount) { - this.currentTest.addResult(new testResult({ - name: "Expected " + - this.currentTest.expectedAllowedFailureCount + - " failures in this file, got " + - this.currentTest.allowedFailureCount + ".", - pass: this.currentTest.expectedAllowedFailureCount == - this.currentTest.allowedFailureCount, - })); + this.currentTest.addResult( + new testResult({ + name: + "Expected " + + this.currentTest.expectedAllowedFailureCount + + " failures in this file, got " + + this.currentTest.allowedFailureCount + + ".", + pass: + this.currentTest.expectedAllowedFailureCount == + this.currentTest.allowedFailureCount, + }) + ); } else if (this.currentTest.allowedFailureCount == 0) { - this.currentTest.addResult(new testResult({ - name: "We expect at least one assertion to fail because this" + - " test file is marked as fail-if in the manifest.", - todo: true, - })); + this.currentTest.addResult( + new testResult({ + name: + "We expect at least one assertion to fail because this" + + " test file is marked as fail-if in the manifest.", + todo: true, + }) + ); } } // Dump memory stats for main thread. - if (Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT) { - this.MemoryStats.dump(this.currentTestIndex, - this.currentTest.path, - gConfig.dumpOutputDirectory, - gConfig.dumpAboutMemoryAfterTest, - gConfig.dumpDMDAfterTest); + if ( + Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT + ) { + this.MemoryStats.dump( + this.currentTestIndex, + this.currentTest.path, + gConfig.dumpOutputDirectory, + gConfig.dumpAboutMemoryAfterTest, + gConfig.dumpDMDAfterTest + ); } // Note the test run time let time = Date.now() - this.lastStartTime; - this.structuredLogger.testEnd(this.currentTest.path, - "OK", - undefined, - "finished in " + time + "ms"); + this.structuredLogger.testEnd( + this.currentTest.path, + "OK", + undefined, + "finished in " + time + "ms" + ); this.currentTest.setDuration(time); if (this.runUntilFailure && this.currentTest.failCount > 0) { @@ -931,8 +1127,9 @@ Tester.prototype = { } // Destroy BackgroundPageThumbs resources. - let {BackgroundPageThumbs} = - ChromeUtils.import("resource://gre/modules/BackgroundPageThumbs.jsm"); + let { BackgroundPageThumbs } = ChromeUtils.import( + "resource://gre/modules/BackgroundPageThumbs.jsm" + ); BackgroundPageThumbs._destroy(); if (window.gBrowser) { @@ -958,22 +1155,31 @@ Tester.prototype = { }); }; - - let {AsyncShutdown} = - ChromeUtils.import("resource://gre/modules/AsyncShutdown.jsm"); + let { AsyncShutdown } = ChromeUtils.import( + "resource://gre/modules/AsyncShutdown.jsm" + ); let barrier = new AsyncShutdown.Barrier( - "ShutdownLeaks: Wait for cleanup to be finished before checking for leaks"); - Services.obs.notifyObservers({wrappedJSObject: barrier}, - "shutdown-leaks-before-check"); + "ShutdownLeaks: Wait for cleanup to be finished before checking for leaks" + ); + Services.obs.notifyObservers( + { wrappedJSObject: barrier }, + "shutdown-leaks-before-check" + ); - barrier.client.addBlocker("ShutdownLeaks: Wait for tabs to finish closing", - TabDestroyObserver.wait()); + barrier.client.addBlocker( + "ShutdownLeaks: Wait for tabs to finish closing", + TabDestroyObserver.wait() + ); barrier.wait().then(() => { // Simulate memory pressure so that we're forced to free more resources // and thus get rid of more false leaks like already terminated workers. - Services.obs.notifyObservers(null, "memory-pressure", "heap-minimize"); + Services.obs.notifyObservers( + null, + "memory-pressure", + "heap-minimize" + ); Services.ppmm.broadcastAsyncMessage("browser-test:collect-request"); @@ -997,8 +1203,9 @@ Tester.prototype = { this.execTest(); } else { this.currentTestIndex++; - if (gConfig.repeat) + if (gConfig.repeat) { this.repeat = gConfig.repeat; + } this.execTest(); } }); @@ -1010,12 +1217,18 @@ Tester.prototype = { this.SimpleTest.reset(); // Load the tests into a testscope - let currentScope = this.currentTest.scope = new testScope(this, this.currentTest, this.currentTest.expected); + let currentScope = (this.currentTest.scope = new testScope( + this, + this.currentTest, + this.currentTest.expected + )); let currentTest = this.currentTest; // Import utils in the test scope. - let {scope} = this.currentTest; - scope.EventUtils = this.currentTest.usesUnsafeCPOWs ? this.cpowEventUtils : this.EventUtils; + let { scope } = this.currentTest; + scope.EventUtils = this.currentTest.usesUnsafeCPOWs + ? this.cpowEventUtils + : this.EventUtils; scope.SimpleTest = this.SimpleTest; scope.gTestPath = this.currentTest.path; scope.ContentTask = this.ContentTask; @@ -1024,17 +1237,23 @@ Tester.prototype = { scope.ExtensionTestUtils = this.ExtensionTestUtils; // Pass a custom report function for mochitest style reporting. scope.Assert = new this.Assert(function(err, message, stack) { - currentTest.addResult(new testResult(err ? { - name: err.message, - ex: err.stack, - stack: err.stack, - allowFailure: currentTest.allowFailure, - } : { - name: message, - pass: true, - stack, - allowFailure: currentTest.allowFailure, - })); + currentTest.addResult( + new testResult( + err + ? { + name: err.message, + ex: err.stack, + stack: err.stack, + allowFailure: currentTest.allowFailure, + } + : { + name: message, + pass: true, + stack, + allowFailure: currentTest.allowFailure, + } + ) + ); }, true); this.ContentTask.setTestScope(currentScope); @@ -1053,12 +1272,19 @@ Tester.prototype = { // load the tools to work with chrome .jar and remote try { - this._scriptLoader.loadSubScript("chrome://mochikit/content/chrome-harness.js", scope); - } catch (ex) { /* no chrome-harness tools */ } + this._scriptLoader.loadSubScript( + "chrome://mochikit/content/chrome-harness.js", + scope + ); + } catch (ex) { + /* no chrome-harness tools */ + } // Import head.js script if it exists. - var currentTestDirPath = - this.currentTest.path.substr(0, this.currentTest.path.lastIndexOf("/")); + var currentTestDirPath = this.currentTest.path.substr( + 0, + this.currentTest.path.lastIndexOf("/") + ); var headPath = currentTestDirPath + "/head.js"; try { this._scriptLoader.loadSubScript(headPath, scope); @@ -1071,10 +1297,12 @@ Tester.prototype = { const containsHeadPath = ex.toString().includes(headPath); if (!isImportError || !containsHeadPath) { - this.currentTest.addResult(new testResult({ - name: "head.js import threw an exception", - ex, - })); + this.currentTest.addResult( + new testResult({ + name: "head.js import threw an exception", + ex, + }) + ); } } @@ -1086,14 +1314,16 @@ Tester.prototype = { if (this.currentTest.scope.__tasks) { // This test consists of tasks, added via the `add_task()` API. if ("test" in this.currentTest.scope) { - throw new Error("Cannot run both a add_task test and a normal test at the same time."); + throw new Error( + "Cannot run both a add_task test and a normal test at the same time." + ); } let PromiseTestUtils = this.PromiseTestUtils; // Allow for a task to be skipped; we need only use the structured logger // for this, whilst deactivating log buffering to ensure that messages // are always printed to stdout. - let skipTask = (task) => { + let skipTask = task => { let logger = this.structuredLogger; logger.deactivateBuffering(); logger.testStatus(this.currentTest.path, task.name, "SKIP"); @@ -1104,7 +1334,10 @@ Tester.prototype = { (async function() { let task; while ((task = this.__tasks.shift())) { - if (task.__skipMe || (this.__runOnlyThisTask && task != this.__runOnlyThisTask)) { + if ( + task.__skipMe || + (this.__runOnlyThisTask && task != this.__runOnlyThisTask) + ) { skipTask(task); continue; } @@ -1116,42 +1349,53 @@ Tester.prototype = { } } catch (ex) { if (currentTest.timedOut) { - currentTest.addResult(new testResult({ - name: "Uncaught exception received from previously timed out test", - pass: false, - ex, - stack: (typeof ex == "object" && "stack" in ex) ? ex.stack : null, - allowFailure: currentTest.allowFailure, - })); + currentTest.addResult( + new testResult({ + name: + "Uncaught exception received from previously timed out test", + pass: false, + ex, + stack: + typeof ex == "object" && "stack" in ex ? ex.stack : null, + allowFailure: currentTest.allowFailure, + }) + ); // We timed out, so we've already cleaned up for this test, just get outta here. return; } - currentTest.addResult(new testResult({ + currentTest.addResult( + new testResult({ name: "Uncaught exception", pass: this.SimpleTest.isExpectingUncaughtException(), ex, - stack: (typeof ex == "object" && "stack" in ex) ? ex.stack : null, + stack: + typeof ex == "object" && "stack" in ex ? ex.stack : null, allowFailure: currentTest.allowFailure, - })); + }) + ); } PromiseTestUtils.assertNoUncaughtRejections(); this.SimpleTest.info("Leaving test " + task.name); } this.finish(); - }).call(currentScope); + }.call(currentScope)); } else if (typeof scope.test == "function") { scope.test(); } else { - throw new Error("This test didn't call add_task, nor did it define a generatorTest() function, nor did it define a test() function, so we don't know how to run it."); + throw new Error( + "This test didn't call add_task, nor did it define a generatorTest() function, nor did it define a test() function, so we don't know how to run it." + ); } } catch (ex) { if (!this.SimpleTest.isIgnoringAllUncaughtExceptions()) { - this.currentTest.addResult(new testResult({ - name: "Exception thrown", - pass: this.SimpleTest.isExpectingUncaughtException(), - ex, - allowFailure: this.currentTest.allowFailure, - })); + this.currentTest.addResult( + new testResult({ + name: "Exception thrown", + pass: this.SimpleTest.isExpectingUncaughtException(), + ex, + allowFailure: this.currentTest.allowFailure, + }) + ); this.SimpleTest.expectUncaughtException(false); } else { this.currentTest.addResult(new testMessage("Exception thrown: " + ex)); @@ -1167,47 +1411,64 @@ Tester.prototype = { var self = this; var timeoutExpires = Date.now() + gTimeoutSeconds * 1000; var waitUntilAtLeast = timeoutExpires - 1000; - this.currentTest.scope.__waitTimer = - this.SimpleTest._originalSetTimeout.apply(window, [function timeoutFn() { - // We sometimes get woken up long before the gTimeoutSeconds - // have elapsed (when running in chaos mode for example). This - // code ensures that we don't wrongly time out in that case. - if (Date.now() < waitUntilAtLeast) { - self.currentTest.scope.__waitTimer = - setTimeout(timeoutFn, timeoutExpires - Date.now()); - return; - } + this.currentTest.scope.__waitTimer = this.SimpleTest._originalSetTimeout.apply( + window, + [ + function timeoutFn() { + // We sometimes get woken up long before the gTimeoutSeconds + // have elapsed (when running in chaos mode for example). This + // code ensures that we don't wrongly time out in that case. + if (Date.now() < waitUntilAtLeast) { + self.currentTest.scope.__waitTimer = setTimeout( + timeoutFn, + timeoutExpires - Date.now() + ); + return; + } - if (--self.currentTest.scope.__timeoutFactor > 0) { - // We were asked to wait a bit longer. - self.currentTest.scope.info( - "Longer timeout required, waiting longer... Remaining timeouts: " + - self.currentTest.scope.__timeoutFactor); - self.currentTest.scope.__waitTimer = - setTimeout(timeoutFn, gTimeoutSeconds * 1000); - return; - } + if (--self.currentTest.scope.__timeoutFactor > 0) { + // We were asked to wait a bit longer. + self.currentTest.scope.info( + "Longer timeout required, waiting longer... Remaining timeouts: " + + self.currentTest.scope.__timeoutFactor + ); + self.currentTest.scope.__waitTimer = setTimeout( + timeoutFn, + gTimeoutSeconds * 1000 + ); + return; + } - // If the test is taking longer than expected, but it's not hanging, - // mark the fact, but let the test continue. At the end of the test, - // if it didn't timeout, we will notify the problem through an error. - // To figure whether it's an actual hang, compare the time of the last - // result or message to half of the timeout time. - // Though, to protect against infinite loops, limit the number of times - // we allow the test to proceed. - const MAX_UNEXPECTED_TIMEOUTS = 10; - if (Date.now() - self.currentTest.lastOutputTime < (gTimeoutSeconds / 2) * 1000 && - ++self.currentTest.unexpectedTimeouts <= MAX_UNEXPECTED_TIMEOUTS) { - self.currentTest.scope.__waitTimer = - setTimeout(timeoutFn, gTimeoutSeconds * 1000); - return; - } + // If the test is taking longer than expected, but it's not hanging, + // mark the fact, but let the test continue. At the end of the test, + // if it didn't timeout, we will notify the problem through an error. + // To figure whether it's an actual hang, compare the time of the last + // result or message to half of the timeout time. + // Though, to protect against infinite loops, limit the number of times + // we allow the test to proceed. + const MAX_UNEXPECTED_TIMEOUTS = 10; + if ( + Date.now() - self.currentTest.lastOutputTime < + (gTimeoutSeconds / 2) * 1000 && + ++self.currentTest.unexpectedTimeouts <= MAX_UNEXPECTED_TIMEOUTS + ) { + self.currentTest.scope.__waitTimer = setTimeout( + timeoutFn, + gTimeoutSeconds * 1000 + ); + return; + } - self.currentTest.addResult(new testResult({ name: "Test timed out" })); - self.currentTest.timedOut = true; - self.currentTest.scope.__waitTimer = null; - self.nextTest(); - }, gTimeoutSeconds * 1000]); + self.currentTest.addResult( + new testResult({ name: "Test timed out" }) + ); + self.currentTest.timedOut = true; + self.currentTest.scope.__waitTimer = null; + self.nextTest(); + }, + gTimeoutSeconds * 1000, + ] + ); } }, @@ -1271,7 +1532,11 @@ function testResult({ name, pass, todo, ex, stack, allowFailure }) { let normalized; if (stack instanceof Ci.nsIStackFrame) { let frames = []; - for (let frame = stack; frame; frame = frame.asyncCaller || frame.caller) { + for ( + let frame = stack; + frame; + frame = frame.asyncCaller || frame.caller + ) { let msg = `${frame.filename}:${frame.name}:${frame.lineNumber}`; frames.push(frame.asyncCause ? `${frame.asyncCause}*${msg}` : msg); } @@ -1312,34 +1577,61 @@ function testScope(aTester, aTest, expected) { } }; this.record = function test_record(condition, name, ex, stack) { - aTest.addResult(new testResult({ - name, pass: condition, ex, - stack: stack || Components.stack.caller, - allowFailure: aTest.allowFailure, - })); + aTest.addResult( + new testResult({ + name, + pass: condition, + ex, + stack: stack || Components.stack.caller, + allowFailure: aTest.allowFailure, + }) + ); }; this.is = function test_is(a, b, name) { - self.record(a == b, name, "Got " + a + ", expected " + b, false, - Components.stack.caller); + self.record( + a == b, + name, + "Got " + a + ", expected " + b, + false, + Components.stack.caller + ); }; this.isnot = function test_isnot(a, b, name) { - self.record(a != b, name, "Didn't expect " + a + ", but got it", false, - Components.stack.caller); + self.record( + a != b, + name, + "Didn't expect " + a + ", but got it", + false, + Components.stack.caller + ); }; this.todo = function test_todo(condition, name, ex, stack) { - aTest.addResult(new testResult({ - name, pass: !condition, todo: true, ex, - stack: stack || Components.stack.caller, - allowFailure: aTest.allowFailure, - })); + aTest.addResult( + new testResult({ + name, + pass: !condition, + todo: true, + ex, + stack: stack || Components.stack.caller, + allowFailure: aTest.allowFailure, + }) + ); }; this.todo_is = function test_todo_is(a, b, name) { - self.todo(a == b, name, "Got " + a + ", expected " + b, - Components.stack.caller); + self.todo( + a == b, + name, + "Got " + a + ", expected " + b, + Components.stack.caller + ); }; this.todo_isnot = function test_todo_isnot(a, b, name) { - self.todo(a != b, name, "Didn't expect " + a + ", but got it", - Components.stack.caller); + self.todo( + a != b, + name, + "Didn't expect " + a + ", but got it", + Components.stack.caller + ); }; this.info = function test_info(name) { aTest.addResult(new testMessage(name)); @@ -1357,15 +1649,27 @@ function testScope(aTester, aTest, expected) { self.__done = false; }; - this.waitForFocus = function test_waitForFocus(callback, targetWindow, expectBlankPage) { + this.waitForFocus = function test_waitForFocus( + callback, + targetWindow, + expectBlankPage + ) { self.SimpleTest.waitForFocus(callback, targetWindow, expectBlankPage); }; - this.waitForClipboard = function test_waitForClipboard(expected, setup, success, failure, flavor) { + this.waitForClipboard = function test_waitForClipboard( + expected, + setup, + success, + failure, + flavor + ) { self.SimpleTest.waitForClipboard(expected, setup, success, failure, flavor); }; - this.registerCleanupFunction = function test_registerCleanupFunction(aFunction) { + this.registerCleanupFunction = function test_registerCleanupFunction( + aFunction + ) { self.__cleanupFunctions.push(aFunction); }; @@ -1377,29 +1681,39 @@ function testScope(aTester, aTest, expected) { self.SimpleTest.copyToProfile(filename); }; - this.expectUncaughtException = function test_expectUncaughtException(aExpecting) { + this.expectUncaughtException = function test_expectUncaughtException( + aExpecting + ) { self.SimpleTest.expectUncaughtException(aExpecting); }; - this.ignoreAllUncaughtExceptions = function test_ignoreAllUncaughtExceptions(aIgnoring) { + this.ignoreAllUncaughtExceptions = function test_ignoreAllUncaughtExceptions( + aIgnoring + ) { self.SimpleTest.ignoreAllUncaughtExceptions(aIgnoring); }; this.expectAssertions = function test_expectAssertions(aMin, aMax) { let min = aMin; let max = aMax; - if (typeof(max) == "undefined") { + if (typeof max == "undefined") { max = min; } - if (typeof(min) != "number" || typeof(max) != "number" || - min < 0 || max < min) { + if ( + typeof min != "number" || + typeof max != "number" || + min < 0 || + max < min + ) { throw new Error("bad parameter to expectAssertions"); } self.__expectedMinAsserts = min; self.__expectedMaxAsserts = max; }; - this.setExpectedFailuresForSelfTest = function test_setExpectedFailuresForSelfTest(expectedAllowedFailureCount) { + this.setExpectedFailuresForSelfTest = function test_setExpectedFailuresForSelfTest( + expectedAllowedFailureCount + ) { aTest.allowFailure = true; aTest.expectedAllowedFailureCount = expectedAllowedFailureCount; }; @@ -1440,8 +1754,8 @@ function testScope(aTester, aTest, expected) { function decorateTaskFn(fn) { fn = fn.bind(this); - fn.skip = () => fn.__skipMe = true; - fn.only = () => this.__runOnlyThisTask = fn; + fn.skip = () => (fn.__skipMe = true); + fn.only = () => (this.__runOnlyThisTask = fn); return fn; } @@ -1482,7 +1796,7 @@ testScope.prototype = { get: () => { return this[prop]; }, - set: (value) => { + set: value => { this[prop] = value; }, }); @@ -1534,7 +1848,8 @@ testScope.prototype = { }, destroy: function test_destroy() { - for (let prop in this) + for (let prop in this) { delete this[prop]; + } }, }; diff --git a/testing/mochitest/chrome-harness.js b/testing/mochitest/chrome-harness.js index 2b0890d011da..a36ce38752fe 100644 --- a/testing/mochitest/chrome-harness.js +++ b/testing/mochitest/chrome-harness.js @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -var {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); +var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +var { NetUtil } = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); /* import-globals-from manifestLibrary.js */ @@ -32,9 +32,9 @@ function getChromeURI(url) { */ function getResolvedURI(url) { var chromeURI = getChromeURI(url); - var resolvedURI = Cc["@mozilla.org/chrome/chrome-registry;1"]. - getService(Ci.nsIChromeRegistry). - convertChromeURL(chromeURI); + var resolvedURI = Cc["@mozilla.org/chrome/chrome-registry;1"] + .getService(Ci.nsIChromeRegistry) + .convertChromeURL(chromeURI); try { resolvedURI = resolvedURI.QueryInterface(Ci.nsIJARURI); @@ -53,8 +53,9 @@ function getResolvedURI(url) { * resolvedURI: nsIURI (from getResolvedURI) that points to a file:/// url */ function getChromeDir(resolvedURI) { - var fileHandler = Cc["@mozilla.org/network/protocol;1?name=file"]. - getService(Ci.nsIFileProtocolHandler); + var fileHandler = Cc["@mozilla.org/network/protocol;1?name=file"].getService( + Ci.nsIFileProtocolHandler + ); var chromeDir = fileHandler.getFileFromURLSpec(resolvedURI.spec); return chromeDir.parent.QueryInterface(Ci.nsIFile); } @@ -112,11 +113,13 @@ function extractJarToTmp(jar) { // in strict mode (which is turned on in debug builds) tmpdir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, parseInt("0777", 8)); - var zReader = Cc["@mozilla.org/libjar/zip-reader;1"]. - createInstance(Ci.nsIZipReader); + var zReader = Cc["@mozilla.org/libjar/zip-reader;1"].createInstance( + Ci.nsIZipReader + ); - var fileHandler = Cc["@mozilla.org/network/protocol;1?name=file"]. - getService(Ci.nsIFileProtocolHandler); + var fileHandler = Cc["@mozilla.org/network/protocol;1?name=file"].getService( + Ci.nsIFileProtocolHandler + ); var fileName = fileHandler.getFileFromURLSpec(jar.JARFile.spec); zReader.open(fileName); @@ -163,7 +166,7 @@ function getTestFilePath(path) { // Get the chrome/jar uri for the current mochitest file // gTestPath being defined by the test harness in browser-chrome tests // or window is being used for mochitest-browser - var baseURI = typeof(gTestPath) == "string" ? gTestPath : window.location.href; + var baseURI = typeof gTestPath == "string" ? gTestPath : window.location.href; var parentURI = getResolvedURI(getRootDirectory(baseURI)); var file; if (parentURI.JARFile) { @@ -171,19 +174,19 @@ function getTestFilePath(path) { file = extractJarToTmp(parentURI); } else { // Otherwise, we can directly cast it to a file URI - var fileHandler = Cc["@mozilla.org/network/protocol;1?name=file"]. - getService(Ci.nsIFileProtocolHandler); + var fileHandler = Cc[ + "@mozilla.org/network/protocol;1?name=file" + ].getService(Ci.nsIFileProtocolHandler); file = fileHandler.getFileFromURLSpec(parentURI.spec); } // Then walk by the given relative path - path.split("/") - .forEach(function(p) { - if (p == "..") { - file = file.parent; - } else if (p != ".") { - file.append(p); - } - }); + path.split("/").forEach(function(p) { + if (p == "..") { + file = file.parent; + } else if (p != ".") { + file.append(p); + } + }); return file.path; } @@ -199,8 +202,7 @@ function buildRelativePath(jarentryname, destdir, basepath) { var parts = jarentryname.split("/"); - var targetFile = Cc["@mozilla.org/file/local;1"] - .createInstance(Ci.nsIFile); + var targetFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile); targetFile.initWithFile(destdir); for (var i = baseParts.length; i < parts.length; i++) { @@ -216,14 +218,19 @@ function readConfig(filename) { var configFile = Services.dirsvc.get("ProfD", Ci.nsIFile); configFile.append(filename); - if (!configFile.exists()) + if (!configFile.exists()) { return {}; + } - var fileInStream = Cc["@mozilla.org/network/file-input-stream;1"]. - createInstance(Ci.nsIFileInputStream); + var fileInStream = Cc[ + "@mozilla.org/network/file-input-stream;1" + ].createInstance(Ci.nsIFileInputStream); fileInStream.init(configFile, -1, 0, 0); - var str = NetUtil.readInputStreamToString(fileInStream, fileInStream.available()); + var str = NetUtil.readInputStreamToString( + fileInStream, + fileInStream.available() + ); fileInStream.close(); return JSON.parse(str); } @@ -248,5 +255,9 @@ function getTestList(params, callback) { } } params = config; - getTestManifest("http://mochi.test:8888/" + params.manifestFile, params, callback); + getTestManifest( + "http://mochi.test:8888/" + params.manifestFile, + params, + callback + ); } diff --git a/testing/mochitest/chunkifyTests.js b/testing/mochitest/chunkifyTests.js index 21ca0e465971..21f7708b73a0 100644 --- a/testing/mochitest/chunkifyTests.js +++ b/testing/mochitest/chunkifyTests.js @@ -3,12 +3,13 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ function skipTests(tests, startTestPattern, endTestPattern) { - var startIndex = 0, endIndex = tests.length - 1; + var startIndex = 0, + endIndex = tests.length - 1; for (var i = 0; i < tests.length; ++i) { var test_path; - if ((tests[i] instanceof Object) && ("test" in tests[i])) { + if (tests[i] instanceof Object && "test" in tests[i]) { test_path = tests[i].test.url; - } else if ((tests[i] instanceof Object) && ("url" in tests[i])) { + } else if (tests[i] instanceof Object && "url" in tests[i]) { test_path = tests[i].url; } else { test_path = tests[i]; diff --git a/testing/mochitest/manifestLibrary.js b/testing/mochitest/manifestLibrary.js index 3e6a693b5adc..7f26b9352cc2 100644 --- a/testing/mochitest/manifestLibrary.js +++ b/testing/mochitest/manifestLibrary.js @@ -26,10 +26,22 @@ function parseTestManifest(testManifest, params, callback) { } if (params.testRoot != "tests" && params.testRoot !== undefined) { let name = params.baseurl + "/" + params.testRoot + "/" + path; - links[name] = {"test": {"url": name, "expected": obj.expected, "uses-unsafe-cpows": obj["uses-unsafe-cpows"]}}; + links[name] = { + test: { + url: name, + expected: obj.expected, + "uses-unsafe-cpows": obj["uses-unsafe-cpows"], + }, + }; } else { let name = params.testPrefix + path; - paths.push({"test": {"url": name, "expected": obj.expected, "uses-unsafe-cpows": obj["uses-unsafe-cpows"]}}); + paths.push({ + test: { + url: name, + expected: obj.expected, + "uses-unsafe-cpows": obj["uses-unsafe-cpows"], + }, + }); } } if (paths.length > 0) { @@ -48,11 +60,23 @@ function getTestManifest(url, params, callback) { try { parseTestManifest(JSON.parse(req.responseText), params, callback); } catch (e) { - dump("TEST-UNEXPECTED-FAIL: manifestLibrary.js | error parsing " + url + " (" + e + ")\n"); + dump( + "TEST-UNEXPECTED-FAIL: manifestLibrary.js | error parsing " + + url + + " (" + + e + + ")\n" + ); throw e; } } else { - dump("TEST-UNEXPECTED-FAIL: manifestLibrary.js | error loading " + url + " (HTTP " + req.status + ")\n"); + dump( + "TEST-UNEXPECTED-FAIL: manifestLibrary.js | error loading " + + url + + " (HTTP " + + req.status + + ")\n" + ); callback({}); } } @@ -103,7 +127,7 @@ function filterTests(filter, testList, runOnly) { if (Object.keys(runtests).length) { for (let i = 0; i < testList.length; i++) { let testpath; - if ((testList[i] instanceof Object) && ("test" in testList[i])) { + if (testList[i] instanceof Object && "test" in testList[i]) { testpath = testList[i].test.url; } else { testpath = testList[i]; @@ -135,7 +159,7 @@ function filterTests(filter, testList, runOnly) { for (let i = 0; i < filteredTests.length; i++) { let found = false; let testpath; - if ((filteredTests[i] instanceof Object) && ("test" in filteredTests[i])) { + if (filteredTests[i] instanceof Object && "test" in filteredTests[i]) { testpath = filteredTests[i].test.url; } else { testpath = filteredTests[i]; diff --git a/testing/mochitest/mochitest-e10s-utils.js b/testing/mochitest/mochitest-e10s-utils.js index 5897c65426a1..b566b9c3dc10 100644 --- a/testing/mochitest/mochitest-e10s-utils.js +++ b/testing/mochitest/mochitest-e10s-utils.js @@ -3,9 +3,16 @@ function e10s_init() { // Listen for an 'oop-browser-crashed' event and log it so people analysing // test logs have a clue about what is going on. - window.addEventListener("oop-browser-crashed", (event) => { - let uri = event.target.currentURI; - Cu.reportError("remote browser crashed while on " + - (uri ? uri.spec : "") + "\n"); - }, true); + window.addEventListener( + "oop-browser-crashed", + event => { + let uri = event.target.currentURI; + Cu.reportError( + "remote browser crashed while on " + + (uri ? uri.spec : "") + + "\n" + ); + }, + true + ); } diff --git a/testing/mochitest/server.js b/testing/mochitest/server.js index e3259820d600..a3b133fe01ea 100644 --- a/testing/mochitest/server.js +++ b/testing/mochitest/server.js @@ -16,8 +16,7 @@ // Disable automatic network detection, so tests work correctly when // not connected to a network. // eslint-disable-next-line mozilla/use-services -var ios = Cc["@mozilla.org/network/io-service;1"] - .getService(Ci.nsIIOService); +var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); ios.manageOfflineStatus = false; ios.offline = false; @@ -38,18 +37,99 @@ var server; // for use in the shutdown handler, if necessary SELECT, SMALL, SPAN, STRIKE, STRONG, STYLE, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TITLE, TR, TT, U, UL, VAR */ -var tags = ["A", "ABBR", "ACRONYM", "ADDRESS", "APPLET", "AREA", "B", "BASE", - "BASEFONT", "BDO", "BIG", "BLOCKQUOTE", "BODY", "BR", "BUTTON", - "CAPTION", "CENTER", "CITE", "CODE", "COL", "COLGROUP", "DD", - "DEL", "DFN", "DIR", "DIV", "DL", "DT", "EM", "FIELDSET", "FONT", - "FORM", "FRAME", "FRAMESET", "H1", "H2", "H3", "H4", "H5", "H6", - "HEAD", "HR", "HTML", "I", "IFRAME", "IMG", "INPUT", "INS", - "ISINDEX", "KBD", "LABEL", "LEGEND", "LI", "LINK", "MAP", "MENU", - "META", "NOFRAMES", "NOSCRIPT", "OBJECT", "OL", "OPTGROUP", - "OPTION", "P", "PARAM", "PRE", "Q", "S", "SAMP", "SCRIPT", - "SELECT", "SMALL", "SPAN", "STRIKE", "STRONG", "STYLE", "SUB", - "SUP", "TABLE", "TBODY", "TD", "TEXTAREA", "TFOOT", "TH", "THEAD", - "TITLE", "TR", "TT", "U", "UL", "VAR"]; +var tags = [ + "A", + "ABBR", + "ACRONYM", + "ADDRESS", + "APPLET", + "AREA", + "B", + "BASE", + "BASEFONT", + "BDO", + "BIG", + "BLOCKQUOTE", + "BODY", + "BR", + "BUTTON", + "CAPTION", + "CENTER", + "CITE", + "CODE", + "COL", + "COLGROUP", + "DD", + "DEL", + "DFN", + "DIR", + "DIV", + "DL", + "DT", + "EM", + "FIELDSET", + "FONT", + "FORM", + "FRAME", + "FRAMESET", + "H1", + "H2", + "H3", + "H4", + "H5", + "H6", + "HEAD", + "HR", + "HTML", + "I", + "IFRAME", + "IMG", + "INPUT", + "INS", + "ISINDEX", + "KBD", + "LABEL", + "LEGEND", + "LI", + "LINK", + "MAP", + "MENU", + "META", + "NOFRAMES", + "NOSCRIPT", + "OBJECT", + "OL", + "OPTGROUP", + "OPTION", + "P", + "PARAM", + "PRE", + "Q", + "S", + "SAMP", + "SCRIPT", + "SELECT", + "SMALL", + "SPAN", + "STRIKE", + "STRONG", + "STYLE", + "SUB", + "SUP", + "TABLE", + "TBODY", + "TD", + "TEXTAREA", + "TFOOT", + "TH", + "THEAD", + "TITLE", + "TR", + "TT", + "U", + "UL", + "VAR", +]; /** * Below, we'll use makeTagFunc to create a function for each of the @@ -93,7 +173,7 @@ function makeTagFunc(tagName) { function makeTags() { // map our global HTML generation functions for (let tag of tags) { - this[tag] = makeTagFunc(tag.toLowerCase()); + this[tag] = makeTagFunc(tag.toLowerCase()); } } @@ -137,7 +217,7 @@ function runServer() { // verify server address // if a.b.c.d or 'localhost' - if (typeof(_SERVER_ADDR) != "undefined") { + if (typeof _SERVER_ADDR != "undefined") { if (_SERVER_ADDR == "localhost") { gServerAddress = _SERVER_ADDR; } else { @@ -145,40 +225,49 @@ function runServer() { if (quads.length == 4) { var invalid = false; for (var i = 0; i < 4; i++) { - if (quads[i] < 0 || quads[i] > 255) + if (quads[i] < 0 || quads[i] > 255) { invalid = true; + } } - if (!invalid) + if (!invalid) { gServerAddress = _SERVER_ADDR; - else - throw new Error("invalid _SERVER_ADDR, please specify a valid IP Address"); + } else { + throw new Error( + "invalid _SERVER_ADDR, please specify a valid IP Address" + ); + } } } } else { - throw new Error("please define _SERVER_ADDR (as an ip address) before running server.js"); + throw new Error( + "please define _SERVER_ADDR (as an ip address) before running server.js" + ); } - if (typeof(_SERVER_PORT) != "undefined") { - if (parseInt(_SERVER_PORT) > 0 && parseInt(_SERVER_PORT) < 65536) + if (typeof _SERVER_PORT != "undefined") { + if (parseInt(_SERVER_PORT) > 0 && parseInt(_SERVER_PORT) < 65536) { SERVER_PORT = _SERVER_PORT; + } } else { - throw new Error("please define _SERVER_PORT (as a port number) before running server.js"); + throw new Error( + "please define _SERVER_PORT (as a port number) before running server.js" + ); } // If DISPLAY_RESULTS is not specified, it defaults to true - if (typeof(_DISPLAY_RESULTS) != "undefined") { + if (typeof _DISPLAY_RESULTS != "undefined") { displayResults = _DISPLAY_RESULTS; } server._start(SERVER_PORT, gServerAddress); // touch a file in the profile directory to indicate we're alive - var foStream = Cc["@mozilla.org/network/file-output-stream;1"] - .createInstance(Ci.nsIFileOutputStream); - var serverAlive = Cc["@mozilla.org/file/local;1"] - .createInstance(Ci.nsIFile); + var foStream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance( + Ci.nsIFileOutputStream + ); + var serverAlive = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile); - if (typeof(_PROFILE_PATH) == "undefined") { + if (typeof _PROFILE_PATH == "undefined") { serverAlive.initWithFile(serverBasePath); serverAlive.append("mochitesttestingprofile"); } else { @@ -188,14 +277,16 @@ function runServer() { // Create a file to inform the harness that the server is ready if (serverAlive.exists()) { serverAlive.append("server_alive.txt"); - foStream.init(serverAlive, - 0x02 | 0x08 | 0x20, 436, 0); // write, create, truncate + foStream.init(serverAlive, 0x02 | 0x08 | 0x20, 436, 0); // write, create, truncate var data = "It's alive!"; foStream.write(data, data.length); foStream.close(); } else { - throw new Error("Failed to create server_alive.txt because " + serverAlive.path + - " could not be found."); + throw new Error( + "Failed to create server_alive.txt because " + + serverAlive.path + + " could not be found." + ); } makeTags(); @@ -204,18 +295,18 @@ function runServer() { // The following is threading magic to spin an event loop -- this has to // happen manually in xpcshell for the server to actually work. // - var thread = Cc["@mozilla.org/thread-manager;1"] - .getService() - .currentThread; - while (!server.isStopped()) + var thread = Cc["@mozilla.org/thread-manager;1"].getService().currentThread; + while (!server.isStopped()) { thread.processNextEvent(true); + } // Server stopped by /server/shutdown handler -- go through pending events // and return. // get rid of any pending requests - while (thread.hasPendingEvents()) + while (thread.hasPendingEvents()) { thread.processNextEvent(true); + } } /** Creates and returns an HTTP server configured to serve Mochitests. */ @@ -238,17 +329,18 @@ function createMochitestServer(serverBasePath) { server.registerContentType("wasm", "application/wasm"); server.setIndexHandler(defaultDirHandler); - var serverRoot = - { - getFile: function getFile(path) { - var file = serverBasePath.clone().QueryInterface(Ci.nsIFile); - path.split("/").forEach(function(p) { - file.appendRelativePath(p); - }); - return file; - }, - QueryInterface(aIID) { return this; }, - }; + var serverRoot = { + getFile: function getFile(path) { + var file = serverBasePath.clone().QueryInterface(Ci.nsIFile); + path.split("/").forEach(function(p) { + file.appendRelativePath(p); + }); + return file; + }, + QueryInterface(aIID) { + return this; + }, + }; server.setObjectState("SERVER_ROOT", serverRoot); @@ -267,27 +359,32 @@ function processLocations(server) { serverLocations.append("server-locations.txt"); const PR_RDONLY = 0x01; - var fis = new FileInputStream(serverLocations, PR_RDONLY, 292 /* 0444 */, - Ci.nsIFileInputStream.CLOSE_ON_EOF); + var fis = new FileInputStream( + serverLocations, + PR_RDONLY, + 292 /* 0444 */, + Ci.nsIFileInputStream.CLOSE_ON_EOF + ); var lis = new ConverterInputStream(fis, "UTF-8", 1024, 0x0); lis.QueryInterface(Ci.nsIUnicharLineInputStream); - const LINE_REGEXP = - new RegExp("^([a-z][-a-z0-9+.]*)" + - "://" + - "(" + - "\\d+\\.\\d+\\.\\d+\\.\\d+" + - "|" + - "(?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\\.)*" + - "[a-z](?:[-a-z0-9]*[a-z0-9])?" + - ")" + - ":" + - "(\\d+)" + - "(?:" + - "\\s+" + - "(\\S+(?:,\\S+)*)" + - ")?$"); + const LINE_REGEXP = new RegExp( + "^([a-z][-a-z0-9+.]*)" + + "://" + + "(" + + "\\d+\\.\\d+\\.\\d+\\.\\d+" + + "|" + + "(?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\\.)*" + + "[a-z](?:[-a-z0-9]*[a-z0-9])?" + + ")" + + ":" + + "(\\d+)" + + "(?:" + + "\\s+" + + "(\\S+(?:,\\S+)*)" + + ")?$" + ); var line = {}; var lineno = 0; @@ -297,19 +394,24 @@ function processLocations(server) { lineno++; var lineValue = line.value; - if (lineValue.charAt(0) == "#" || lineValue == "") + if (lineValue.charAt(0) == "#" || lineValue == "") { continue; + } var match = LINE_REGEXP.exec(lineValue); - if (!match) + if (!match) { throw new Error("Syntax error in server-locations.txt, line " + lineno); + } var [, scheme, host, port, options] = match; if (options) { if (options.split(",").includes("primary")) { if (seenPrimary) { - throw new Error("Multiple primary locations in server-locations.txt, " + - "line " + lineno); + throw new Error( + "Multiple primary locations in server-locations.txt, " + + "line " + + lineno + ); } server.identity.setPrimary(scheme, host, port); @@ -319,8 +421,7 @@ function processLocations(server) { } server.identity.add(scheme, host, port); - } - while (more); + } while (more); } // PATH HANDLERS @@ -340,8 +441,9 @@ function serverShutdown(metadata, response) { // /server/debug?[012] function serverDebug(metadata, response) { response.setStatusLine(metadata.httpVersion, 400, "Bad debugging level"); - if (metadata.queryString.length !== 1) + if (metadata.queryString.length !== 1) { return; + } var mode; if (metadata.queryString === "0") { @@ -409,10 +511,12 @@ function list(requestPath, directory, recurse) { // Sort files by name, so that tests can be run in a pre-defined order inside // a given directory (see bug 384823) function leafNameComparator(first, second) { - if (first.leafName < second.leafName) + if (first.leafName < second.leafName) { return -1; - if (first.leafName > second.leafName) + } + if (first.leafName > second.leafName) { return 1; + } return 0; } files.sort(leafNameComparator); @@ -428,8 +532,8 @@ function list(requestPath, directory, recurse) { [links[key], childCount] = list(key, file, recurse); count += childCount; } else if (file.leafName.charAt(0) != ".") { - links[key] = {"test": {"url": key, "expected": "pass"}}; - } + links[key] = { test: { url: key, expected: "pass" } }; + } } return [links, count]; @@ -441,20 +545,23 @@ function list(requestPath, directory, recurse) { * a supporting file. */ function isTest(filename, pattern) { - if (pattern) + if (pattern) { return pattern.test(filename); + } // File name is a URL style path to a test file, make sure that we check for // tests that start with the appropriate prefix. - var testPrefix = typeof(_TEST_PREFIX) == "string" ? _TEST_PREFIX : "test_"; + var testPrefix = typeof _TEST_PREFIX == "string" ? _TEST_PREFIX : "test_"; var testPattern = new RegExp("^" + testPrefix); var pathPieces = filename.split("/"); - return testPattern.test(pathPieces[pathPieces.length - 1]) && - !filename.includes(".js") && - !filename.includes(".css") && - !/\^headers\^$/.test(filename); + return ( + testPattern.test(pathPieces[pathPieces.length - 1]) && + !filename.includes(".js") && + !filename.includes(".css") && + !/\^headers\^$/.test(filename) + ); } /** @@ -465,11 +572,12 @@ function linksToListItems(links) { var children = ""; for (let link in links) { const value = links[link]; - var classVal = (!isTest(link) && !(value instanceof Object)) - ? "non-test invisible" - : "test"; + var classVal = + !isTest(link) && !(value instanceof Object) + ? "non-test invisible" + : "test"; if (value instanceof Object) { - children = UL({class: "testdir"}, linksToListItems(value)); + children = UL({ class: "testdir" }, linksToListItems(value)); } else { children = ""; } @@ -477,14 +585,20 @@ function linksToListItems(links) { var bug_title = link.match(/test_bug\S+/); var bug_num = null; if (bug_title != null) { - bug_num = bug_title[0].match(/\d+/); + bug_num = bug_title[0].match(/\d+/); } - if ((bug_title == null) || (bug_num == null)) { - response += LI({class: classVal}, A({href: link}, link), children); + if (bug_title == null || bug_num == null) { + response += LI({ class: classVal }, A({ href: link }, link), children); } else { var bug_url = "https://bugzilla.mozilla.org/show_bug.cgi?id=" + bug_num; - response += LI({class: classVal}, A({href: link}, link), " - ", A({href: bug_url}, "Bug " + bug_num), children); + response += LI( + { class: classVal }, + A({ href: link }, link), + " - ", + A({ href: bug_url }, "Bug " + bug_num), + children + ); } } return response; @@ -497,40 +611,48 @@ function linksToTableRows(links, recursionLevel) { var response = ""; for (let link in links) { const value = links[link]; - var classVal = (!isTest(link) && ((value instanceof Object) && ("test" in value))) - ? "non-test invisible" - : ""; + var classVal = + !isTest(link) && (value instanceof Object && "test" in value) + ? "non-test invisible" + : ""; - var spacer = "padding-left: " + (10 * recursionLevel) + "px"; + var spacer = "padding-left: " + 10 * recursionLevel + "px"; - if ((value instanceof Object) && !("test" in value)) { - response += TR({class: "dir", id: "tr-" + link }, - TD({colspan: "3"}, " "), - TD({style: spacer}, - A({href: link}, link))); + if (value instanceof Object && !("test" in value)) { + response += TR( + { class: "dir", id: "tr-" + link }, + TD({ colspan: "3" }, " "), + TD({ style: spacer }, A({ href: link }, link)) + ); response += linksToTableRows(value, recursionLevel + 1); } else { var bug_title = link.match(/test_bug\S+/); var bug_num = null; if (bug_title != null) { - bug_num = bug_title[0].match(/\d+/); + bug_num = bug_title[0].match(/\d+/); } - if ((bug_title == null) || (bug_num == null)) { - response += TR({class: classVal, id: "tr-" + link }, - TD("0"), - TD("0"), - TD("0"), - TD({style: spacer}, - A({href: link}, link))); + if (bug_title == null || bug_num == null) { + response += TR( + { class: classVal, id: "tr-" + link }, + TD("0"), + TD("0"), + TD("0"), + TD({ style: spacer }, A({ href: link }, link)) + ); } else { var bug_url = "https://bugzilla.mozilla.org/show_bug.cgi?id=" + bug_num; - response += TR({class: classVal, id: "tr-" + link }, - TD("0"), - TD("0"), - TD("0"), - TD({style: spacer}, - A({href: link}, link), " - ", - A({href: bug_url}, "Bug " + bug_num))); + response += TR( + { class: classVal, id: "tr-" + link }, + TD("0"), + TD("0"), + TD("0"), + TD( + { style: spacer }, + A({ href: link }, link), + " - ", + A({ href: bug_url }, "Bug " + bug_num) + ) + ); } } } @@ -540,9 +662,9 @@ function linksToTableRows(links, recursionLevel) { function arrayOfTestFiles(linkArray, fileArray, testPattern) { for (let link in linkArray) { const value = linkArray[link]; - if ((value instanceof Object) && !("test" in value)) { + if (value instanceof Object && !("test" in value)) { arrayOfTestFiles(value, fileArray, testPattern); - } else if (isTest(link, testPattern) && (value instanceof Object)) { + } else if (isTest(link, testPattern) && value instanceof Object) { fileArray.push(value.test); } } @@ -553,7 +675,9 @@ function arrayOfTestFiles(linkArray, fileArray, testPattern) { function jsonArrayOfTestFiles(links) { var testFiles = []; arrayOfTestFiles(links, testFiles); - testFiles = testFiles.map(function(file) { return '"' + file.url + '"'; }); + testFiles = testFiles.map(function(file) { + return '"' + file.url + '"'; + }); return "[" + testFiles.join(",\n") + "]"; } @@ -562,19 +686,11 @@ function jsonArrayOfTestFiles(links) { * Produce a normal directory listing. */ function regularListing(metadata, response) { - var [links] = list(metadata.path, - metadata.getProperty("directory"), - false); + var [links] = list(metadata.path, metadata.getProperty("directory"), false); response.write( HTML( - HEAD( - TITLE("mochitest index ", metadata.path) - ), - BODY( - BR(), - A({href: ".."}, "Up a level"), - UL(linksToListItems(links)) - ) + HEAD(TITLE("mochitest index ", metadata.path)), + BODY(BR(), A({ href: ".." }, "Up a level"), UL(linksToListItems(links))) ) ); } @@ -584,21 +700,29 @@ function regularListing(metadata, response) { * it into an object for creating a table of clickable links for each test. */ function convertManifestToTestLinks(root, manifest) { - const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); + const { NetUtil } = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); var manifestFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile); manifestFile.initWithFile(serverBasePath); manifestFile.append(manifest); - var manifestStream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream); + var manifestStream = Cc[ + "@mozilla.org/network/file-input-stream;1" + ].createInstance(Ci.nsIFileInputStream); manifestStream.init(manifestFile, -1, 0, 0); - var manifestObj = JSON.parse(NetUtil.readInputStreamToString(manifestStream, - manifestStream.available())); + var manifestObj = JSON.parse( + NetUtil.readInputStreamToString(manifestStream, manifestStream.available()) + ); var paths = manifestObj.tests; var pathPrefix = "/" + root + "/"; - return [paths.reduce(function(t, p) { t[pathPrefix + p.path] = true; return t; }, {}), - paths.length]; + return [ + paths.reduce(function(t, p) { + t[pathPrefix + p.path] = true; + return t; + }, {}), + paths.length, + ]; } /** @@ -609,98 +733,125 @@ function testListing(metadata, response) { var links = {}; var count = 0; if (!metadata.queryString.includes("manifestFile")) { - [links, count] = list(metadata.path, - metadata.getProperty("directory"), - true); - } else if (typeof(Components) != undefined) { + [links, count] = list( + metadata.path, + metadata.getProperty("directory"), + true + ); + } else if (typeof Components != undefined) { var manifest = metadata.queryString.match(/manifestFile=([^&]+)/)[1]; - [links, count] = convertManifestToTestLinks(metadata.path.split("/")[1], - manifest); + [links, count] = convertManifestToTestLinks( + metadata.path.split("/")[1], + manifest + ); } - var table_class = metadata.queryString.indexOf("hideResultsTable=1") > -1 ? "invisible" : ""; + var table_class = + metadata.queryString.indexOf("hideResultsTable=1") > -1 ? "invisible" : ""; - let testname = (metadata.queryString.indexOf("testname=") > -1) - ? metadata.queryString.match(/testname=([^&]+)/)[1] - : ""; + let testname = + metadata.queryString.indexOf("testname=") > -1 + ? metadata.queryString.match(/testname=([^&]+)/)[1] + : ""; dumpn("count: " + count); - var tests = testname - ? "['/" + testname + "']" - : jsonArrayOfTestFiles(links); + var tests = testname ? "['/" + testname + "']" : jsonArrayOfTestFiles(links); response.write( HTML( HEAD( TITLE("MochiTest | ", metadata.path), - LINK({rel: "stylesheet", - type: "text/css", href: "/static/harness.css"} - ), - SCRIPT({type: "text/javascript", - src: "/tests/SimpleTest/StructuredLog.jsm"}), - SCRIPT({type: "text/javascript", - src: "/tests/SimpleTest/LogController.js"}), - SCRIPT({type: "text/javascript", - src: "/tests/SimpleTest/MemoryStats.js"}), - SCRIPT({type: "text/javascript", - src: "/tests/SimpleTest/TestRunner.js"}), - SCRIPT({type: "text/javascript", - src: "/tests/SimpleTest/MozillaLogger.js"}), - SCRIPT({type: "text/javascript", - src: "/chunkifyTests.js"}), - SCRIPT({type: "text/javascript", - src: "/manifestLibrary.js"}), - SCRIPT({type: "text/javascript", - src: "/tests/SimpleTest/setup.js"}), - SCRIPT({type: "text/javascript"}, - "window.onload = hookup; gTestList=" + tests + ";" + LINK({ + rel: "stylesheet", + type: "text/css", + href: "/static/harness.css", + }), + SCRIPT({ + type: "text/javascript", + src: "/tests/SimpleTest/StructuredLog.jsm", + }), + SCRIPT({ + type: "text/javascript", + src: "/tests/SimpleTest/LogController.js", + }), + SCRIPT({ + type: "text/javascript", + src: "/tests/SimpleTest/MemoryStats.js", + }), + SCRIPT({ + type: "text/javascript", + src: "/tests/SimpleTest/TestRunner.js", + }), + SCRIPT({ + type: "text/javascript", + src: "/tests/SimpleTest/MozillaLogger.js", + }), + SCRIPT({ type: "text/javascript", src: "/chunkifyTests.js" }), + SCRIPT({ type: "text/javascript", src: "/manifestLibrary.js" }), + SCRIPT({ type: "text/javascript", src: "/tests/SimpleTest/setup.js" }), + SCRIPT( + { type: "text/javascript" }, + "window.onload = hookup; gTestList=" + tests + ";" ) ), BODY( - DIV({class: "container"}, - H2("--> ", A({href: "#", id: "runtests"}, "Run Tests"), " <--"), - P({style: "float: right;"}, + DIV( + { class: "container" }, + H2("--> ", A({ href: "#", id: "runtests" }, "Run Tests"), " <--"), + P( + { style: "float: right;" }, SMALL( "Based on the ", - A({href: "http://www.mochikit.com/"}, "MochiKit"), + A({ href: "http://www.mochikit.com/" }, "MochiKit"), " unit tests." ) ), - DIV({class: "status"}, - H1({id: "indicator"}, "Status"), - H2({id: "pass"}, "Passed: ", SPAN({id: "pass-count"}, "0")), - H2({id: "fail"}, "Failed: ", SPAN({id: "fail-count"}, "0")), - H2({id: "fail"}, "Todo: ", SPAN({id: "todo-count"}, "0")) + DIV( + { class: "status" }, + H1({ id: "indicator" }, "Status"), + H2({ id: "pass" }, "Passed: ", SPAN({ id: "pass-count" }, "0")), + H2({ id: "fail" }, "Failed: ", SPAN({ id: "fail-count" }, "0")), + H2({ id: "fail" }, "Todo: ", SPAN({ id: "todo-count" }, "0")) ), - DIV({class: "clear"}), - DIV({id: "current-test"}, - B("Currently Executing: ", - SPAN({id: "current-test-path"}, "_") - ) + DIV({ class: "clear" }), + DIV( + { id: "current-test" }, + B("Currently Executing: ", SPAN({ id: "current-test-path" }, "_")) ), - DIV({class: "clear"}), - DIV({class: "frameholder"}, - IFRAME({scrolling: "no", id: "testframe", "allowfullscreen": true}) + DIV({ class: "clear" }), + DIV( + { class: "frameholder" }, + IFRAME({ scrolling: "no", id: "testframe", allowfullscreen: true }) ), - DIV({class: "clear"}), - DIV({class: "toggle"}, - A({href: "#", id: "toggleNonTests"}, "Show Non-Tests"), + DIV({ class: "clear" }), + DIV( + { class: "toggle" }, + A({ href: "#", id: "toggleNonTests" }, "Show Non-Tests"), BR() ), - ( - displayResults ? - TABLE({cellpadding: 0, cellspacing: 0, class: table_class, id: "test-table"}, - TR(TD("Passed"), TD("Failed"), TD("Todo"), TD("Test Files")), - linksToTableRows(links, 0) - ) : "" - ), - + displayResults + ? TABLE( + { + cellpadding: 0, + cellspacing: 0, + class: table_class, + id: "test-table", + }, + TR(TD("Passed"), TD("Failed"), TD("Todo"), TD("Test Files")), + linksToTableRows(links, 0) + ) + : "", BR(), - TABLE({cellpadding: 0, cellspacing: 0, border: 1, bordercolor: "red", id: "fail-table"} - ), + TABLE({ + cellpadding: 0, + cellspacing: 0, + border: 1, + bordercolor: "red", + id: "fail-table", + }), - DIV({class: "clear"}) + DIV({ class: "clear" }) ) ) ) diff --git a/testing/mochitest/start_desktop.js b/testing/mochitest/start_desktop.js index 4ca531118393..93d59d935ba9 100644 --- a/testing/mochitest/start_desktop.js +++ b/testing/mochitest/start_desktop.js @@ -4,12 +4,13 @@ // Defined by Marionette. /* global __webDriverArguments */ -const flavor = __webDriverArguments[0].flavor; +const flavor = __webDriverArguments[0].flavor; const url = __webDriverArguments[0].testUrl; // eslint-disable-next-line mozilla/use-services -let wm = Cc["@mozilla.org/appshell/window-mediator;1"] - .getService(Ci.nsIWindowMediator); +let wm = Cc["@mozilla.org/appshell/window-mediator;1"].getService( + Ci.nsIWindowMediator +); let win = wm.getMostRecentWindow("navigator:browser"); if (!win) { win = wm.getMostRecentWindow("mail:3pane"); @@ -17,5 +18,5 @@ if (!win) { // mochikit's bootstrap.js has set up a listener for this event. It's // used so bootstrap.js knows which flavor and url to load. -let ev = new CustomEvent("mochitest-load", {"detail": [flavor, url]}); +let ev = new CustomEvent("mochitest-load", { detail: [flavor, url] }); win.dispatchEvent(ev); diff --git a/testing/mochitest/tests/browser/browser_BrowserTestUtils.js b/testing/mochitest/tests/browser/browser_BrowserTestUtils.js index 5c84d340be06..2f1f667cbd9d 100644 --- a/testing/mochitest/tests/browser/browser_BrowserTestUtils.js +++ b/testing/mochitest/tests/browser/browser_BrowserTestUtils.js @@ -5,12 +5,19 @@ function getLastEventDetails(browser) { } add_task(async function() { - let onClickEvt = 'document.getElementById("out").textContent = event.target.localName + "," + event.clientX + "," + event.clientY;'; - const url = "" + - "" + - "
Other
" + - ""; - let tab = await BrowserTestUtils.openNewForegroundTab(gBrowser, "data:text/html," + url); + let onClickEvt = + 'document.getElementById("out").textContent = event.target.localName + "," + event.clientX + "," + event.clientY;'; + const url = + "" + + "" + + "
Other
" + + ""; + let tab = await BrowserTestUtils.openNewForegroundTab( + gBrowser, + "data:text/html," + url + ); let browser = tab.linkedBrowser; await BrowserTestUtils.synthesizeMouseAtCenter("#one", {}, browser); @@ -34,25 +41,53 @@ add_task(async function() { details = await getLastEventDetails(browser); is(details, "div,40,84", "synthesizeMouseAtCenter with complex selector"); - let cancelled = await BrowserTestUtils.synthesizeMouseAtCenter("body > div", { type: "mousedown" }, browser); + let cancelled = await BrowserTestUtils.synthesizeMouseAtCenter( + "body > div", + { type: "mousedown" }, + browser + ); details = await getLastEventDetails(browser); - is(details, "div,40,84", "synthesizeMouseAtCenter mousedown with complex selector"); - ok(cancelled, "synthesizeMouseAtCenter mousedown with complex selector not cancelled"); + is( + details, + "div,40,84", + "synthesizeMouseAtCenter mousedown with complex selector" + ); + ok( + cancelled, + "synthesizeMouseAtCenter mousedown with complex selector not cancelled" + ); - cancelled = await BrowserTestUtils.synthesizeMouseAtCenter("body > div", { type: "mouseup" }, browser); + cancelled = await BrowserTestUtils.synthesizeMouseAtCenter( + "body > div", + { type: "mouseup" }, + browser + ); details = await getLastEventDetails(browser); - is(details, "div,40,84", "synthesizeMouseAtCenter mouseup with complex selector"); - ok(!cancelled, "synthesizeMouseAtCenter mouseup with complex selector cancelled"); + is( + details, + "div,40,84", + "synthesizeMouseAtCenter mouseup with complex selector" + ); + ok( + !cancelled, + "synthesizeMouseAtCenter mouseup with complex selector cancelled" + ); gBrowser.removeTab(tab); }); add_task(async function() { await BrowserTestUtils.registerAboutPage( - registerCleanupFunction, "about-pages-are-cool", - getRootDirectory(gTestPath) + "dummy.html", 0); + registerCleanupFunction, + "about-pages-are-cool", + getRootDirectory(gTestPath) + "dummy.html", + 0 + ); let tab = await BrowserTestUtils.openNewForegroundTab( - gBrowser, "about:about-pages-are-cool", true); + gBrowser, + "about:about-pages-are-cool", + true + ); ok(tab, "Successfully created an about: page and loaded it."); BrowserTestUtils.removeTab(tab); try { @@ -61,11 +96,20 @@ add_task(async function() { } catch (ex) { ok(false, "Should not throw unregistering a known about: page"); } - await BrowserTestUtils.unregisterAboutPage("random-other-about-page").then(() => { - ok(false, "Should not have succeeded unregistering an unknown about: page."); - }, () => { - ok(true, "Should have returned a rejected promise trying to unregister an unknown about page"); - }); + await BrowserTestUtils.unregisterAboutPage("random-other-about-page").then( + () => { + ok( + false, + "Should not have succeeded unregistering an unknown about: page." + ); + }, + () => { + ok( + true, + "Should have returned a rejected promise trying to unregister an unknown about page" + ); + } + ); }); add_task(async function testWaitForEvent() { @@ -76,16 +120,28 @@ add_task(async function testWaitForEvent() { // Use capturing phase to make sure the event listener added by // BrowserTestUtils.waitForEvent is called before the normal event listener // below. - let eventPromise = BrowserTestUtils.waitForEvent(gBrowser, "dummyevent", true); + let eventPromise = BrowserTestUtils.waitForEvent( + gBrowser, + "dummyevent", + true + ); eventPromise.then(() => { waitForEventResolved = true; }); // Add normal event listener that is called after the event listener added by // BrowserTestUtils.waitForEvent. - gBrowser.addEventListener("dummyevent", () => { - eventListenerCalled = true; - is(waitForEventResolved, false, "BrowserTestUtils.waitForEvent promise resolution handler shouldn't be called at this point."); - }, { once: true }); + gBrowser.addEventListener( + "dummyevent", + () => { + eventListenerCalled = true; + is( + waitForEventResolved, + false, + "BrowserTestUtils.waitForEvent promise resolution handler shouldn't be called at this point." + ); + }, + { once: true } + ); var event = new CustomEvent("dummyevent"); gBrowser.dispatchEvent(event); diff --git a/testing/mochitest/tests/browser/browser_browserLoaded_content_loaded.js b/testing/mochitest/tests/browser/browser_browserLoaded_content_loaded.js index 231433690324..ff6665fc3eb6 100644 --- a/testing/mochitest/tests/browser/browser_browserLoaded_content_loaded.js +++ b/testing/mochitest/tests/browser/browser_browserLoaded_content_loaded.js @@ -4,8 +4,11 @@ function isDOMLoaded(browser) { return ContentTask.spawn(browser, null, async function() { - Assert.equal(content.document.readyState, "complete", - "Browser should be loaded."); + Assert.equal( + content.document.readyState, + "complete", + "Browser should be loaded." + ); }); } @@ -28,14 +31,18 @@ add_task(async function() { `http://test:80`, ]; // Add tabs, get the respective browsers - let browsers = tabURLs.map(u => BrowserTestUtils.addTab(gBrowser, u).linkedBrowser); + let browsers = tabURLs.map( + u => BrowserTestUtils.addTab(gBrowser, u).linkedBrowser + ); // wait for promises to settle - await Promise.all((function* () { - for (let b of browsers) { - yield BrowserTestUtils.browserLoaded(b); - } - })()); + await Promise.all( + (function*() { + for (let b of browsers) { + yield BrowserTestUtils.browserLoaded(b); + } + })() + ); for (const browser of browsers) { await isDOMLoaded(browser); } diff --git a/testing/mochitest/tests/browser/browser_fail_add_task_uncaught_rejection.js b/testing/mochitest/tests/browser/browser_fail_add_task_uncaught_rejection.js index 2cf27db2b126..f420b370372f 100644 --- a/testing/mochitest/tests/browser/browser_fail_add_task_uncaught_rejection.js +++ b/testing/mochitest/tests/browser/browser_fail_add_task_uncaught_rejection.js @@ -6,7 +6,8 @@ setExpectedFailuresForSelfTest(8); // Keep "JSMPromise" separate so "Promise" still refers to native Promises. -let JSMPromise = ChromeUtils.import("resource://gre/modules/Promise.jsm", {}).Promise; +let JSMPromise = ChromeUtils.import("resource://gre/modules/Promise.jsm", {}) + .Promise; async function rejectOnNextTick(error) { await Promise.resolve(); diff --git a/testing/mochitest/tests/browser/browser_fail_uncaught_rejection.js b/testing/mochitest/tests/browser/browser_fail_uncaught_rejection.js index 7db8eed0819e..4fd36ade6492 100644 --- a/testing/mochitest/tests/browser/browser_fail_uncaught_rejection.js +++ b/testing/mochitest/tests/browser/browser_fail_uncaught_rejection.js @@ -1,7 +1,8 @@ setExpectedFailuresForSelfTest(3); // Keep "JSMPromise" separate so "Promise" still refers to native Promises. -let JSMPromise = ChromeUtils.import("resource://gre/modules/Promise.jsm", {}).Promise; +let JSMPromise = ChromeUtils.import("resource://gre/modules/Promise.jsm", {}) + .Promise; function test() { Promise.reject(new Error("Promise rejection.")); diff --git a/testing/mochitest/tests/browser/browser_getTestFile.js b/testing/mochitest/tests/browser/browser_getTestFile.js index 4793eb8b4689..d1b0287ddea7 100644 --- a/testing/mochitest/tests/browser/browser_getTestFile.js +++ b/testing/mochitest/tests/browser/browser_getTestFile.js @@ -1,6 +1,6 @@ function test() { - let {Promise} = ChromeUtils.import("resource://gre/modules/Promise.jsm"); - const {OS} = ChromeUtils.import("resource://gre/modules/osfile.jsm"); + let { Promise } = ChromeUtils.import("resource://gre/modules/Promise.jsm"); + const { OS } = ChromeUtils.import("resource://gre/modules/osfile.jsm"); let decoder = new TextDecoder(); waitForExplicitFinish(); @@ -10,35 +10,46 @@ function test() { }, "getTestFilePath rejects absolute paths"); Promise.all([ - OS.File.exists(getTestFilePath("browser_getTestFile.js")) - .then(function(exists) { - ok(exists, "getTestFilePath consider the path as being relative"); - }), + OS.File.exists(getTestFilePath("browser_getTestFile.js")).then(function( + exists + ) { + ok(exists, "getTestFilePath consider the path as being relative"); + }), - OS.File.exists(getTestFilePath("./browser_getTestFile.js")) - .then(function(exists) { - ok(exists, "getTestFilePath also accepts explicit relative path"); - }), + OS.File.exists(getTestFilePath("./browser_getTestFile.js")).then(function( + exists + ) { + ok(exists, "getTestFilePath also accepts explicit relative path"); + }), - OS.File.exists(getTestFilePath("./browser_getTestFileTypo.xul")) - .then(function(exists) { + OS.File.exists(getTestFilePath("./browser_getTestFileTypo.xul")).then( + function(exists) { ok(!exists, "getTestFilePath do not throw if the file doesn't exists"); - }), + } + ), - OS.File.read(getTestFilePath("test-dir/test-file")) - .then(function(array) { - is(decoder.decode(array), "foo\n", "getTestFilePath can reach sub-folder files 1/2"); - }), + OS.File.read(getTestFilePath("test-dir/test-file")).then(function(array) { + is( + decoder.decode(array), + "foo\n", + "getTestFilePath can reach sub-folder files 1/2" + ); + }), - OS.File.read(getTestFilePath("./test-dir/test-file")) - .then(function(array) { - is(decoder.decode(array), "foo\n", "getTestFilePath can reach sub-folder files 2/2"); - }), - - ]).then(function() { - finish(); - }, function(error) { - ok(false, error); - finish(); - }); + OS.File.read(getTestFilePath("./test-dir/test-file")).then(function(array) { + is( + decoder.decode(array), + "foo\n", + "getTestFilePath can reach sub-folder files 2/2" + ); + }), + ]).then( + function() { + finish(); + }, + function(error) { + ok(false, error); + finish(); + } + ); } diff --git a/testing/mochitest/tests/browser/browser_head.js b/testing/mochitest/tests/browser/browser_head.js index 0e1f7dd25f20..b7330a0fc0cd 100644 --- a/testing/mochitest/tests/browser/browser_head.js +++ b/testing/mochitest/tests/browser/browser_head.js @@ -2,7 +2,11 @@ var testVar; registerCleanupFunction(function() { ok(true, "I'm a cleanup function in test file"); - is(this.testVar, "I'm a var in test file", "Test cleanup function scope is correct"); + is( + this.testVar, + "I'm a var in test file", + "Test cleanup function scope is correct" + ); }); function test() { diff --git a/testing/mochitest/tests/browser/browser_parameters.js b/testing/mochitest/tests/browser/browser_parameters.js index 32ba82d92d1d..813cd662ba90 100644 --- a/testing/mochitest/tests/browser/browser_parameters.js +++ b/testing/mochitest/tests/browser/browser_parameters.js @@ -1,4 +1,3 @@ function test() { ok(SimpleTest.harnessParameters, "Should have parameters"); } - diff --git a/testing/mochitest/tests/browser/browser_privileges.js b/testing/mochitest/tests/browser/browser_privileges.js index 50cb5c7ac3ff..042a928b9c6b 100644 --- a/testing/mochitest/tests/browser/browser_privileges.js +++ b/testing/mochitest/tests/browser/browser_privileges.js @@ -5,8 +5,9 @@ function test() { // this will throw an exception if we are not running with privileges try { // eslint-disable-next-line no-unused-vars, mozilla/use-services - var prefs = Cc["@mozilla.org/preferences-service;1"]. - getService(Ci.nsIPrefBranch); + var prefs = Cc["@mozilla.org/preferences-service;1"].getService( + Ci.nsIPrefBranch + ); } catch (e) { hasPrivileges = false; } diff --git a/testing/mochitest/tests/browser/browser_uncaught_rejection_expected.js b/testing/mochitest/tests/browser/browser_uncaught_rejection_expected.js index f0735ffb2fb4..86dcb49ff0a7 100644 --- a/testing/mochitest/tests/browser/browser_uncaught_rejection_expected.js +++ b/testing/mochitest/tests/browser/browser_uncaught_rejection_expected.js @@ -1,5 +1,6 @@ // Keep "JSMPromise" separate so "Promise" still refers to native Promises. -let JSMPromise = ChromeUtils.import("resource://gre/modules/Promise.jsm", {}).Promise; +let JSMPromise = ChromeUtils.import("resource://gre/modules/Promise.jsm", {}) + .Promise; ChromeUtils.import("resource://testing-common/PromiseTestUtils.jsm", this); PromiseTestUtils.whitelistRejectionsGlobally(/Whitelisted rejection./); diff --git a/testing/mochitest/tests/browser/browser_waitForFocus.js b/testing/mochitest/tests/browser/browser_waitForFocus.js index eca3980a2b8d..1e0bac586608 100644 --- a/testing/mochitest/tests/browser/browser_waitForFocus.js +++ b/testing/mochitest/tests/browser/browser_waitForFocus.js @@ -1,4 +1,3 @@ - const gBaseURL = "https://example.com/browser/testing/mochitest/tests/browser/"; function promiseTabLoadEvent(tab, url) { @@ -18,7 +17,11 @@ add_task(async function() { let browser = gBrowser.selectedBrowser; await SimpleTest.promiseFocus(browser, true); - is(document.activeElement, browser, "Browser is focused when about:blank is loaded"); + is( + document.activeElement, + browser, + "Browser is focused when about:blank is loaded" + ); gBrowser.removeCurrentTab(); gURLBar.focus(); @@ -35,7 +38,11 @@ add_task(async function() { if (browser.contentWindow) { await SimpleTest.promiseFocus(browser.contentWindow, true); - is(document.activeElement, browser, "Browser is focused when about:blank is loaded"); + is( + document.activeElement, + browser, + "Browser is focused when about:blank is loaded" + ); } gBrowser.removeCurrentTab(); @@ -55,11 +62,19 @@ add_task(async function() { await SimpleTest.promiseFocus(browser.contentWindow); - is(document.activeElement, browser, "Browser is focused when page is loaded"); + is( + document.activeElement, + browser, + "Browser is focused when page is loaded" + ); await SimpleTest.promiseFocus(browser.contentWindow.frames[0]); - is(browser.contentWindow.document.activeElement.localName, "iframe", "Child iframe is focused"); + is( + browser.contentWindow.document.activeElement.localName, + "iframe", + "Child iframe is focused" + ); } gBrowser.removeCurrentTab(); @@ -67,13 +82,20 @@ add_task(async function() { // Pass a browser to promiseFocus add_task(async function() { - await BrowserTestUtils.openNewForegroundTab(gBrowser, gBaseURL + "waitForFocusPage.html"); + await BrowserTestUtils.openNewForegroundTab( + gBrowser, + gBaseURL + "waitForFocusPage.html" + ); gURLBar.focus(); await SimpleTest.promiseFocus(gBrowser.selectedBrowser); - is(document.activeElement, gBrowser.selectedBrowser, "Browser is focused when promiseFocus is passed a browser"); + is( + document.activeElement, + gBrowser.selectedBrowser, + "Browser is focused when promiseFocus is passed a browser" + ); gBrowser.removeCurrentTab(); }); diff --git a/testing/mochitest/tests/browser/head.js b/testing/mochitest/tests/browser/head.js index cb549679b286..cd9565f7439c 100644 --- a/testing/mochitest/tests/browser/head.js +++ b/testing/mochitest/tests/browser/head.js @@ -8,5 +8,9 @@ ok(true, "I'm a test in head file"); registerCleanupFunction(function() { ok(true, "I'm a cleanup function in head file"); - is(this.headVar, "I'm a var in head file", "Head cleanup function scope is correct"); + is( + this.headVar, + "I'm a var in head file", + "Head cleanup function scope is correct" + ); }); diff --git a/testing/modules/AppData.jsm b/testing/modules/AppData.jsm index 58128d057b7a..9ec11e8f819f 100644 --- a/testing/modules/AppData.jsm +++ b/testing/modules/AppData.jsm @@ -4,13 +4,11 @@ "use strict"; -var EXPORTED_SYMBOLS = [ - "makeFakeAppDir", -]; +var EXPORTED_SYMBOLS = ["makeFakeAppDir"]; -const {OS} = ChromeUtils.import("resource://gre/modules/osfile.jsm"); -const {Promise} = ChromeUtils.import("resource://gre/modules/Promise.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { OS } = ChromeUtils.import("resource://gre/modules/osfile.jsm"); +const { Promise } = ChromeUtils.import("resource://gre/modules/Promise.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); // Reference needed in order for fake app dir provider to be active. var gFakeAppDirectoryProvider; @@ -72,8 +70,10 @@ var makeFakeAppDir = function() { }, QueryInterace(iid) { - if (iid.equals(Ci.nsIDirectoryServiceProvider) || - iid.equals(Ci.nsISupports)) { + if ( + iid.equals(Ci.nsIDirectoryServiceProvider) || + iid.equals(Ci.nsISupports) + ) { return this; } diff --git a/testing/modules/AppInfo.jsm b/testing/modules/AppInfo.jsm index 773988a74ce0..d0e78b7afdc0 100644 --- a/testing/modules/AppInfo.jsm +++ b/testing/modules/AppInfo.jsm @@ -4,19 +4,16 @@ "use strict"; -var EXPORTED_SYMBOLS = [ - "newAppInfo", - "getAppInfo", - "updateAppInfo", -]; +var EXPORTED_SYMBOLS = ["newAppInfo", "getAppInfo", "updateAppInfo"]; - -let origPlatformInfo = Cc["@mozilla.org/xre/app-info;1"] - .getService(Ci.nsIPlatformInfo); +let origPlatformInfo = Cc["@mozilla.org/xre/app-info;1"].getService( + Ci.nsIPlatformInfo +); // eslint-disable-next-line mozilla/use-services -let origRuntime = Cc["@mozilla.org/xre/app-info;1"] - .getService(Ci.nsIXULRuntime); +let origRuntime = Cc["@mozilla.org/xre/app-info;1"].getService( + Ci.nsIXULRuntime +); /** * Create new XULAppInfo instance with specified options. @@ -32,13 +29,13 @@ let origRuntime = Cc["@mozilla.org/xre/app-info;1"] * extraProps: extra properties added to XULAppInfo */ var newAppInfo = function(options = {}) { - let ID = ("ID" in options) ? options.ID : "xpcshell@tests.mozilla.org"; - let name = ("name" in options) ? options.name : "xpcshell"; - let version = ("version" in options) ? options.version : "1"; - let platformVersion - = ("platformVersion" in options) ? options.platformVersion : "p-ver"; - let OS = ("OS" in options) ? options.OS : "XPCShell"; - let extraProps = ("extraProps" in options) ? options.extraProps : {}; + let ID = "ID" in options ? options.ID : "xpcshell@tests.mozilla.org"; + let name = "name" in options ? options.name : "xpcshell"; + let version = "version" in options ? options.version : "1"; + let platformVersion = + "platformVersion" in options ? options.platformVersion : "p-ver"; + let OS = "OS" in options ? options.OS : "XPCShell"; + let extraProps = "extraProps" in options ? options.extraProps : {}; let appInfo = { // nsIXULAppInfo @@ -68,9 +65,7 @@ var newAppInfo = function(options = {}) { }, }; - let interfaces = [Ci.nsIXULAppInfo, - Ci.nsIPlatformInfo, - Ci.nsIXULRuntime]; + let interfaces = [Ci.nsIXULAppInfo, Ci.nsIPlatformInfo, Ci.nsIXULRuntime]; if ("nsIWinAppHelper" in Ci) { interfaces.push(Ci.nsIWinAppHelper); } @@ -98,7 +93,9 @@ var currentAppInfo = newAppInfo(); /** * Obtain a reference to the current object used to define XULAppInfo. */ -var getAppInfo = function() { return currentAppInfo; }; +var getAppInfo = function() { + return currentAppInfo; +}; /** * Update the current application info. @@ -117,7 +114,10 @@ var updateAppInfo = function(options) { // Unregister an existing factory if one exists. try { - let existing = Components.manager.getClassObjectByContractID(contractid, Ci.nsIFactory); + let existing = Components.manager.getClassObjectByContractID( + contractid, + Ci.nsIFactory + ); registrar.unregisterFactory(id, existing); } catch (ex) {} diff --git a/testing/modules/Assert.jsm b/testing/modules/Assert.jsm index 89499aa9167c..9a56c6745ebe 100644 --- a/testing/modules/Assert.jsm +++ b/testing/modules/Assert.jsm @@ -12,14 +12,17 @@ "use strict"; -var EXPORTED_SYMBOLS = [ - "Assert", -]; +var EXPORTED_SYMBOLS = ["Assert"]; -const {ObjectUtils} = ChromeUtils.import("resource://gre/modules/ObjectUtils.jsm"); +const { ObjectUtils } = ChromeUtils.import( + "resource://gre/modules/ObjectUtils.jsm" +); -ChromeUtils.defineModuleGetter(this, "Promise", - "resource://gre/modules/Promise.jsm"); +ChromeUtils.defineModuleGetter( + this, + "Promise", + "resource://gre/modules/Promise.jsm" +); /** * 1. The assert module provides functions that throw AssertionError's when * particular conditions are not met. @@ -33,12 +36,14 @@ ChromeUtils.defineModuleGetter(this, "Promise", * test-only modules. This is false when the reporter is set by content scripts, * because they may still run in the parent process. */ -var Assert = this.Assert = function(reporterFunc, isDefault) { - if (reporterFunc) +var Assert = (this.Assert = function(reporterFunc, isDefault) { + if (reporterFunc) { this.setReporter(reporterFunc); - if (isDefault) + } + if (isDefault) { Assert.setReporter(reporterFunc); -}; + } +}); // This allows using the Assert object as an additional global instance. Object.setPrototypeOf(Assert, Assert.prototype); @@ -66,7 +71,7 @@ function truncate(text, newLength = kTruncateLength) { if (typeof text == "string") { return text.length < newLength ? text : text.slice(0, newLength); } - return text; + return text; } function getMessage(error, prefix = "") { @@ -86,8 +91,13 @@ function getMessage(error, prefix = "") { let message = prefix; if (error.operator) { let truncateLength = error.truncate ? kTruncateLength : Infinity; - message += (prefix ? " - " : "") + truncate(actual, truncateLength) + " " + - error.operator + " " + truncate(expected, truncateLength); + message += + (prefix ? " - " : "") + + truncate(actual, truncateLength) + + " " + + error.operator + + " " + + truncate(expected, truncateLength); } return message; } @@ -191,11 +201,21 @@ proto.setReporter = function(reporterFunc) { * @param truncate (optional) [true] * (boolean) Whether or not `actual` and `expected` should be truncated when printing */ -proto.report = function(failed, actual, expected, message, operator, truncate = true) { +proto.report = function( + failed, + actual, + expected, + message, + operator, + truncate = true +) { // Although not ideal, we allow a "null" message due to the way some of the extension tests // work. if (message !== undefined && message !== null && typeof message != "string") { - this.ok(false, `Expected a string or undefined for the error message to Assert.*, got ${typeof message}`); + this.ok( + false, + `Expected a string or undefined for the error message to Assert.*, got ${typeof message}` + ); } let err = new Assert.AssertionError({ message, @@ -228,7 +248,13 @@ proto.report = function(failed, actual, expected, message, operator, truncate = */ proto.ok = function(value, message) { if (arguments.length > 2) { - this.report(true, false, true, "Too many arguments passed to `Assert.ok()`", "=="); + this.report( + true, + false, + true, + "Too many arguments passed to `Assert.ok()`", + "==" + ); } else { this.report(!value, value, true, message, "=="); } @@ -281,7 +307,14 @@ proto.notEqual = function notEqual(actual, expected, message) { * (string) Short explanation of the expected result */ proto.deepEqual = function deepEqual(actual, expected, message) { - this.report(!ObjectUtils.deepEqual(actual, expected), actual, expected, message, "deepEqual", false); + this.report( + !ObjectUtils.deepEqual(actual, expected), + actual, + expected, + message, + "deepEqual", + false + ); }; /** @@ -296,7 +329,14 @@ proto.deepEqual = function deepEqual(actual, expected, message) { * (string) Short explanation of the expected result */ proto.notDeepEqual = function notDeepEqual(actual, expected, message) { - this.report(ObjectUtils.deepEqual(actual, expected), actual, expected, message, "notDeepEqual", false); + this.report( + ObjectUtils.deepEqual(actual, expected), + actual, + expected, + message, + "notDeepEqual", + false + ); }; /** @@ -331,14 +371,21 @@ proto.notStrictEqual = function notStrictEqual(actual, expected, message) { function checkExpectedArgument(instance, funcName, expected) { if (!expected) { - instance.ok(false, `Error: The 'expected' argument was not supplied to Assert.${funcName}()`); + instance.ok( + false, + `Error: The 'expected' argument was not supplied to Assert.${funcName}()` + ); } - if (!instanceOf(expected, "RegExp") && - typeof expected !== "function" && - typeof expected !== "object") { - instance.ok(false, - `Error: The 'expected' argument to Assert.${funcName}() must be a RegExp, function or an object`); + if ( + !instanceOf(expected, "RegExp") && + typeof expected !== "function" && + typeof expected !== "object" + ) { + instance.ok( + false, + `Error: The 'expected' argument to Assert.${funcName}() must be a RegExp, function or an object` + ); } } @@ -349,10 +396,12 @@ function expectedException(actual, expected) { if (instanceOf(expected, "RegExp")) { return expected.test(actual); - // We need to guard against the right hand parameter of "instanceof" lacking - // the "prototype" property, which is true of arrow functions in particular. - } else if (!(typeof expected === "function" && !expected.prototype) && - actual instanceof expected) { + // We need to guard against the right hand parameter of "instanceof" lacking + // the "prototype" property, which is true of arrow functions in particular. + } else if ( + !(typeof expected === "function" && !expected.prototype) && + actual instanceof expected + ) { return true; } else if (expected.call({}, actual) === true) { return true; @@ -393,14 +442,15 @@ proto.throws = function(block, expected, message) { actual = e; } - message = (expected.name ? " (" + expected.name + ")." : ".") + - (message ? " " + message : "."); + message = + (expected.name ? " (" + expected.name + ")." : ".") + + (message ? " " + message : "."); if (!actual) { this.report(true, actual, expected, "Missing expected exception" + message); } - if ((actual && !expectedException(actual, expected))) { + if (actual && !expectedException(actual, expected)) { throw actual; } @@ -421,17 +471,25 @@ proto.throws = function(block, expected, message) { proto.rejects = function(promise, expected, message) { checkExpectedArgument(this, "rejects", expected); return new Promise((resolve, reject) => { - return promise.then( - () => this.report(true, null, expected, "Missing expected exception " + message), - err => { - if (!expectedException(err, expected)) { - reject(err); - return; + return promise + .then( + () => + this.report( + true, + null, + expected, + "Missing expected exception " + message + ), + err => { + if (!expectedException(err, expected)) { + reject(err); + return; + } + this.report(false, err, expected, message); + resolve(); } - this.report(false, err, expected, message); - resolve(); - } - ).catch(reject); + ) + .catch(reject); }); }; diff --git a/testing/modules/CoverageUtils.jsm b/testing/modules/CoverageUtils.jsm index f93c78a9ae16..6826d01a357b 100644 --- a/testing/modules/CoverageUtils.jsm +++ b/testing/modules/CoverageUtils.jsm @@ -4,12 +4,12 @@ "use strict"; -var EXPORTED_SYMBOLS = [ - "CoverageCollector", -]; +var EXPORTED_SYMBOLS = ["CoverageCollector"]; /* globals Debugger */ -const {addDebuggerToGlobal} = ChromeUtils.import("resource://gre/modules/jsdebugger.jsm"); +const { addDebuggerToGlobal } = ChromeUtils.import( + "resource://gre/modules/jsdebugger.jsm" +); addDebuggerToGlobal(Cu.getGlobalForObject(this)); /** @@ -22,7 +22,7 @@ var CoverageCollector = function(prefix) { this._dbg.addAllGlobalsAsDebuggees(); this._scripts = this._dbg.findScripts(); - this._dbg.onNewScript = (script) => { + this._dbg.onNewScript = script => { this._scripts.push(script); }; @@ -44,7 +44,7 @@ CoverageCollector.prototype._getLinesCovered = function() { } cov.forEach(covered => { - let {lineNumber, columnNumber, offset, count} = covered; + let { lineNumber, columnNumber, offset, count } = covered; if (!count) { return; } @@ -71,10 +71,11 @@ CoverageCollector.prototype._getLinesCovered = function() { // any offset on a particular line, that line must have been covered. for (let scriptName in currentCoverage) { for (let key in currentCoverage[scriptName]) { - if (!this._allCoverage[scriptName] || - !this._allCoverage[scriptName][key] || - (this._allCoverage[scriptName][key] < - currentCoverage[scriptName][key])) { + if ( + !this._allCoverage[scriptName] || + !this._allCoverage[scriptName][key] || + this._allCoverage[scriptName][key] < currentCoverage[scriptName][key] + ) { // eslint-disable-next-line no-unused-vars let [lineNumber, colNumber, offset] = key.split("#"); if (!coveredLines[scriptName]) { @@ -100,7 +101,7 @@ CoverageCollector.prototype._getUncoveredLines = function() { } // Get all lines in the script - scriptOffsets.forEach( function(element, index) { + scriptOffsets.forEach(function(element, index) { if (!element) { return; } @@ -138,11 +139,11 @@ CoverageCollector.prototype._getMethodNames = function() { } /** - * Get all lines contained within the method and - * push a record of the form: - * : - */ - scriptOffsets.forEach( function(element, index) { + * Get all lines contained within the method and + * push a record of the form: + * : + */ + scriptOffsets.forEach(function(element, index) { if (!element) { return; } @@ -161,14 +162,17 @@ CoverageCollector.prototype._getMethodNames = function() { */ CoverageCollector.prototype.recordTestCoverage = function(testName) { let ccov_scope = {}; - const {OS} = ChromeUtils.import("resource://gre/modules/osfile.jsm", ccov_scope); + const { OS } = ChromeUtils.import( + "resource://gre/modules/osfile.jsm", + ccov_scope + ); dump("Collecting coverage for: " + testName + "\n"); let rawLines = this._getLinesCovered(testName); let methods = this._getMethodNames(); let uncoveredLines = this._getUncoveredLines(); let result = []; - let versionControlBlock = {version: 1.0}; + let versionControlBlock = { version: 1.0 }; result.push(versionControlBlock); for (let scriptName in rawLines) { @@ -180,8 +184,13 @@ CoverageCollector.prototype.recordTestCoverage = function(testName) { uncovered: [], }; - if (typeof(methods[scriptName]) != "undefined" && methods[scriptName] != null) { - for (let [methodName, methodLines] of Object.entries(methods[scriptName])) { + if ( + typeof methods[scriptName] != "undefined" && + methods[scriptName] != null + ) { + for (let [methodName, methodLines] of Object.entries( + methods[scriptName] + )) { rec.methods[methodName] = methodLines; } } @@ -199,7 +208,7 @@ CoverageCollector.prototype.recordTestCoverage = function(testName) { let arr = this._encoder.encode(JSON.stringify(result, null, 2)); let path = this._prefix + "/jscov_" + Date.now() + ".json"; dump("Writing coverage to: " + path + "\n"); - return OS.File.writeAtomic(path, arr, {tmpPath: path + ".tmp"}); + return OS.File.writeAtomic(path, arr, { tmpPath: path + ".tmp" }); }; /** diff --git a/testing/modules/FileTestUtils.jsm b/testing/modules/FileTestUtils.jsm index 1c7d7e545ec4..2bfc8bca47e2 100644 --- a/testing/modules/FileTestUtils.jsm +++ b/testing/modules/FileTestUtils.jsm @@ -8,9 +8,7 @@ "use strict"; -var EXPORTED_SYMBOLS = [ - "FileTestUtils", -]; +var EXPORTED_SYMBOLS = ["FileTestUtils"]; ChromeUtils.import("resource://gre/modules/AsyncShutdown.jsm", this); ChromeUtils.import("resource://gre/modules/DownloadPaths.jsm", this); @@ -91,8 +89,10 @@ var FileTestUtils = { // error if the file existed before, and was recently deleted. There is no // way to distinguish this from an access list issue because checking for // the file existence would also result in the same error. - if (!(ex instanceof OS.File.Error) || - !(ex.becauseNoSuchFile || ex.becauseAccessDenied)) { + if ( + !(ex instanceof OS.File.Error) || + !(ex.becauseNoSuchFile || ex.becauseAccessDenied) + ) { throw ex; } } @@ -103,7 +103,9 @@ var FileTestUtils = { * Returns a reference to a global temporary directory that will be deleted * when all tests terminate. */ -XPCOMUtils.defineLazyGetter(FileTestUtils, "_globalTemporaryDirectory", +XPCOMUtils.defineLazyGetter( + FileTestUtils, + "_globalTemporaryDirectory", function() { // While previous test runs should have deleted their temporary directories, // on Windows they might still be pending deletion on the physical file @@ -112,7 +114,8 @@ XPCOMUtils.defineLazyGetter(FileTestUtils, "_globalTemporaryDirectory", let randomNumber = Math.floor(Math.random() * 1000000); let dir = FileUtils.getFile("TmpD", ["testdir-" + randomNumber]); dir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY); - AsyncShutdown.profileBeforeChange.addBlocker("Removing test files", + AsyncShutdown.profileBeforeChange.addBlocker( + "Removing test files", async () => { // Remove the files we know about first. for (let path of gPathsToRemove) { @@ -126,13 +129,16 @@ XPCOMUtils.defineLazyGetter(FileTestUtils, "_globalTemporaryDirectory", // Detect any extra files, like the ".part" files of downloads. let iterator = new OS.File.DirectoryIterator(dir.path); try { - await iterator.forEach(entry => this.tolerantRemove(entry.path, - entry.isDir)); + await iterator.forEach(entry => + this.tolerantRemove(entry.path, entry.isDir) + ); } finally { iterator.close(); } // This will fail if any test leaves inaccessible files behind. await OS.File.removeEmptyDir(dir.path); - }); + } + ); return dir; - }); + } +); diff --git a/testing/modules/MockRegistrar.jsm b/testing/modules/MockRegistrar.jsm index 7c7e3dd11eef..db18b021fc28 100644 --- a/testing/modules/MockRegistrar.jsm +++ b/testing/modules/MockRegistrar.jsm @@ -4,19 +4,22 @@ "use strict"; -var EXPORTED_SYMBOLS = [ - "MockRegistrar", -]; +var EXPORTED_SYMBOLS = ["MockRegistrar"]; const Cm = Components.manager; -const {Log} = ChromeUtils.import("resource://gre/modules/Log.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { Log } = ChromeUtils.import("resource://gre/modules/Log.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); var logger = Log.repository.getLogger("MockRegistrar"); -XPCOMUtils.defineLazyServiceGetter(this, "UUIDGen", - "@mozilla.org/uuid-generator;1", - "nsIUUIDGenerator"); +XPCOMUtils.defineLazyServiceGetter( + this, + "UUIDGen", + "@mozilla.org/uuid-generator;1", + "nsIUUIDGenerator" +); var MockRegistrar = Object.freeze({ _registeredComponents: new Map(), @@ -80,10 +83,12 @@ var MockRegistrar = Object.freeze({ QueryInterface: ChromeUtils.generateQI([Ci.nsIFactory]), }; - this.registrar.registerFactory(cid, - "A Mock for " + contractID, - contractID, - factory); + this.registrar.registerFactory( + cid, + "A Mock for " + contractID, + contractID, + factory + ); this._registeredComponents.set(cid, { contractID, @@ -109,9 +114,12 @@ var MockRegistrar = Object.freeze({ if (component.originalCID) { // Passing `null` for the factory re-maps the contract ID to the // entry for its original CID. - this.registrar.registerFactory(component.originalCID, "", - component.contractID, - null); + this.registrar.registerFactory( + component.originalCID, + "", + component.contractID, + null + ); } this._registeredComponents.delete(cid); @@ -125,5 +133,4 @@ var MockRegistrar = Object.freeze({ this.unregister(cid); } }, - }); diff --git a/testing/modules/MockRegistry.jsm b/testing/modules/MockRegistry.jsm index edb9f2545914..685f0864072f 100644 --- a/testing/modules/MockRegistry.jsm +++ b/testing/modules/MockRegistry.jsm @@ -1,9 +1,10 @@ - "use strict"; var EXPORTED_SYMBOLS = ["MockRegistry"]; -const {MockRegistrar} = ChromeUtils.import("resource://testing-common/MockRegistrar.jsm"); +const { MockRegistrar } = ChromeUtils.import( + "resource://testing-common/MockRegistrar.jsm" +); class MockRegistry { constructor() { @@ -27,7 +28,7 @@ class MockRegistry { * subset of the interface used in tests. In particular, only values * of type string are supported. */ - function MockWindowsRegKey() { } + function MockWindowsRegKey() {} MockWindowsRegKey.prototype = { values: null, @@ -48,8 +49,9 @@ class MockRegistry { }, get valueCount() { - if (!this.values) + if (!this.values) { throw Cr.NS_ERROR_FAILURE; + } return this.values.size; }, @@ -65,8 +67,9 @@ class MockRegistry { }, getValueName(index) { - if (!this.values || index >= this.values.size) + if (!this.values || index >= this.values.size) { throw Cr.NS_ERROR_FAILURE; + } let names = Array.from(this.values.keys()); return names[index]; }, @@ -79,7 +82,10 @@ class MockRegistry { }, }; - this.cid = MockRegistrar.register("@mozilla.org/windows-registry-key;1", MockWindowsRegKey); + this.cid = MockRegistrar.register( + "@mozilla.org/windows-registry-key;1", + MockWindowsRegKey + ); } shutdown() { diff --git a/testing/modules/Sinon.jsm b/testing/modules/Sinon.jsm index 81b5caede7d7..a7b512234359 100644 --- a/testing/modules/Sinon.jsm +++ b/testing/modules/Sinon.jsm @@ -2,21 +2,31 @@ var EXPORTED_SYMBOLS = ["sinon"]; -var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); // ================================================ // Load mocking/stubbing library sinon // docs: http://sinonjs.org/releases/v7.2.7/ -const {clearInterval, clearTimeout, setInterval, setIntervalWithTarget, setTimeout, setTimeoutWithTarget} = ChromeUtils.import("resource://gre/modules/Timer.jsm"); +const { + clearInterval, + clearTimeout, + setInterval, + setIntervalWithTarget, + setTimeout, + setTimeoutWithTarget, +} = ChromeUtils.import("resource://gre/modules/Timer.jsm"); // eslint-disable-next-line no-unused-vars const global = { - clearInterval, - clearTimeout, - setInterval, - setIntervalWithTarget, - setTimeout, - setTimeoutWithTarget, + clearInterval, + clearTimeout, + setInterval, + setIntervalWithTarget, + setTimeout, + setTimeoutWithTarget, }; -Services.scriptloader.loadSubScript("resource://testing-common/sinon-7.2.7.js", this); +Services.scriptloader.loadSubScript( + "resource://testing-common/sinon-7.2.7.js", + this +); const sinon = global.sinon; // ================================================ diff --git a/testing/modules/StructuredLog.jsm b/testing/modules/StructuredLog.jsm index ed34b355c5af..a75b1f284a98 100644 --- a/testing/modules/StructuredLog.jsm +++ b/testing/modules/StructuredLog.jsm @@ -4,10 +4,7 @@ "use strict"; -var EXPORTED_SYMBOLS = [ - "StructuredLogger", - "StructuredFormatter", -]; +var EXPORTED_SYMBOLS = ["StructuredLogger", "StructuredFormatter"]; /** * TestLogger: Logger class generating messages compliant with the @@ -34,12 +31,19 @@ var StructuredLogger = function(name, dumpFun = dump, mutators = []) { */ StructuredLogger.prototype = { testStart(test) { - var data = {test: this._testId(test)}; + var data = { test: this._testId(test) }; this._logData("test_start", data); }, - testStatus(test, subtest, status, expected = "PASS", - message = null, stack = null, extra = null) { + testStatus( + test, + subtest, + status, + expected = "PASS", + message = null, + stack = null, + extra = null + ) { if (subtest === null || subtest === undefined) { // Fix for assertions that don't pass in a name subtest = "undefined assertion name"; @@ -67,8 +71,15 @@ StructuredLogger.prototype = { this._logData("test_status", data); }, - testEnd(test, status, expected = "OK", message = null, stack = null, extra = null) { - var data = {test: this._testId(test), status}; + testEnd( + test, + status, + expected = "OK", + message = null, + stack = null, + extra = null + ) { + var data = { test: this._testId(test), status }; if (expected != status && status != "SKIP") { data.expected = expected; @@ -87,16 +98,25 @@ StructuredLogger.prototype = { }, assertionCount(test, count, minExpected = 0, maxExpected = 0) { - var data = {test: this._testId(test), - min_expected: minExpected, - max_expected: maxExpected, - count}; + var data = { + test: this._testId(test), + min_expected: minExpected, + max_expected: maxExpected, + count, + }; this._logData("assertion_count", data); }, - suiteStart(tests, name = null, runinfo = null, versioninfo = null, deviceinfo = null, extra = null) { - var data = {tests: tests.map(x => this._testId(x))}; + suiteStart( + tests, + name = null, + runinfo = null, + versioninfo = null, + deviceinfo = null, + extra = null + ) { + var data = { tests: tests.map(x => this._testId(x)) }; if (name !== null) { data.name = name; } @@ -130,7 +150,6 @@ StructuredLogger.prototype = { this._logData("suite_end", data); }, - /** * Unstructured logging functions. The "extra" parameter can always by used to * log suite specific data. If a "stack" field is provided it is logged at the @@ -179,7 +198,6 @@ StructuredLogger.prototype = { }); }, - _logData(action, data = {}) { var allData = { action, @@ -208,17 +226,15 @@ StructuredLogger.prototype = { }, }; - /** * StructuredFormatter: Formatter class turning structured messages * into human-readable messages. */ var StructuredFormatter = function() { - this.testStartTimes = {}; + this.testStartTimes = {}; }; StructuredFormatter.prototype = { - log(message) { return message.message; }, @@ -234,25 +250,40 @@ StructuredFormatter.prototype = { }, test_status(message) { - var statusInfo = message.test + " | " + message.subtest + - (message.message ? " | " + message.message : ""); + var statusInfo = + message.test + + " | " + + message.subtest + + (message.message ? " | " + message.message : ""); if (message.expected) { - return "TEST-UNEXPECTED-" + message.status + " | " + statusInfo + - " - expected: " + message.expected; + return ( + "TEST-UNEXPECTED-" + + message.status + + " | " + + statusInfo + + " - expected: " + + message.expected + ); } - return "TEST-" + message.status + " | " + statusInfo; + return "TEST-" + message.status + " | " + statusInfo; }, test_end(message) { var startTime = this.testStartTimes[message.test]; delete this.testStartTimes[message.test]; - var statusInfo = message.test + (message.message ? " | " + String(message.message) : ""); + var statusInfo = + message.test + (message.message ? " | " + String(message.message) : ""); var result; if (message.expected) { - result = "TEST-UNEXPECTED-" + message.status + " | " + statusInfo + - " - expected: " + message.expected; + result = + "TEST-UNEXPECTED-" + + message.status + + " | " + + statusInfo + + " - expected: " + + message.expected; } else { - return "TEST-" + message.status + " | " + statusInfo; + return "TEST-" + message.status + " | " + statusInfo; } result = result + " | took " + message.time - startTime + "ms"; return result; @@ -262,4 +293,3 @@ StructuredFormatter.prototype = { return "SUITE-END | took " + message.time - this.suiteStartTime + "ms"; }, }; - diff --git a/testing/modules/TestUtils.jsm b/testing/modules/TestUtils.jsm index c796a5ab63de..3a650dea2196 100644 --- a/testing/modules/TestUtils.jsm +++ b/testing/modules/TestUtils.jsm @@ -18,12 +18,12 @@ "use strict"; -var EXPORTED_SYMBOLS = [ - "TestUtils", -]; +var EXPORTED_SYMBOLS = ["TestUtils"]; -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {clearInterval, setInterval} = ChromeUtils.import("resource://gre/modules/Timer.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { clearInterval, setInterval } = ChromeUtils.import( + "resource://gre/modules/Timer.jsm" +); var TestUtils = { executeSoon(callbackFn) { @@ -89,19 +89,23 @@ var TestUtils = { */ waitForPrefChange(prefName, checkFn) { return new Promise((resolve, reject) => { - Services.prefs.addObserver(prefName, function observer(subject, topic, data) { + Services.prefs.addObserver(prefName, function observer( + subject, + topic, + data + ) { try { let prefValue = null; switch (Services.prefs.getPrefType(prefName)) { - case Services.prefs.PREF_STRING: - prefValue = Services.prefs.getStringPref(prefName); - break; - case Services.prefs.PREF_INT: - prefValue = Services.prefs.getIntPref(prefName); - break; - case Services.prefs.PREF_BOOL: - prefValue = Services.prefs.getBoolPref(prefName); - break; + case Services.prefs.PREF_STRING: + prefValue = Services.prefs.getStringPref(prefName); + break; + case Services.prefs.PREF_INT: + prefValue = Services.prefs.getIntPref(prefName); + break; + case Services.prefs.PREF_BOOL: + prefValue = Services.prefs.getBoolPref(prefName); + break; } if (checkFn && !checkFn(prefValue)) { return; @@ -129,7 +133,10 @@ var TestUtils = { eltOrRect = eltOrRect.getBoundingClientRect(); } let { left, top, width, height } = eltOrRect; - let canvas = win.document.createElementNS("http://www.w3.org/1999/xhtml", "canvas"); + let canvas = win.document.createElementNS( + "http://www.w3.org/1999/xhtml", + "canvas" + ); let ctx = canvas.getContext("2d"); let ratio = win.devicePixelRatio; canvas.width = width * ratio; @@ -139,7 +146,7 @@ var TestUtils = { return canvas.toDataURL(); }, - /** + /** * Will poll a condition function until it returns true. * * @param condition diff --git a/testing/modules/tests/xpcshell/test_assert.js b/testing/modules/tests/xpcshell/test_assert.js index 60147a67e72f..14fd38e8834f 100644 --- a/testing/modules/tests/xpcshell/test_assert.js +++ b/testing/modules/tests/xpcshell/test_assert.js @@ -33,17 +33,26 @@ function run_test() { return objChain.slice(-clsChain.length) === clsChain; } - assert.ok(indirectInstanceOf(ns.Assert.AssertionError.prototype, Error), - "Assert.AssertionError instanceof Error"); + assert.ok( + indirectInstanceOf(ns.Assert.AssertionError.prototype, Error), + "Assert.AssertionError instanceof Error" + ); - assert.throws(makeBlock(assert.ok, false), - ns.Assert.AssertionError, "ok(false)"); + assert.throws( + makeBlock(assert.ok, false), + ns.Assert.AssertionError, + "ok(false)" + ); assert.ok(true, "ok(true)"); assert.ok("test", "ok('test')"); - assert.throws(makeBlock(assert.equal, true, false), ns.Assert.AssertionError, "equal"); + assert.throws( + makeBlock(assert.equal, true, false), + ns.Assert.AssertionError, + "equal" + ); assert.equal(null, null, "equal"); @@ -55,57 +64,94 @@ function run_test() { assert.notEqual(true, false, "notEqual"); - assert.throws(makeBlock(assert.notEqual, true, true), - ns.Assert.AssertionError, "notEqual"); + assert.throws( + makeBlock(assert.notEqual, true, true), + ns.Assert.AssertionError, + "notEqual" + ); - assert.throws(makeBlock(assert.strictEqual, 2, "2"), - ns.Assert.AssertionError, "strictEqual"); + assert.throws( + makeBlock(assert.strictEqual, 2, "2"), + ns.Assert.AssertionError, + "strictEqual" + ); - assert.throws(makeBlock(assert.strictEqual, null, undefined), - ns.Assert.AssertionError, "strictEqual"); + assert.throws( + makeBlock(assert.strictEqual, null, undefined), + ns.Assert.AssertionError, + "strictEqual" + ); assert.notStrictEqual(2, "2", "notStrictEqual"); // deepEquals joy! // 7.2 - assert.deepEqual(new Date(2000, 3, 14), new Date(2000, 3, 14), "deepEqual date"); + assert.deepEqual( + new Date(2000, 3, 14), + new Date(2000, 3, 14), + "deepEqual date" + ); assert.deepEqual(new Date(NaN), new Date(NaN), "deepEqual invalid dates"); - assert.throws(makeBlock(assert.deepEqual, new Date(), new Date(2000, 3, 14)), - ns.Assert.AssertionError, - "deepEqual date"); + assert.throws( + makeBlock(assert.deepEqual, new Date(), new Date(2000, 3, 14)), + ns.Assert.AssertionError, + "deepEqual date" + ); // 7.3 assert.deepEqual(/a/, /a/); assert.deepEqual(/a/g, /a/g); assert.deepEqual(/a/i, /a/i); assert.deepEqual(/a/m, /a/m); - assert.deepEqual(/a/igm, /a/igm); - assert.throws(makeBlock(assert.deepEqual, /ab/, /a/), ns.Assert.AssertionError); - assert.throws(makeBlock(assert.deepEqual, /a/g, /a/), ns.Assert.AssertionError); - assert.throws(makeBlock(assert.deepEqual, /a/i, /a/), ns.Assert.AssertionError); - assert.throws(makeBlock(assert.deepEqual, /a/m, /a/), ns.Assert.AssertionError); - assert.throws(makeBlock(assert.deepEqual, /a/igm, /a/im), ns.Assert.AssertionError); + assert.deepEqual(/a/gim, /a/gim); + assert.throws( + makeBlock(assert.deepEqual, /ab/, /a/), + ns.Assert.AssertionError + ); + assert.throws( + makeBlock(assert.deepEqual, /a/g, /a/), + ns.Assert.AssertionError + ); + assert.throws( + makeBlock(assert.deepEqual, /a/i, /a/), + ns.Assert.AssertionError + ); + assert.throws( + makeBlock(assert.deepEqual, /a/m, /a/), + ns.Assert.AssertionError + ); + assert.throws( + makeBlock(assert.deepEqual, /a/gim, /a/im), + ns.Assert.AssertionError + ); let re1 = /a/; re1.lastIndex = 3; - assert.throws(makeBlock(assert.deepEqual, re1, /a/), ns.Assert.AssertionError); + assert.throws( + makeBlock(assert.deepEqual, re1, /a/), + ns.Assert.AssertionError + ); // 7.4 assert.deepEqual(4, "4", "deepEqual == check"); assert.deepEqual(true, 1, "deepEqual == check"); - assert.throws(makeBlock(assert.deepEqual, 4, "5"), - ns.Assert.AssertionError, - "deepEqual == check"); + assert.throws( + makeBlock(assert.deepEqual, 4, "5"), + ns.Assert.AssertionError, + "deepEqual == check" + ); // 7.5 // having the same number of owned properties && the same set of keys - assert.deepEqual({a: 4}, {a: 4}); - assert.deepEqual({a: 4, b: "2"}, {a: 4, b: "2"}); + assert.deepEqual({ a: 4 }, { a: 4 }); + assert.deepEqual({ a: 4, b: "2" }, { a: 4, b: "2" }); assert.deepEqual([4], ["4"]); - assert.throws(makeBlock(assert.deepEqual, {a: 4}, {a: 4, b: true}), - ns.Assert.AssertionError); - assert.deepEqual(["a"], {0: "a"}); + assert.throws( + makeBlock(assert.deepEqual, { a: 4 }, { a: 4, b: true }), + ns.Assert.AssertionError + ); + assert.deepEqual(["a"], { 0: "a" }); let a1 = [1, 2, 3]; let a2 = [1, 2, 3]; @@ -113,12 +159,16 @@ function run_test() { a1.b = true; a2.b = true; a2.a = "test"; - assert.throws(makeBlock(assert.deepEqual, Object.keys(a1), Object.keys(a2)), - ns.Assert.AssertionError); + assert.throws( + makeBlock(assert.deepEqual, Object.keys(a1), Object.keys(a2)), + ns.Assert.AssertionError + ); assert.deepEqual(a1, a2); let nbRoot = { - toString() { return this.first + " " + this.last; }, + toString() { + return this.first + " " + this.last; + }, }; function nameBuilder(first, last) { @@ -142,7 +192,10 @@ function run_test() { nameBuilder2.prototype = Object; nb2 = new nameBuilder2("Ryan", "Dahl"); - assert.throws(makeBlock(assert.deepEqual, nb1, nb2), ns.Assert.AssertionError); + assert.throws( + makeBlock(assert.deepEqual, nb1, nb2), + ns.Assert.AssertionError + ); // String literal + object assert.throws(makeBlock(assert.deepEqual, "a", {}), ns.Assert.AssertionError); @@ -155,10 +208,19 @@ function run_test() { makeBlock(thrower, ns.Assert.AssertionError); // the basic calls work - assert.throws(makeBlock(thrower, ns.Assert.AssertionError), - ns.Assert.AssertionError, "message"); - assert.throws(makeBlock(thrower, ns.Assert.AssertionError), ns.Assert.AssertionError); - assert.throws(makeBlock(thrower, ns.Assert.AssertionError), ns.Assert.AssertionError); + assert.throws( + makeBlock(thrower, ns.Assert.AssertionError), + ns.Assert.AssertionError, + "message" + ); + assert.throws( + makeBlock(thrower, ns.Assert.AssertionError), + ns.Assert.AssertionError + ); + assert.throws( + makeBlock(thrower, ns.Assert.AssertionError), + ns.Assert.AssertionError + ); // if not passing an error, catch all. assert.throws(makeBlock(thrower, TypeError), TypeError); @@ -171,9 +233,12 @@ function run_test() { threw = true; assert.ok(e instanceof TypeError, "type"); } - assert.equal(true, threw, - "Assert.throws with an explicit error is eating extra errors", - ns.Assert.AssertionError); + assert.equal( + true, + threw, + "Assert.throws with an explicit error is eating extra errors", + ns.Assert.AssertionError + ); threw = false; function ifError(err) { @@ -188,12 +253,9 @@ function run_test() { // make sure that validating using constructor really works threw = false; try { - assert.throws( - function() { - throw new Error({}); - }, - Array - ); + assert.throws(function() { + throw new Error({}); + }, Array); } catch (e) { threw = true; } @@ -204,14 +266,14 @@ function run_test() { // use a fn to validate error object assert.throws(makeBlock(thrower, TypeError), function(err) { - if ((err instanceof TypeError) && /test/.test(err)) { + if (err instanceof TypeError && /test/.test(err)) { return true; } return false; }); // do the same with an arrow function assert.throws(makeBlock(thrower, TypeError), err => { - if ((err instanceof TypeError) && /test/.test(err)) { + if (err instanceof TypeError && /test/.test(err)) { return true; } return false; @@ -221,8 +283,10 @@ function run_test() { try { assert.equal(actual, ""); } catch (e) { - assert.equal(e.toString(), - ["AssertionError:", expected, "==", '""'].join(" ")); + assert.equal( + e.toString(), + ["AssertionError:", expected, "==", '""'].join(" ") + ); } } testAssertionMessage(undefined, '"undefined"'); @@ -242,9 +306,11 @@ function run_test() { testAssertionMessage(/abc/gim, '"/abc/gim"'); testAssertionMessage(function f() {}, '"function f() {}"'); testAssertionMessage({}, "{}"); - testAssertionMessage({a: undefined, b: null}, '{"a":"undefined","b":null}'); - testAssertionMessage({a: NaN, b: Infinity, c: -Infinity}, - '{"a":"NaN","b":"Infinity","c":"-Infinity"}'); + testAssertionMessage({ a: undefined, b: null }, '{"a":"undefined","b":null}'); + testAssertionMessage( + { a: NaN, b: Infinity, c: -Infinity }, + '{"a":"NaN","b":"Infinity","c":"-Infinity"}' + ); // https://github.com/joyent/node/issues/2893 try { @@ -253,7 +319,10 @@ function run_test() { }); } catch (e) { threw = true; - assert.equal(e.message, "Error: The 'expected' argument was not supplied to Assert.throws() - false == true"); + assert.equal( + e.message, + "Error: The 'expected' argument was not supplied to Assert.throws() - false == true" + ); } assert.ok(threw); @@ -285,20 +354,27 @@ function run_test() { // Test XPCShell-test integration: ok(true, "OK, this went well"); deepEqual(/a/g, /a/g, "deep equal should work on RegExp"); - deepEqual(/a/igm, /a/igm, "deep equal should work on RegExp"); - deepEqual({a: 4, b: "1"}, {b: "1", a: 4}, "deep equal should work on regular Object"); + deepEqual(/a/gim, /a/gim, "deep equal should work on RegExp"); + deepEqual( + { a: 4, b: "1" }, + { b: "1", a: 4 }, + "deep equal should work on regular Object" + ); deepEqual(a1, a2, "deep equal should work on Array with Object properties"); // Test robustness of reporting: - equal(new ns.Assert.AssertionError({ - actual: { - toJSON() { - throw new Error("bam!"); + equal( + new ns.Assert.AssertionError({ + actual: { + toJSON() { + throw new Error("bam!"); + }, }, - }, - expected: "foo", - operator: "=", - }).message, "[object Object] = \"foo\""); + expected: "foo", + operator: "=", + }).message, + '[object Object] = "foo"' + ); let message; assert.greater(3, 2); diff --git a/testing/modules/tests/xpcshell/test_mockRegistrar.js b/testing/modules/tests/xpcshell/test_mockRegistrar.js index e24fb556bdd9..ba1321c0debd 100644 --- a/testing/modules/tests/xpcshell/test_mockRegistrar.js +++ b/testing/modules/tests/xpcshell/test_mockRegistrar.js @@ -1,7 +1,9 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ -const {MockRegistrar} = ChromeUtils.import("resource://testing-common/MockRegistrar.jsm"); +const { MockRegistrar } = ChromeUtils.import( + "resource://testing-common/MockRegistrar.jsm" +); function platformInfo(injectedValue) { this.platformVersion = injectedValue; @@ -21,21 +23,43 @@ add_test(function test_register() { }; MockRegistrar.register("@mozilla.org/xre/app-info;1", localPlatformInfo); - Assert.equal(Cc["@mozilla.org/xre/app-info;1"].createInstance(Ci.nsIPlatformInfo).platformVersion, "local version"); + Assert.equal( + Cc["@mozilla.org/xre/app-info;1"].createInstance(Ci.nsIPlatformInfo) + .platformVersion, + "local version" + ); run_next_test(); }); add_test(function test_register_with_arguments() { - MockRegistrar.register("@mozilla.org/xre/app-info;1", platformInfo, ["override"]); - Assert.equal(Cc["@mozilla.org/xre/app-info;1"].createInstance(Ci.nsIPlatformInfo).platformVersion, "override"); + MockRegistrar.register("@mozilla.org/xre/app-info;1", platformInfo, [ + "override", + ]); + Assert.equal( + Cc["@mozilla.org/xre/app-info;1"].createInstance(Ci.nsIPlatformInfo) + .platformVersion, + "override" + ); run_next_test(); }); add_test(function test_register_twice() { - MockRegistrar.register("@mozilla.org/xre/app-info;1", platformInfo, ["override"]); - Assert.equal(Cc["@mozilla.org/xre/app-info;1"].createInstance(Ci.nsIPlatformInfo).platformVersion, "override"); + MockRegistrar.register("@mozilla.org/xre/app-info;1", platformInfo, [ + "override", + ]); + Assert.equal( + Cc["@mozilla.org/xre/app-info;1"].createInstance(Ci.nsIPlatformInfo) + .platformVersion, + "override" + ); - MockRegistrar.register("@mozilla.org/xre/app-info;1", platformInfo, ["override again"]); - Assert.equal(Cc["@mozilla.org/xre/app-info;1"].createInstance(Ci.nsIPlatformInfo).platformVersion, "override again"); + MockRegistrar.register("@mozilla.org/xre/app-info;1", platformInfo, [ + "override again", + ]); + Assert.equal( + Cc["@mozilla.org/xre/app-info;1"].createInstance(Ci.nsIPlatformInfo) + .platformVersion, + "override again" + ); run_next_test(); }); diff --git a/testing/modules/tests/xpcshell/test_structuredlog.js b/testing/modules/tests/xpcshell/test_structuredlog.js index 9f87aa02eb30..c35e96a34cf0 100644 --- a/testing/modules/tests/xpcshell/test_structuredlog.js +++ b/testing/modules/tests/xpcshell/test_structuredlog.js @@ -2,7 +2,9 @@ http://creativecommons.org/publicdomain/zero/1.0/ */ function run_test() { - const {StructuredLogger} = ChromeUtils.import("resource://testing-common/StructuredLog.jsm"); + const { StructuredLogger } = ChromeUtils.import( + "resource://testing-common/StructuredLog.jsm" + ); let testBuffer = []; @@ -37,13 +39,12 @@ function run_test() { level: "INFO", }); - logger.info("Test message", - {foo: "bar"}); + logger.info("Test message", { foo: "bar" }); assertLastMsg({ action: "log", message: "Test message", level: "INFO", - extra: {foo: "bar"}, + extra: { foo: "bar" }, }); // Test end / start actions @@ -110,8 +111,14 @@ function run_test() { expected: "PASS", }); - logger.testStatus("aTest", "bar", "FAIL", "PASS", null, - "Many\nlines\nof\nstack\n"); + logger.testStatus( + "aTest", + "bar", + "FAIL", + "PASS", + null, + "Many\nlines\nof\nstack\n" + ); assertLastMsg({ action: "test_status", test: "aTest", diff --git a/testing/mozbase/mozlog/mozlog/formatters/html/main.js b/testing/mozbase/mozlog/mozlog/formatters/html/main.js index fa0bb2ef6706..cb2721ab2961 100644 --- a/testing/mozbase/mozlog/mozlog/formatters/html/main.js +++ b/testing/mozbase/mozlog/mozlog/formatters/html/main.js @@ -3,169 +3,164 @@ * You can obtain one at http://mozilla.org/MPL/2.0/. */ function toArray(iter) { - if (iter === null) { - return null; - } - return Array.prototype.slice.call(iter); + if (iter === null) { + return null; + } + return Array.prototype.slice.call(iter); } function find(selector, elem) { - if (!elem) { - elem = document; - } - return elem.querySelector(selector); + if (!elem) { + elem = document; + } + return elem.querySelector(selector); } function find_all(selector, elem) { - if (!elem) { - elem = document; - } - return toArray(elem.querySelectorAll(selector)); + if (!elem) { + elem = document; + } + return toArray(elem.querySelectorAll(selector)); } addEventListener("DOMContentLoaded", function() { - reset_sort_headers(); + reset_sort_headers(); - split_debug_onto_two_rows(); + split_debug_onto_two_rows(); - find_all(".col-links a.screenshot").forEach(function(elem) { - elem.addEventListener("click", - function(event) { - var node = elem; - while (node && !node.classList.contains("results-table-row")) { - node = node.parentNode; - } - if (node != null) { - if (node.nextSibling && - node.nextSibling.classList.contains("debug")) { - var href = find(".screenshot img", node.nextSibling).src; - window.open(href); - } - } - event.preventDefault(); - }); + find_all(".col-links a.screenshot").forEach(function(elem) { + elem.addEventListener("click", function(event) { + var node = elem; + while (node && !node.classList.contains("results-table-row")) { + node = node.parentNode; + } + if (node != null) { + if (node.nextSibling && node.nextSibling.classList.contains("debug")) { + var href = find(".screenshot img", node.nextSibling).src; + window.open(href); + } + } + event.preventDefault(); }); + }); - find_all(".screenshot a").forEach(function(elem) { - elem.addEventListener("click", - function(event) { - window.open(find("img", elem).getAttribute("src")); - event.preventDefault(); - }); + find_all(".screenshot a").forEach(function(elem) { + elem.addEventListener("click", function(event) { + window.open(find("img", elem).getAttribute("src")); + event.preventDefault(); }); + }); - find_all(".sortable").forEach(function(elem) { - elem.addEventListener("click", - function(event) { - toggle_sort_states(elem); - var colIndex = toArray(elem.parentNode.childNodes).indexOf(elem); - var key = elem.classList.contains("numeric") ? key_num : key_alpha; - sort_table(elem, key(colIndex)); - }); + find_all(".sortable").forEach(function(elem) { + elem.addEventListener("click", function(event) { + toggle_sort_states(elem); + var colIndex = toArray(elem.parentNode.childNodes).indexOf(elem); + var key = elem.classList.contains("numeric") ? key_num : key_alpha; + sort_table(elem, key(colIndex)); }); + }); }); function sort_table(clicked, key_func) { - one_row_for_data(); - var rows = find_all(".results-table-row"); - var reversed = !clicked.classList.contains("asc"); + one_row_for_data(); + var rows = find_all(".results-table-row"); + var reversed = !clicked.classList.contains("asc"); - var sorted_rows = sort(rows, key_func, reversed); + var sorted_rows = sort(rows, key_func, reversed); - var parent = document.getElementById("results-table-body"); - sorted_rows.forEach(function(elem) { - parent.appendChild(elem); - }); + var parent = document.getElementById("results-table-body"); + sorted_rows.forEach(function(elem) { + parent.appendChild(elem); + }); - split_debug_onto_two_rows(); + split_debug_onto_two_rows(); } function sort(items, key_func, reversed) { - var sort_array = items.map(function(item, i) { - return [key_func(item), i]; - }); - var multiplier = reversed ? -1 : 1; + var sort_array = items.map(function(item, i) { + return [key_func(item), i]; + }); + var multiplier = reversed ? -1 : 1; - sort_array.sort(function(a, b) { - var key_a = a[0]; - var key_b = b[0]; - return multiplier * (key_a >= key_b ? 1 : -1); - }); + sort_array.sort(function(a, b) { + var key_a = a[0]; + var key_b = b[0]; + return multiplier * (key_a >= key_b ? 1 : -1); + }); - return sort_array.map(function(item) { - var index = item[1]; - return items[index]; - }); + return sort_array.map(function(item) { + var index = item[1]; + return items[index]; + }); } function key_alpha(col_index) { - return function(elem) { - return elem.childNodes[col_index].firstChild.data.toLowerCase(); - }; + return function(elem) { + return elem.childNodes[col_index].firstChild.data.toLowerCase(); + }; } function key_num(col_index) { - return function(elem) { - return parseFloat(elem.childNodes[col_index].firstChild.data); - }; + return function(elem) { + return parseFloat(elem.childNodes[col_index].firstChild.data); + }; } function reset_sort_headers() { - find_all(".sort-icon").forEach(function(elem) { - elem.remove(); - }); - find_all(".sortable").forEach(function(elem) { - var icon = document.createElement("div"); - icon.className = "sort-icon"; - icon.textContent = "vvv"; - elem.insertBefore(icon, elem.firstChild); - elem.classList.remove("desc", "active"); - elem.classList.add("asc", "inactive"); - }); + find_all(".sort-icon").forEach(function(elem) { + elem.remove(); + }); + find_all(".sortable").forEach(function(elem) { + var icon = document.createElement("div"); + icon.className = "sort-icon"; + icon.textContent = "vvv"; + elem.insertBefore(icon, elem.firstChild); + elem.classList.remove("desc", "active"); + elem.classList.add("asc", "inactive"); + }); } function toggle_sort_states(elem) { - // if active, toggle between asc and desc - if (elem.classList.contains("active")) { - elem.classList.toggle("asc"); - elem.classList.toggle("desc"); - } + // if active, toggle between asc and desc + if (elem.classList.contains("active")) { + elem.classList.toggle("asc"); + elem.classList.toggle("desc"); + } - // if inactive, reset all other functions and add ascending active - if (elem.classList.contains("inactive")) { - reset_sort_headers(); - elem.classList.remove("inactive"); - elem.classList.add("active"); - } + // if inactive, reset all other functions and add ascending active + if (elem.classList.contains("inactive")) { + reset_sort_headers(); + elem.classList.remove("inactive"); + elem.classList.add("active"); + } } function split_debug_onto_two_rows() { - find_all("tr.results-table-row").forEach(function(elem) { - var new_row = document.createElement("tr"); - new_row.className = "debug"; - elem.parentNode.insertBefore(new_row, elem.nextSibling); - find_all(".debug", elem).forEach(function(td_elem) { - if (find(".log", td_elem)) { - new_row.appendChild(td_elem); - td_elem.colSpan = 5; - } else { - td_elem.remove(); - } - }); + find_all("tr.results-table-row").forEach(function(elem) { + var new_row = document.createElement("tr"); + new_row.className = "debug"; + elem.parentNode.insertBefore(new_row, elem.nextSibling); + find_all(".debug", elem).forEach(function(td_elem) { + if (find(".log", td_elem)) { + new_row.appendChild(td_elem); + td_elem.colSpan = 5; + } else { + td_elem.remove(); + } }); + }); } function one_row_for_data() { - find_all("tr.results-table-row").forEach(function(elem) { - if (elem.nextSibling.classList.contains("debug")) { - toArray(elem.nextSibling.childNodes).forEach( - function(td_elem) { - elem.appendChild(td_elem); - }); - } else { - var new_td = document.createElement("td"); - new_td.className = "debug"; - elem.appendChild(new_td); - } - }); + find_all("tr.results-table-row").forEach(function(elem) { + if (elem.nextSibling.classList.contains("debug")) { + toArray(elem.nextSibling.childNodes).forEach(function(td_elem) { + elem.appendChild(td_elem); + }); + } else { + var new_td = document.createElement("td"); + new_td.className = "debug"; + elem.appendChild(new_td); + } + }); } diff --git a/testing/raptor/webext/raptor/benchmark.js b/testing/raptor/webext/raptor/benchmark.js index 095bf4e4d61b..766556cc4089 100644 --- a/testing/raptor/webext/raptor/benchmark.js +++ b/testing/raptor/webext/raptor/benchmark.js @@ -17,7 +17,9 @@ function receiveMessage(event) { function sendResult(_type, _value) { // send result back to background runner script raptorLog(`sending result back to runner: ${_type} ${_value}`); - chrome.runtime.sendMessage({"type": _type, "value": _value}, function(response) { + chrome.runtime.sendMessage({ type: _type, value: _value }, function( + response + ) { raptorLog(response.text); }); } diff --git a/testing/raptor/webext/raptor/pageload.js b/testing/raptor/webext/raptor/pageload.js index 97ebc57f758f..1c9e900a5f18 100644 --- a/testing/raptor/webext/raptor/pageload.js +++ b/testing/raptor/webext/raptor/pageload.js @@ -57,7 +57,7 @@ function raptorContentHandler() { sendPageloadReady(); // retrieve test settings from local ext storage - if (typeof(browser) !== "undefined") { + if (typeof browser !== "undefined") { // firefox, returns promise browser.storage.local.get("settings").then(function(item) { setup(item.settings); @@ -73,7 +73,7 @@ function raptorContentHandler() { function sendPageloadReady() { // send message to runnerjs indicating pageloadjs is ready to start getting measures raptorLog("sending pageloadjs-ready message to runnerjs"); - chrome.runtime.sendMessage({"type": "pageloadjs-ready"}, function(response) { + chrome.runtime.sendMessage({ type: "pageloadjs-ready" }, function(response) { if (response !== undefined) { raptorLog(`${response.text}`); } @@ -155,9 +155,11 @@ function measureHero() { var resultType = `hero:${heroFound}`; raptorLog(`found ${resultType}`); // calculcate result: performance.timing.fetchStart - time when we got hero element - perfData.measure(name = resultType, - startMark = startMeasure, - endMark = heroFound); + perfData.measure( + (name = resultType), + (startMark = startMeasure), + (endMark = heroFound) + ); var perfResult = perfData.getEntriesByName(resultType); var _result = Math.round(perfResult[0].duration); sendResult(resultType, _result); @@ -167,27 +169,30 @@ function measureHero() { }); } // we want the element 100% visible on the viewport - var options = {root: null, rootMargin: "0px", threshold: [1]}; + var options = { root: null, rootMargin: "0px", threshold: [1] }; try { obs = new window.IntersectionObserver(callbackHero, options); heroElementsFound.forEach(function(el) { // if hero element is one we want to measure, add it to the observer - if (heroesToCapture.indexOf(el.getAttribute("elementtiming")) > -1) + if (heroesToCapture.indexOf(el.getAttribute("elementtiming")) > -1) { obs.observe(el); + } }); } catch (err) { raptorLog(err); } } else { - raptorLog("couldn't find hero element"); + raptorLog("couldn't find hero element"); } } function measureFNBPaint() { var x = window.performance.timing.timeToNonBlankPaint; - if (typeof(x) == "undefined") { - raptorLog("ERROR: timeToNonBlankPaint is undefined; ensure the pref is enabled"); + if (typeof x == "undefined") { + raptorLog( + "ERROR: timeToNonBlankPaint is undefined; ensure the pref is enabled" + ); return; } if (x > 0) { @@ -198,10 +203,14 @@ function measureFNBPaint() { } else { gRetryCounter += 1; if (gRetryCounter <= 10) { - raptorLog(`fnbpaint is not yet available, retry number ${gRetryCounter}...`); + raptorLog( + `fnbpaint is not yet available, retry number ${gRetryCounter}...` + ); window.setTimeout(measureFNBPaint, 100); } else { - raptorLog(`unable to get a value for fnbpaint after ${gRetryCounter} retries`); + raptorLog( + `unable to get a value for fnbpaint after ${gRetryCounter} retries` + ); } } } @@ -209,8 +218,10 @@ function measureFNBPaint() { function measureDCF() { var x = window.performance.timing.timeToDOMContentFlushed; - if (typeof(x) == "undefined") { - raptorLog("ERROR: domContentFlushed is undefined; ensure the pref is enabled"); + if (typeof x == "undefined") { + raptorLog( + "ERROR: domContentFlushed is undefined; ensure the pref is enabled" + ); return; } if (x > 0) { @@ -221,7 +232,9 @@ function measureDCF() { } else { gRetryCounter += 1; if (gRetryCounter <= 10) { - raptorLog(`dcf is not yet available (0), retry number ${gRetryCounter}...`); + raptorLog( + `dcf is not yet available (0), retry number ${gRetryCounter}...` + ); window.setTimeout(measureDCF, 100); } else { raptorLog(`unable to get a value for dcf after ${gRetryCounter} retries`); @@ -232,8 +245,10 @@ function measureDCF() { function measureTTFI() { var x = window.performance.timing.timeToFirstInteractive; - if (typeof(x) == "undefined") { - raptorLog("ERROR: timeToFirstInteractive is undefined; ensure the pref is enabled"); + if (typeof x == "undefined") { + raptorLog( + "ERROR: timeToFirstInteractive is undefined; ensure the pref is enabled" + ); return; } if (x > 0) { @@ -250,7 +265,9 @@ function measureTTFI() { // times out at 30 seconds). Some pages will never get 5 seconds // without a busy period! if (gRetryCounter <= 25 * (1000 / 200)) { - raptorLog(`TTFI is not yet available (0), retry number ${gRetryCounter}...`); + raptorLog( + `TTFI is not yet available (0), retry number ${gRetryCounter}...` + ); window.setTimeout(measureTTFI, 200); } else { // unable to get a value for TTFI - negative value will be filtered out later @@ -267,13 +284,16 @@ function measureFCP() { // Firefox implementation of FCP is not yet spec-compliant (see Bug 1519410) result = window.performance.timing.timeToContentfulPaint; - if (typeof(result) == "undefined") { + if (typeof result == "undefined") { // we're on chromium result = 0; let perfEntries = perfData.getEntriesByType("paint"); if (perfEntries.length >= 2) { - if (perfEntries[1].name == "first-contentful-paint" && perfEntries[1].startTime != undefined) { + if ( + perfEntries[1].name == "first-contentful-paint" && + perfEntries[1].startTime != undefined + ) { // this value is actually the final measurement / time to get the FCP event in MS result = perfEntries[1].startTime; } @@ -282,7 +302,7 @@ function measureFCP() { if (result > 0) { raptorLog("got time to first-contentful-paint"); - if (typeof(browser) !== "undefined") { + if (typeof browser !== "undefined") { // Firefox returns a timestamp, not the actual measurement in MS; need to calculate result var startTime = perfData.timing.fetchStart; result = result - startTime; @@ -293,10 +313,14 @@ function measureFCP() { } else { gRetryCounter += 1; if (gRetryCounter <= 10) { - raptorLog(`time to first-contentful-paint is not yet available (0), retry number ${gRetryCounter}...`); + raptorLog( + `time to first-contentful-paint is not yet available (0), retry number ${gRetryCounter}...` + ); window.setTimeout(measureFCP, 100); } else { - raptorLog(`unable to get a value for time-to-fcp after ${gRetryCounter} retries`); + raptorLog( + `unable to get a value for time-to-fcp after ${gRetryCounter} retries` + ); } } } @@ -304,7 +328,7 @@ function measureFCP() { function measureLoadTime() { var x = window.performance.timing.loadEventStart; - if (typeof(x) == "undefined") { + if (typeof x == "undefined") { raptorLog("ERROR: loadEventStart is undefined"); return; } @@ -316,10 +340,14 @@ function measureLoadTime() { } else { gRetryCounter += 1; if (gRetryCounter <= 40 * (1000 / 200)) { - raptorLog(`loadEventStart is not yet available (0), retry number ${gRetryCounter}...`); + raptorLog( + `loadEventStart is not yet available (0), retry number ${gRetryCounter}...` + ); window.setTimeout(measureLoadTime, 100); } else { - raptorLog(`unable to get a value for loadEventStart after ${gRetryCounter} retries`); + raptorLog( + `unable to get a value for loadEventStart after ${gRetryCounter} retries` + ); } } } @@ -327,7 +355,9 @@ function measureLoadTime() { function sendResult(_type, _value) { // send result back to background runner script raptorLog(`sending result back to runner: ${_type} ${_value}`); - chrome.runtime.sendMessage({"type": _type, "value": _value}, function(response) { + chrome.runtime.sendMessage({ type: _type, value: _value }, function( + response + ) { if (response !== undefined) { raptorLog(response.text); } diff --git a/testing/raptor/webext/raptor/runner.js b/testing/raptor/webext/raptor/runner.js index 5c75513aea90..60753dc76bae 100644 --- a/testing/raptor/webext/raptor/runner.js +++ b/testing/raptor/webext/raptor/runner.js @@ -1,4 +1,3 @@ - /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -73,16 +72,16 @@ var debugMode = 0; var screenCapture = false; var results = { - "name": "", - "page": "", - "type": "", - "browser_cycle": 0, - "expected_browser_cycles": 0, - "cold": false, - "lower_is_better": true, - "alert_change_type": "relative", - "alert_threshold": 2.0, - "measurements": {}, + name: "", + page: "", + type: "", + browser_cycle: 0, + expected_browser_cycles: 0, + cold: false, + lower_is_better: true, + alert_change_type: "relative", + alert_threshold: 2.0, + measurements: {}, }; function getTestSettings() { @@ -127,7 +126,8 @@ function getTestSettings() { results.type = testType; results.unit = settings.unit; results.subtest_unit = settings.subtest_unit; - results.subtest_lower_is_better = settings.subtest_lower_is_better === true; + results.subtest_lower_is_better = + settings.subtest_lower_is_better === true; if (settings.gecko_profile === true) { results.extra_options = ["gecko_profile"]; @@ -182,16 +182,18 @@ function getTestSettings() { } // write options to storage that our content script needs to know - if (["firefox", "geckoview", "refbrow", "fenix"].includes(browserName)) { + if ( + ["firefox", "geckoview", "refbrow", "fenix"].includes(browserName) + ) { ext.storage.local.clear().then(function() { - ext.storage.local.set({settings}).then(function() { + ext.storage.local.set({ settings }).then(function() { raptorLog("wrote settings to ext local storage"); resolve(); }); }); } else { ext.storage.local.clear(function() { - ext.storage.local.set({settings}, function() { + ext.storage.local.set({ settings }, function() { raptorLog("wrote settings to ext local storage"); resolve(); }); @@ -239,7 +241,7 @@ function testTabCreated(tab) { testTabID = tab.id; postToControlServer("status", `opened new empty tab: ${testTabID}`); // update raptor browser toolbar icon text, for a visual indicator when debugging - ext.browserAction.setTitle({title: "Raptor RUNNING"}); + ext.browserAction.setTitle({ title: "Raptor RUNNING" }); } function testTabRemoved(tab) { @@ -282,12 +284,14 @@ async function waitForResult() { break; case TEST_PAGE_LOAD: - if (!isHeroPending && - !isFNBPaintPending && - !isFCPPending && - !isDCFPending && - !isTTFIPending && - !isLoadTimePending) { + if ( + !isHeroPending && + !isFNBPaintPending && + !isFCPPending && + !isDCFPending && + !isTTFIPending && + !isLoadTimePending + ) { raptorLog("no more results pending; resolving checkForResult"); resolve(); } else { @@ -336,7 +340,8 @@ async function getScreenCapture() { screenshotUri = await ext.tabs.captureVisibleTab(); } else { screenshotUri = await new Promise(resolve => - ext.tabs.captureVisibleTab(resolve)); + ext.tabs.captureVisibleTab(resolve) + ); } postToControlServer("screenshot", [screenshotUri, testName, pageCycle]); } catch (e) { @@ -345,7 +350,10 @@ async function getScreenCapture() { } async function startGeckoProfiling() { - postToControlServer("status", `starting Gecko profiling for threads: ${geckoThreads}`); + postToControlServer( + "status", + `starting Gecko profiling for threads: ${geckoThreads}` + ); await browser.geckoProfiler.start({ bufferSize: geckoEntries, interval: geckoInterval, @@ -380,7 +388,8 @@ async function nextCycle() { if (isBackgroundTest) { postToControlServer( "end_background", - `bringing app to foreground, pausing for ${foregroundDelay / 1000} seconds` + `bringing app to foreground, pausing for ${foregroundDelay / + 1000} seconds` ); // wait a bit to be sure the app is in foreground before starting // new test, or finishing test @@ -412,16 +421,21 @@ async function nextCycle() { isHeroPending = true; pendingHeroes = Array.from(settings.measure.hero); } - if (getFNBPaint) + if (getFNBPaint) { isFNBPaintPending = true; - if (getFCP) + } + if (getFCP) { isFCPPending = true; - if (getDCF) + } + if (getDCF) { isDCFPending = true; - if (getTTFI) + } + if (getTTFI) { isTTFIPending = true; - if (getLoadTime) + } + if (getLoadTime) { isLoadTimePending = true; + } break; case TEST_SCENARIO: @@ -435,34 +449,34 @@ async function nextCycle() { postToControlServer("status", `closing Tab: ${testTabID}`); // open new tab - ext.tabs.create({url: "about:blank"}); + ext.tabs.create({ url: "about:blank" }); postToControlServer("status", "Open new tab"); } setTimeout(function() { postToControlServer("status", `update tab: ${testTabID}`); // update the test page - browse to our test URL - ext.tabs.update(testTabID, {url: testURL}, testTabUpdated); + ext.tabs.update(testTabID, { url: testURL }, testTabUpdated); if (testType == TEST_SCENARIO) { scenarioTimer(); } - }, newTabDelay); - }, pageCycleDelay); - } else { - verifyResults(); - } + }, newTabDelay); + }, pageCycleDelay); + } else { + verifyResults(); + } } async function timeoutAlarmListener() { console.error(`raptor-page-timeout on ${testURL}`); var pendingMetrics = { - "hero": isHeroPending, + hero: isHeroPending, "fnb paint": isFNBPaintPending, - "fcp": isFCPPending, - "dcf": isDCFPending, - "ttfi": isTTFIPending, + fcp: isFCPPending, + dcf: isDCFPending, + ttfi: isTTFIPending, "load time": isLoadTimePending, }; @@ -483,13 +497,19 @@ function setTimeoutAlarm(timeoutName, timeoutMS) { var now = Date.now(); // eslint-disable-line mozilla/avoid-Date-timing var timeout_when = now + timeoutMS; ext.alarms.create(timeoutName, { when: timeout_when }); - raptorLog(`now is ${now}, set raptor alarm ${timeoutName} to expire ` + - `at ${timeout_when}`); + raptorLog( + `now is ${now}, set raptor alarm ${timeoutName} to expire ` + + `at ${timeout_when}` + ); } function cancelTimeoutAlarm(timeoutName) { - if (browserName === "firefox" || browserName === "geckoview" || - browserName === "refbrow" || browserName === "fenix") { + if ( + browserName === "firefox" || + browserName === "geckoview" || + browserName === "refbrow" || + browserName === "fenix" + ) { var clearAlarm = ext.alarms.clear(timeoutName); clearAlarm.then(function(onCleared) { if (onCleared) { @@ -514,17 +534,18 @@ function resultListener(request, sender, sendResponse) { // check if this is a message from pageloaderjs indicating it is ready to start if (request.type == "pageloadjs-ready") { raptorLog("received pageloadjs-ready!"); - sendResponse({text: "pageloadjs-ready-response"}); + sendResponse({ text: "pageloadjs-ready-response" }); collectResults(); return; } if (request.type && request.value) { raptorLog(`result: ${request.type} ${request.value}`); - sendResponse({text: `confirmed ${request.type}`}); + sendResponse({ text: `confirmed ${request.type}` }); - if (!(request.type in results.measurements)) + if (!(request.type in results.measurements)) { results.measurements[request.type] = []; + } switch (testType) { case TEST_BENCHMARK: @@ -578,8 +599,10 @@ function verifyResults() { if (count == pageCycles) { raptorLog(`have ${count} results for ${x}, as expected`); } else { - raptorLog(`ERROR: expected ${pageCycles} results for ${x} ` + - `but only have ${count}`); + raptorLog( + `ERROR: expected ${pageCycles} results for ${x} ` + + `but only have ${count}` + ); } } postToControlServer("results", results); @@ -607,7 +630,7 @@ function postToControlServer(msgType, msgData = "") { if (msgType != "screenshot") { raptorLog(`${msgData}`); } - var data = { "type": `webext_${msgType}`, "data": msgData}; + var data = { type: `webext_${msgType}`, data: msgData }; client.send(JSON.stringify(data)); } if (msgType == "results") { @@ -682,16 +705,22 @@ function raptorRunner() { // create new empty tab, which starts the test; we want to // wait some time for the browser to settle before beginning - let text = `* pausing ${postStartupDelay / 1000} seconds to let browser settle... *`; + let text = `* pausing ${postStartupDelay / + 1000} seconds to let browser settle... *`; postToControlServer("status", text); // on geckoview you can't create a new tab; only using existing tab - set it blank first - if (config.browser == "geckoview" || config.browser == "refbrow" || - config.browser == "fenix") { - setTimeout(function() { nextCycle(); }, postStartupDelay); + if ( + config.browser == "geckoview" || + config.browser == "refbrow" || + config.browser == "fenix" + ) { + setTimeout(function() { + nextCycle(); + }, postStartupDelay); } else { setTimeout(function() { - ext.tabs.create({url: "about:blank"}); + ext.tabs.create({ url: "about:blank" }); nextCycle(); }, postStartupDelay); } diff --git a/testing/specialpowers/api.js b/testing/specialpowers/api.js index 2b6faab90ddc..cd862b03e927 100644 --- a/testing/specialpowers/api.js +++ b/testing/specialpowers/api.js @@ -4,23 +4,34 @@ /* globals ExtensionAPI */ -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {FileUtils} = ChromeUtils.import("resource://gre/modules/FileUtils.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { FileUtils } = ChromeUtils.import( + "resource://gre/modules/FileUtils.jsm" +); -XPCOMUtils.defineLazyServiceGetter(this, "resProto", - "@mozilla.org/network/protocol;1?name=resource", - "nsISubstitutingProtocolHandler"); +XPCOMUtils.defineLazyServiceGetter( + this, + "resProto", + "@mozilla.org/network/protocol;1?name=resource", + "nsISubstitutingProtocolHandler" +); this.specialpowers = class extends ExtensionAPI { onStartup() { let uri = Services.io.newURI("content/", null, this.extension.rootURI); - resProto.setSubstitutionWithFlags("specialpowers", uri, - resProto.ALLOW_CONTENT_ACCESS); + resProto.setSubstitutionWithFlags( + "specialpowers", + uri, + resProto.ALLOW_CONTENT_ACCESS + ); // Register special testing modules. - Components.manager.QueryInterface(Ci.nsIComponentRegistrar) - .autoRegister(FileUtils.getFile("ProfD", ["tests.manifest"])); + Components.manager + .QueryInterface(Ci.nsIComponentRegistrar) + .autoRegister(FileUtils.getFile("ProfD", ["tests.manifest"])); ChromeUtils.registerWindowActor("SpecialPowers", { allFrames: true, diff --git a/testing/specialpowers/content/MockColorPicker.jsm b/testing/specialpowers/content/MockColorPicker.jsm index 41cd85997510..91cb7b2c546d 100644 --- a/testing/specialpowers/content/MockColorPicker.jsm +++ b/testing/specialpowers/content/MockColorPicker.jsm @@ -14,12 +14,15 @@ Cu.forcePermissiveCOWs(); var registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); var oldClassID = ""; -var newClassID = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator).generateUUID(); +var newClassID = Cc["@mozilla.org/uuid-generator;1"] + .getService(Ci.nsIUUIDGenerator) + .generateUUID(); var newFactory = function(window) { return { createInstance(aOuter, aIID) { - if (aOuter) + if (aOuter) { throw Cr.NS_ERROR_NO_AGGREGATION; + } return new MockColorPickerInstance(window).QueryInterface(aIID); }, lockFactory(aLock) { @@ -38,8 +41,10 @@ var MockColorPicker = { oldClassID = registrar.contractIDToCID(CONTRACT_ID); } catch (ex) { oldClassID = ""; - dump("TEST-INFO | can't get colorpicker registered component, " + - "assuming there is none"); + dump( + "TEST-INFO | can't get colorpicker registered component, " + + "assuming there is none" + ); } registrar.registerFactory(newClassID, "", CONTRACT_ID, this.factory); } @@ -95,8 +100,12 @@ MockColorPickerInstance.prototype = { result = MockColorPicker.returnColor; } } catch (ex) { - dump("TEST-UNEXPECTED-FAIL | Exception in MockColorPicker.jsm open() " + - "method: " + ex + "\n"); + dump( + "TEST-UNEXPECTED-FAIL | Exception in MockColorPicker.jsm open() " + + "method: " + + ex + + "\n" + ); } if (aColorPickerShownCallback) { aColorPickerShownCallback.done(result); diff --git a/testing/specialpowers/content/MockFilePicker.jsm b/testing/specialpowers/content/MockFilePicker.jsm index 27e7703233ca..9f029b597556 100644 --- a/testing/specialpowers/content/MockFilePicker.jsm +++ b/testing/specialpowers/content/MockFilePicker.jsm @@ -8,9 +8,12 @@ const Cm = Components.manager; const CONTRACT_ID = "@mozilla.org/filepicker;1"; -ChromeUtils.defineModuleGetter(this, "FileUtils", - "resource://gre/modules/FileUtils.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +ChromeUtils.defineModuleGetter( + this, + "FileUtils", + "resource://gre/modules/FileUtils.jsm" +); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); // Allow stuff from this scope to be accessed from non-privileged scopes. This // would crash if used outside of automation. @@ -18,12 +21,15 @@ Cu.forcePermissiveCOWs(); var registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); var oldClassID; -var newClassID = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator).generateUUID(); +var newClassID = Cc["@mozilla.org/uuid-generator;1"] + .getService(Ci.nsIUUIDGenerator) + .generateUUID(); var newFactory = function(window) { return { createInstance(aOuter, aIID) { - if (aOuter) + if (aOuter) { throw Cr.NS_ERROR_NO_AGGREGATION; + } return new MockFilePickerInstance(window).QueryInterface(aIID); }, lockFactory(aLock) { @@ -101,11 +107,12 @@ var MockFilePicker = { file.append("testfile"); file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o644); let promise = this.window.File.createFromNsIFile(file) - .then(domFile => domFile, () => null) - // domFile can be null. - .then(domFile => { - this.returnData = [this.internalFileData({ nsIFile: file, domFile })]; - }).then(() => file); + .then(domFile => domFile, () => null) + // domFile can be null. + .then(domFile => { + this.returnData = [this.internalFileData({ nsIFile: file, domFile })]; + }) + .then(() => file); this.pendingPromises = [promise]; @@ -115,7 +122,9 @@ var MockFilePicker = { useBlobFile() { var blob = new this.window.Blob([]); - var file = new this.window.File([blob], "helloworld.txt", { type: "plain/text" }); + var file = new this.window.File([blob], "helloworld.txt", { + type: "plain/text", + }); this.returnData = [this.internalFileData({ domFile: file })]; this.pendingPromises = []; }, @@ -134,10 +143,14 @@ var MockFilePicker = { if (file instanceof this.window.File) { this.returnData.push(this.internalFileData({ domFile: file })); } else { - let promise = this.window.File.createFromNsIFile(file, { existenceCheck: false }); + let promise = this.window.File.createFromNsIFile(file, { + existenceCheck: false, + }); promise.then(domFile => { - this.returnData.push(this.internalFileData({ nsIFile: file, domFile })); + this.returnData.push( + this.internalFileData({ nsIFile: file, domFile }) + ); }); this.pendingPromises.push(promise); } @@ -163,12 +176,14 @@ MockFilePickerInstance.prototype = { this.parent = aParent; }, appendFilter(aTitle, aFilter) { - if (typeof MockFilePicker.appendFilterCallback == "function") + if (typeof MockFilePicker.appendFilterCallback == "function") { MockFilePicker.appendFilterCallback(this, aTitle, aFilter); + } }, appendFilters(aFilterMask) { - if (typeof MockFilePicker.appendFiltersCallback == "function") + if (typeof MockFilePicker.appendFiltersCallback == "function") { MockFilePicker.appendFiltersCallback(this, aFilterMask); + } }, defaultString: "", defaultExtension: "", @@ -201,14 +216,16 @@ MockFilePickerInstance.prototype = { return null; }, get fileURL() { - if (MockFilePicker.returnData.length >= 1 && - MockFilePicker.returnData[0].nsIFile) { + if ( + MockFilePicker.returnData.length >= 1 && + MockFilePicker.returnData[0].nsIFile + ) { return Services.io.newFileURI(MockFilePicker.returnData[0].nsIFile); } return null; }, - * getFiles(asDOM) { + *getFiles(asDOM) { for (let d of MockFilePicker.returnData) { if (asDOM) { yield d.domFile || d.domDirectory; @@ -229,54 +246,64 @@ MockFilePickerInstance.prototype = { MockFilePicker.showing = true; this.window.setTimeout(() => { // Maybe all the pending promises are already resolved, but we want to be sure. - Promise.all(MockFilePicker.pendingPromises).then(() => { - return Ci.nsIFilePicker.returnOK; - }, () => { - return Ci.nsIFilePicker.returnCancel; - }).then(result => { - // Nothing else has to be done. - MockFilePicker.pendingPromises = []; - - if (result == Ci.nsIFilePicker.returnCancel) { - return result; - } - - MockFilePicker.displayDirectory = this.displayDirectory; - MockFilePicker.displaySpecialDirectory = this.displaySpecialDirectory; - MockFilePicker.shown = true; - if (typeof MockFilePicker.showCallback == "function") { - try { - var returnValue = MockFilePicker.showCallback(this); - if (typeof returnValue != "undefined") { - return returnValue; - } - } catch (ex) { + Promise.all(MockFilePicker.pendingPromises) + .then( + () => { + return Ci.nsIFilePicker.returnOK; + }, + () => { return Ci.nsIFilePicker.returnCancel; } - } + ) + .then(result => { + // Nothing else has to be done. + MockFilePicker.pendingPromises = []; - return MockFilePicker.returnValue; - }).then(result => { - // Some additional result file can be set by the callback. Let's - // resolve the pending promises again. - return Promise.all(MockFilePicker.pendingPromises).then(() => { - return result; - }, () => { - return Ci.nsIFilePicker.returnCancel; + if (result == Ci.nsIFilePicker.returnCancel) { + return result; + } + + MockFilePicker.displayDirectory = this.displayDirectory; + MockFilePicker.displaySpecialDirectory = this.displaySpecialDirectory; + MockFilePicker.shown = true; + if (typeof MockFilePicker.showCallback == "function") { + try { + var returnValue = MockFilePicker.showCallback(this); + if (typeof returnValue != "undefined") { + return returnValue; + } + } catch (ex) { + return Ci.nsIFilePicker.returnCancel; + } + } + + return MockFilePicker.returnValue; + }) + .then(result => { + // Some additional result file can be set by the callback. Let's + // resolve the pending promises again. + return Promise.all(MockFilePicker.pendingPromises).then( + () => { + return result; + }, + () => { + return Ci.nsIFilePicker.returnCancel; + } + ); + }) + .then(result => { + MockFilePicker.pendingPromises = []; + + if (aFilePickerShownCallback) { + aFilePickerShownCallback.done(result); + } + + if (typeof MockFilePicker.afterOpenCallback == "function") { + this.window.setTimeout(() => { + MockFilePicker.afterOpenCallback(this); + }, 0); + } }); - }).then(result => { - MockFilePicker.pendingPromises = []; - - if (aFilePickerShownCallback) { - aFilePickerShownCallback.done(result); - } - - if (typeof MockFilePicker.afterOpenCallback == "function") { - this.window.setTimeout(() => { - MockFilePicker.afterOpenCallback(this); - }, 0); - } - }); }); }, }; diff --git a/testing/specialpowers/content/MockPermissionPrompt.jsm b/testing/specialpowers/content/MockPermissionPrompt.jsm index afd34aaf789c..bcb3560ee401 100644 --- a/testing/specialpowers/content/MockPermissionPrompt.jsm +++ b/testing/specialpowers/content/MockPermissionPrompt.jsm @@ -8,15 +8,18 @@ const Cm = Components.manager; const CONTRACT_ID = "@mozilla.org/content-permission/prompt;1"; -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); var registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); var oldClassID, oldFactory; -var newClassID = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator).generateUUID(); +var newClassID = Cc["@mozilla.org/uuid-generator;1"] + .getService(Ci.nsIUUIDGenerator) + .generateUUID(); var newFactory = { createInstance(aOuter, aIID) { - if (aOuter) + if (aOuter) { throw Cr.NS_ERROR_NO_AGGREGATION; + } return new MockPermissionPromptInstance().QueryInterface(aIID); }, lockFactory(aLock) { @@ -35,8 +38,10 @@ var MockPermissionPrompt = { } catch (ex) { oldClassID = ""; oldFactory = null; - dump("TEST-INFO | can't get permission prompt registered component, " + - "assuming there is none"); + dump( + "TEST-INFO | can't get permission prompt registered component, " + + "assuming there is none" + ); } if (oldFactory) { registrar.unregisterFactory(oldClassID, oldFactory); @@ -45,8 +50,7 @@ var MockPermissionPrompt = { } }, - reset() { - }, + reset() {}, cleanup() { this.reset(); @@ -57,7 +61,7 @@ var MockPermissionPrompt = { }, }; -function MockPermissionPromptInstance() { } +function MockPermissionPromptInstance() {} MockPermissionPromptInstance.prototype = { QueryInterface: ChromeUtils.generateQI([Ci.nsIContentPermissionPrompt]), @@ -67,8 +71,12 @@ MockPermissionPromptInstance.prototype = { let perms = request.types.QueryInterface(Ci.nsIArray); for (let idx = 0; idx < perms.length; idx++) { let perm = perms.queryElementAt(idx, Ci.nsIContentPermissionType); - if (Services.perms.testExactPermissionFromPrincipal( - request.principal, perm.type) != Ci.nsIPermissionManager.ALLOW_ACTION) { + if ( + Services.perms.testExactPermissionFromPrincipal( + request.principal, + perm.type + ) != Ci.nsIPermissionManager.ALLOW_ACTION + ) { request.cancel(); return; } diff --git a/testing/specialpowers/content/SpecialPowersAPI.jsm b/testing/specialpowers/content/SpecialPowersAPI.jsm index cb848ae0b77e..48bbb5f3197e 100644 --- a/testing/specialpowers/content/SpecialPowersAPI.jsm +++ b/testing/specialpowers/content/SpecialPowersAPI.jsm @@ -9,27 +9,54 @@ var EXPORTED_SYMBOLS = ["SpecialPowersAPI", "bindDOMWindowUtils"]; -var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -ChromeUtils.defineModuleGetter(this, "MockFilePicker", - "resource://specialpowers/MockFilePicker.jsm"); -ChromeUtils.defineModuleGetter(this, "MockColorPicker", - "resource://specialpowers/MockColorPicker.jsm"); -ChromeUtils.defineModuleGetter(this, "MockPermissionPrompt", - "resource://specialpowers/MockPermissionPrompt.jsm"); -ChromeUtils.defineModuleGetter(this, "SpecialPowersSandbox", - "resource://specialpowers/SpecialPowersSandbox.jsm"); -ChromeUtils.defineModuleGetter(this, "WrapPrivileged", - "resource://specialpowers/WrapPrivileged.jsm"); -ChromeUtils.defineModuleGetter(this, "PrivateBrowsingUtils", - "resource://gre/modules/PrivateBrowsingUtils.jsm"); -ChromeUtils.defineModuleGetter(this, "NetUtil", - "resource://gre/modules/NetUtil.jsm"); -ChromeUtils.defineModuleGetter(this, "AppConstants", - "resource://gre/modules/AppConstants.jsm"); +ChromeUtils.defineModuleGetter( + this, + "MockFilePicker", + "resource://specialpowers/MockFilePicker.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "MockColorPicker", + "resource://specialpowers/MockColorPicker.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "MockPermissionPrompt", + "resource://specialpowers/MockPermissionPrompt.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "SpecialPowersSandbox", + "resource://specialpowers/SpecialPowersSandbox.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "WrapPrivileged", + "resource://specialpowers/WrapPrivileged.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "PrivateBrowsingUtils", + "resource://gre/modules/PrivateBrowsingUtils.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "NetUtil", + "resource://gre/modules/NetUtil.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "AppConstants", + "resource://gre/modules/AppConstants.jsm" +); -ChromeUtils.defineModuleGetter(this, "PerTestCoverageUtils", - "resource://testing-common/PerTestCoverageUtils.jsm"); +ChromeUtils.defineModuleGetter( + this, + "PerTestCoverageUtils", + "resource://testing-common/PerTestCoverageUtils.jsm" +); // Allow stuff from this scope to be accessed from non-privileged scopes. This // would crash if used outside of automation. @@ -39,7 +66,6 @@ function bindDOMWindowUtils(aWindow) { return aWindow && WrapPrivileged.wrap(aWindow.windowUtils); } - // SPConsoleListener reflects nsIConsoleMessage objects into JS in a // tidy, XPCOM-hiding way. Messages that are nsIScriptError objects // have their properties exposed in detail. It also auto-unregisters @@ -52,45 +78,47 @@ SPConsoleListener.prototype = { // Overload the observe method for both nsIConsoleListener and nsIObserver. // The topic will be null for nsIConsoleListener. observe(msg, topic) { - let m = { message: msg.message, - errorMessage: null, - cssSelectors: null, - sourceName: null, - sourceLine: null, - lineNumber: null, - columnNumber: null, - category: null, - windowID: null, - isScriptError: false, - isConsoleEvent: false, - isWarning: false, - isException: false, - isStrict: false }; + let m = { + message: msg.message, + errorMessage: null, + cssSelectors: null, + sourceName: null, + sourceLine: null, + lineNumber: null, + columnNumber: null, + category: null, + windowID: null, + isScriptError: false, + isConsoleEvent: false, + isWarning: false, + isException: false, + isStrict: false, + }; if (msg instanceof Ci.nsIScriptError) { - m.errorMessage = msg.errorMessage; - m.cssSelectors = msg.cssSelectors; - m.sourceName = msg.sourceName; - m.sourceLine = msg.sourceLine; - m.lineNumber = msg.lineNumber; - m.columnNumber = msg.columnNumber; - m.category = msg.category; - m.windowID = msg.outerWindowID; + m.errorMessage = msg.errorMessage; + m.cssSelectors = msg.cssSelectors; + m.sourceName = msg.sourceName; + m.sourceLine = msg.sourceLine; + m.lineNumber = msg.lineNumber; + m.columnNumber = msg.columnNumber; + m.category = msg.category; + m.windowID = msg.outerWindowID; m.innerWindowID = msg.innerWindowID; m.isScriptError = true; - m.isWarning = ((msg.flags & Ci.nsIScriptError.warningFlag) === 1); - m.isException = ((msg.flags & Ci.nsIScriptError.exceptionFlag) === 1); - m.isStrict = ((msg.flags & Ci.nsIScriptError.strictFlag) === 1); + m.isWarning = (msg.flags & Ci.nsIScriptError.warningFlag) === 1; + m.isException = (msg.flags & Ci.nsIScriptError.exceptionFlag) === 1; + m.isStrict = (msg.flags & Ci.nsIScriptError.strictFlag) === 1; } else if (topic === "console-api-log-event") { // This is a dom/console event. let unwrapped = msg.wrappedJSObject; - m.errorMessage = unwrapped.arguments[0]; - m.sourceName = unwrapped.filename; - m.lineNumber = unwrapped.lineNumber; - m.columnNumber = unwrapped.columnNumber; - m.windowID = unwrapped.ID; - m.innerWindowID = unwrapped.innerID; + m.errorMessage = unwrapped.arguments[0]; + m.sourceName = unwrapped.filename; + m.lineNumber = unwrapped.lineNumber; + m.columnNumber = unwrapped.columnNumber; + m.windowID = unwrapped.ID; + m.innerWindowID = unwrapped.innerID; m.isConsoleEvent = true; - m.isWarning = unwrapped.level === "warning"; + m.isWarning = unwrapped.level === "warning"; } Object.freeze(m); @@ -107,8 +135,10 @@ SPConsoleListener.prototype = { } }, - QueryInterface: ChromeUtils.generateQI([Ci.nsIConsoleListener, - Ci.nsIObserver]), + QueryInterface: ChromeUtils.generateQI([ + Ci.nsIConsoleListener, + Ci.nsIObserver, + ]), }; class SpecialPowersAPI extends JSWindowActorChild { @@ -117,7 +147,7 @@ class SpecialPowersAPI extends JSWindowActorChild { this._consoleListeners = []; this._encounteredCrashDumpFiles = []; - this._unexpectedCrashDumpFiles = { }; + this._unexpectedCrashDumpFiles = {}; this._crashDumpDir = null; this._mfl = null; this._applyingPermissions = false; @@ -127,29 +157,33 @@ class SpecialPowersAPI extends JSWindowActorChild { this._os = null; this._pu = null; - this._nextExtensionID = 0; this._extensionListeners = null; } receiveMessage(message) { switch (message.name) { - case "Assert": { - // An assertion has been done in a mochitest chrome script - let {name, passed, stack, diag} = message.data; + case "Assert": + { + // An assertion has been done in a mochitest chrome script + let { name, passed, stack, diag } = message.data; - let SimpleTest = ( - this.contentWindow && - this.contentWindow.wrappedJSObject.SimpleTest); + let SimpleTest = + this.contentWindow && this.contentWindow.wrappedJSObject.SimpleTest; - if (SimpleTest) { - SimpleTest.record(passed, name, diag, stack && stack.formattedStack); - } else { - // Well, this is unexpected. - dump(name + "\n"); + if (SimpleTest) { + SimpleTest.record( + passed, + name, + diag, + stack && stack.formattedStack + ); + } else { + // Well, this is unexpected. + dump(name + "\n"); + } } - } - break; + break; } return undefined; } @@ -182,9 +216,15 @@ class SpecialPowersAPI extends JSWindowActorChild { * properties. This is explained in a comment in the wrapper code above, * and shouldn't be a problem. */ - wrap(obj) { return WrapPrivileged.wrap(obj); } - unwrap(obj) { return WrapPrivileged.unwrap(obj); } - isWrapper(val) { return WrapPrivileged.isWrapper(val); } + wrap(obj) { + return WrapPrivileged.wrap(obj); + } + unwrap(obj) { + return WrapPrivileged.unwrap(obj); + } + isWrapper(val) { + return WrapPrivileged.isWrapper(val); + } /* * When content needs to pass a callback or a callback object to an API @@ -193,16 +233,23 @@ class SpecialPowersAPI extends JSWindowActorChild { * need a layer to wrap the values in SpecialPowers wrappers before they ever * reach content. */ - wrapCallback(func) { return WrapPrivileged.wrapCallback(func); } - wrapCallbackObject(obj) { return WrapPrivileged.wrapCallbackObject(obj); } + wrapCallback(func) { + return WrapPrivileged.wrapCallback(func); + } + wrapCallbackObject(obj) { + return WrapPrivileged.wrapCallbackObject(obj); + } /* * Used for assigning a property to a SpecialPowers wrapper, without unwrapping * the value that is assigned. */ setWrapped(obj, prop, val) { - if (!WrapPrivileged.isWrapper(obj)) - throw new Error("You only need to use this for SpecialPowers wrapped objects"); + if (!WrapPrivileged.isWrapper(obj)) { + throw new Error( + "You only need to use this for SpecialPowers wrapped objects" + ); + } obj = WrapPrivileged.unwrap(obj); return Reflect.set(obj, prop, val); @@ -250,7 +297,7 @@ class SpecialPowersAPI extends JSWindowActorChild { var mc = new window.MessageChannel(); sb.port = mc.port1; try { - let blob = new Blob([str], {type: "application/javascript"}); + let blob = new Blob([str], { type: "application/javascript" }); let blobUrl = URL.createObjectURL(blob); Services.scriptloader.loadSubScript(blobUrl, sb); } catch (e) { @@ -263,8 +310,9 @@ class SpecialPowersAPI extends JSWindowActorChild { _readUrlAsString(aUrl) { // Fetch script content as we can't use scriptloader's loadSubScript // to evaluate http:// urls... - var scriptableStream = Cc["@mozilla.org/scriptableinputstream;1"] - .getService(Ci.nsIScriptableInputStream); + var scriptableStream = Cc[ + "@mozilla.org/scriptableinputstream;1" + ].getService(Ci.nsIScriptableInputStream); var channel = NetUtil.newChannel({ uri: aUrl, @@ -293,8 +341,9 @@ class SpecialPowersAPI extends JSWindowActorChild { if (status == 404) { throw new Error( `Error while executing chrome script '${aUrl}':\n` + - "The script doesn't exist. Ensure you have registered it in " + - "'support-files' in your mochitest.ini."); + "The script doesn't exist. Ensure you have registered it in " + + "'support-files' in your mochitest.ini." + ); } return output; @@ -302,13 +351,14 @@ class SpecialPowersAPI extends JSWindowActorChild { loadChromeScript(urlOrFunction, sandboxOptions) { // Create a unique id for this chrome script - let uuidGenerator = Cc["@mozilla.org/uuid-generator;1"] - .getService(Ci.nsIUUIDGenerator); + let uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].getService( + Ci.nsIUUIDGenerator + ); let id = uuidGenerator.generateUUID().toString(); // Tells chrome code to evaluate this chrome script let scriptArgs = { id, sandboxOptions }; - if (typeof(urlOrFunction) == "function") { + if (typeof urlOrFunction == "function") { scriptArgs.function = { body: "(" + urlOrFunction.toString() + ")();", name: urlOrFunction.name, @@ -324,8 +374,7 @@ class SpecialPowersAPI extends JSWindowActorChild { }; scriptArgs.url = urlOrFunction; } - this.sendAsyncMessage("SPLoadChromeScript", - scriptArgs); + this.sendAsyncMessage("SPLoadChromeScript", scriptArgs); // Returns a MessageManager like API in order to be // able to communicate with this chrome script @@ -335,27 +384,26 @@ class SpecialPowersAPI extends JSWindowActorChild { listeners.push({ name, listener }); }, - promiseOneMessage: name => new Promise(resolve => { - chromeScript.addMessageListener(name, function listener(message) { - chromeScript.removeMessageListener(name, listener); - resolve(message); - }); - }), + promiseOneMessage: name => + new Promise(resolve => { + chromeScript.addMessageListener(name, function listener(message) { + chromeScript.removeMessageListener(name, listener); + resolve(message); + }); + }), removeMessageListener: (name, listener) => { listeners = listeners.filter( - o => (o.name != name || o.listener != listener) + o => o.name != name || o.listener != listener ); }, sendAsyncMessage: (name, message) => { - this.sendAsyncMessage("SPChromeScriptMessage", - { id, name, message }); + this.sendAsyncMessage("SPChromeScriptMessage", { id, name, message }); }, sendQuery: (name, message) => { - return this.sendQuery("SPChromeScriptMessage", - { id, name, message }); + return this.sendQuery("SPChromeScriptMessage", { id, name, message }); }, destroy: () => { @@ -363,16 +411,19 @@ class SpecialPowersAPI extends JSWindowActorChild { this._removeMessageListener("SPChromeScriptMessage", chromeScript); }, - receiveMessage: (aMessage) => { + receiveMessage: aMessage => { let messageId = aMessage.json.id; let name = aMessage.json.name; let message = aMessage.json.message; if (this.contentWindow) { - message = new StructuredCloneHolder(message).deserialize(this.contentWindow); + message = new StructuredCloneHolder(message).deserialize( + this.contentWindow + ); } // Ignore message from other chrome script - if (messageId != id) + if (messageId != id) { return null; + } let result; if (aMessage.name == "SPChromeScriptMessage") { @@ -391,7 +442,10 @@ class SpecialPowersAPI extends JSWindowActorChild { async importInMainProcess(importString) { var message = await this.sendQuery("SPImportInMainProcess", importString); if (message.hadError) { - throw new Error("SpecialPowers.importInMainProcess failed with error " + message.errorMessage); + throw new Error( + "SpecialPowers.importInMainProcess failed with error " + + message.errorMessage + ); } } @@ -409,14 +463,23 @@ class SpecialPowersAPI extends JSWindowActorChild { /* * Convenient shortcuts to the standard Components abbreviations. */ - get Cc() { return WrapPrivileged.wrap(this.getFullComponents().classes); } - get Ci() { return WrapPrivileged.wrap(this.getFullComponents().interfaces); } - get Cu() { return WrapPrivileged.wrap(this.getFullComponents().utils); } - get Cr() { return WrapPrivileged.wrap(this.getFullComponents().results); } + get Cc() { + return WrapPrivileged.wrap(this.getFullComponents().classes); + } + get Ci() { + return WrapPrivileged.wrap(this.getFullComponents().interfaces); + } + get Cu() { + return WrapPrivileged.wrap(this.getFullComponents().utils); + } + get Cr() { + return WrapPrivileged.wrap(this.getFullComponents().results); + } getDOMWindowUtils(aWindow) { - if (aWindow == this.contentWindow && this.DOMWindowUtils != null) + if (aWindow == this.contentWindow && this.DOMWindowUtils != null) { return this.DOMWindowUtils; + } return bindDOMWindowUtils(aWindow); } @@ -430,20 +493,26 @@ class SpecialPowersAPI extends JSWindowActorChild { return WrapPrivileged.wrap(new DOMParser()); } - get InspectorUtils() { return WrapPrivileged.wrap(InspectorUtils); } + get InspectorUtils() { + return WrapPrivileged.wrap(InspectorUtils); + } - get PromiseDebugging() { return WrapPrivileged.wrap(PromiseDebugging); } + get PromiseDebugging() { + return WrapPrivileged.wrap(PromiseDebugging); + } async waitForCrashes(aExpectingProcessCrash) { if (!aExpectingProcessCrash) { return; } - var crashIds = this._encounteredCrashDumpFiles.filter((filename) => { - return ((filename.length === 40) && filename.endsWith(".dmp")); - }).map((id) => { - return id.slice(0, -4); // Strip the .dmp extension to get the ID - }); + var crashIds = this._encounteredCrashDumpFiles + .filter(filename => { + return filename.length === 40 && filename.endsWith(".dmp"); + }) + .map(id => { + return id.slice(0, -4); // Strip the .dmp extension to get the ID + }); await this.sendQuery("SPProcessCrashManagerWait", { crashIds, @@ -457,7 +526,7 @@ class SpecialPowersAPI extends JSWindowActorChild { op: "delete-crash-dump-files", filenames: this._encounteredCrashDumpFiles, }; - if (!await this.sendQuery("SPProcessCrashService", message)) { + if (!(await this.sendQuery("SPProcessCrashService", message))) { success = false; } } @@ -487,11 +556,13 @@ class SpecialPowersAPI extends JSWindowActorChild { _setTimeout(callback) { // for mochitest-browser - if (typeof this.chromeWindow != "undefined") + if (typeof this.chromeWindow != "undefined") { this.chromeWindow.setTimeout(callback, 0); + } // for mochitest-plain - else + else { this.contentWindow.setTimeout(callback, 0); + } } promiseTimeout(delay) { @@ -501,17 +572,17 @@ class SpecialPowersAPI extends JSWindowActorChild { } _delayCallbackTwice(callback) { - let delayedCallback = () => { - let delayAgain = (aCallback) => { - // Using this._setTimeout doesn't work here - // It causes failures in mochtests that use - // multiple pushPrefEnv calls - // For chrome/browser-chrome mochitests - this._setTimeout(aCallback); - }; - delayAgain(delayAgain.bind(this, callback)); - }; - return delayedCallback; + let delayedCallback = () => { + let delayAgain = aCallback => { + // Using this._setTimeout doesn't work here + // It causes failures in mochtests that use + // multiple pushPrefEnv calls + // For chrome/browser-chrome mochitests + this._setTimeout(aCallback); + }; + delayAgain(delayAgain.bind(this, callback)); + }; + return delayedCallback; } /* apply permissions to the system and when the test case is finished (SimpleTest.finish()) @@ -529,65 +600,94 @@ class SpecialPowersAPI extends JSWindowActorChild { var cleanupPermissions = []; for (var p in inPermissions) { - var permission = inPermissions[p]; - var originalValue = Ci.nsIPermissionManager.UNKNOWN_ACTION; - var context = Cu.unwaiveXrays(permission.context); // Sometimes |context| is a DOM object on which we expect - // to be able to access .nodePrincipal, so we need to unwaive. - if (await this.testPermission(permission.type, Ci.nsIPermissionManager.ALLOW_ACTION, context)) { - originalValue = Ci.nsIPermissionManager.ALLOW_ACTION; - } else if (await this.testPermission(permission.type, Ci.nsIPermissionManager.DENY_ACTION, context)) { - originalValue = Ci.nsIPermissionManager.DENY_ACTION; - } else if (await this.testPermission(permission.type, Ci.nsIPermissionManager.PROMPT_ACTION, context)) { - originalValue = Ci.nsIPermissionManager.PROMPT_ACTION; - } else if (await this.testPermission(permission.type, Ci.nsICookiePermission.ACCESS_SESSION, context)) { - originalValue = Ci.nsICookiePermission.ACCESS_SESSION; - } + var permission = inPermissions[p]; + var originalValue = Ci.nsIPermissionManager.UNKNOWN_ACTION; + var context = Cu.unwaiveXrays(permission.context); // Sometimes |context| is a DOM object on which we expect + // to be able to access .nodePrincipal, so we need to unwaive. + if ( + await this.testPermission( + permission.type, + Ci.nsIPermissionManager.ALLOW_ACTION, + context + ) + ) { + originalValue = Ci.nsIPermissionManager.ALLOW_ACTION; + } else if ( + await this.testPermission( + permission.type, + Ci.nsIPermissionManager.DENY_ACTION, + context + ) + ) { + originalValue = Ci.nsIPermissionManager.DENY_ACTION; + } else if ( + await this.testPermission( + permission.type, + Ci.nsIPermissionManager.PROMPT_ACTION, + context + ) + ) { + originalValue = Ci.nsIPermissionManager.PROMPT_ACTION; + } else if ( + await this.testPermission( + permission.type, + Ci.nsICookiePermission.ACCESS_SESSION, + context + ) + ) { + originalValue = Ci.nsICookiePermission.ACCESS_SESSION; + } - let principal = this._getPrincipalFromArg(context); - if (principal.isSystemPrincipal) { - continue; - } + let principal = this._getPrincipalFromArg(context); + if (principal.isSystemPrincipal) { + continue; + } - let perm; - if (typeof permission.allow !== "boolean") { - perm = permission.allow; - } else { - perm = permission.allow ? Ci.nsIPermissionManager.ALLOW_ACTION - : Ci.nsIPermissionManager.DENY_ACTION; - } + let perm; + if (typeof permission.allow !== "boolean") { + perm = permission.allow; + } else { + perm = permission.allow + ? Ci.nsIPermissionManager.ALLOW_ACTION + : Ci.nsIPermissionManager.DENY_ACTION; + } - if (permission.remove) - perm = Ci.nsIPermissionManager.UNKNOWN_ACTION; + if (permission.remove) { + perm = Ci.nsIPermissionManager.UNKNOWN_ACTION; + } - if (originalValue == perm) { - continue; - } + if (originalValue == perm) { + continue; + } - var todo = {"op": "add", - "type": permission.type, - "permission": perm, - "value": perm, - "principal": principal, - "expireType": (typeof permission.expireType === "number") ? - permission.expireType : 0, // default: EXPIRE_NEVER - "expireTime": (typeof permission.expireTime === "number") ? - permission.expireTime : 0}; + var todo = { + op: "add", + type: permission.type, + permission: perm, + value: perm, + principal, + expireType: + typeof permission.expireType === "number" ? permission.expireType : 0, // default: EXPIRE_NEVER + expireTime: + typeof permission.expireTime === "number" ? permission.expireTime : 0, + }; - var cleanupTodo = Object.assign({}, todo); + var cleanupTodo = Object.assign({}, todo); - if (permission.remove) - todo.op = "remove"; + if (permission.remove) { + todo.op = "remove"; + } - pendingPermissions.push(todo); + pendingPermissions.push(todo); - /* Push original permissions value or clear into cleanup array */ - if (originalValue == Ci.nsIPermissionManager.UNKNOWN_ACTION) { - cleanupTodo.op = "remove"; - } else { - cleanupTodo.value = originalValue; - cleanupTodo.permission = originalValue; - } - cleanupPermissions.push(cleanupTodo); + /* Push original permissions value or clear into cleanup array */ + if (originalValue == Ci.nsIPermissionManager.UNKNOWN_ACTION) { + cleanupTodo.op = "remove"; + } else { + cleanupTodo.value = originalValue; + cleanupTodo.permission = originalValue; + } + cleanupPermissions.push(cleanupTodo); } if (pendingPermissions.length > 0) { @@ -606,16 +706,24 @@ class SpecialPowersAPI extends JSWindowActorChild { // main-process) and get signals from it. if (this.isMainProcess()) { this.permissionObserverProxy._specialPowersAPI = this; - Services.obs.addObserver(this.permissionObserverProxy, "perm-changed"); + Services.obs.addObserver( + this.permissionObserverProxy, + "perm-changed" + ); } else { this.registerObservers("perm-changed"); // bind() is used to set 'this' to SpecialPowersAPI itself. - this._addMessageListener("specialpowers-perm-changed", this.permChangedProxy.bind(this)); + this._addMessageListener( + "specialpowers-perm-changed", + this.permChangedProxy.bind(this) + ); } } this._permissionsUndoStack.push(cleanupPermissions); - this._pendingPermissions.push([pendingPermissions, - this._delayCallbackTwice(callback)]); + this._pendingPermissions.push([ + pendingPermissions, + this._delayCallbackTwice(callback), + ]); this._applyPermissions(); } else { this._setTimeout(callback); @@ -641,8 +749,8 @@ class SpecialPowersAPI extends JSWindowActorChild { */ registerObservers(topic) { var msg = { - "op": "add", - "observerTopic": topic, + op: "add", + observerTopic: topic, }; return this.sendQuery("SPObserverService", msg); } @@ -664,7 +772,10 @@ class SpecialPowersAPI extends JSWindowActorChild { } else { if (this._observingPermissions) { this._observingPermissions = false; - this._removeMessageListener("specialpowers-perm-changed", this.permChangedProxy.bind(this)); + this._removeMessageListener( + "specialpowers-perm-changed", + this.permChangedProxy.bind(this) + ); } this._setTimeout(resolve); } @@ -676,16 +787,18 @@ class SpecialPowersAPI extends JSWindowActorChild { } flushPermissions(callback) { - while (this._permissionsUndoStack.length > 1) + while (this._permissionsUndoStack.length > 1) { this.popPermissions(null); + } return this.popPermissions(callback); } - setTestPluginEnabledState(newEnabledState, pluginName) { - return this.sendQuery("SPSetTestPluginEnabledState", - { newEnabledState, pluginName }); + return this.sendQuery("SPSetTestPluginEnabledState", { + newEnabledState, + pluginName, + }); } /* @@ -709,9 +822,9 @@ class SpecialPowersAPI extends JSWindowActorChild { this._permissionObserver._lastPermission = lastPermission; this._permissionObserver._callback = callback; this._permissionObserver._nextCallback = function() { - self._applyingPermissions = false; - // Now apply any permissions that may have been queued while we were applying - self._applyPermissions(); + self._applyingPermissions = false; + // Now apply any permissions that may have been queued while we were applying + self._applyPermissions(); }; for (var idx in pendingActions) { @@ -737,12 +850,18 @@ class SpecialPowersAPI extends JSWindowActorChild { _addObserverProxy(notification) { if (notification in this._proxiedObservers) { - this._addMessageListener(notification, this._proxiedObservers[notification]); + this._addMessageListener( + notification, + this._proxiedObservers[notification] + ); } } _removeObserverProxy(notification) { if (notification in this._proxiedObservers) { - this._removeMessageListener(notification, this._proxiedObservers[notification]); + this._removeMessageListener( + notification, + this._proxiedObservers[notification] + ); } } @@ -752,8 +871,12 @@ class SpecialPowersAPI extends JSWindowActorChild { this._addObserverProxy(notification); obs = Cu.waiveXrays(obs); - if (typeof obs == "object" && obs.observe.name != "SpecialPowersCallbackWrapper") + if ( + typeof obs == "object" && + obs.observe.name != "SpecialPowersCallbackWrapper" + ) { obs.observe = WrapPrivileged.wrapCallback(obs.observe); + } Services.obs.addObserver(obs, notification, weak); } removeObserver(obs, notification) { @@ -775,7 +898,10 @@ class SpecialPowersAPI extends JSWindowActorChild { */ addAsyncObserver(obs, notification, weak) { obs = Cu.waiveXrays(obs); - if (typeof obs == "object" && obs.observe.name != "SpecialPowersCallbackWrapper") { + if ( + typeof obs == "object" && + obs.observe.name != "SpecialPowersCallbackWrapper" + ) { obs.observe = WrapPrivileged.wrapCallback(obs.observe); } let asyncObs = (...args) => { @@ -803,9 +929,9 @@ class SpecialPowersAPI extends JSWindowActorChild { } call_Instanceof(obj1, obj2) { - obj1 = WrapPrivileged.unwrap(obj1); - obj2 = WrapPrivileged.unwrap(obj2); - return obj1 instanceof obj2; + obj1 = WrapPrivileged.unwrap(obj1); + obj2 = WrapPrivileged.unwrap(obj2); + return obj1 instanceof obj2; } // Returns a privileged getter from an object. GetOwnPropertyDescriptor does @@ -910,20 +1036,20 @@ class SpecialPowersAPI extends JSWindowActorChild { // XXX: these APIs really ought to be removed, they're not e10s-safe. // (also they're pretty Firefox-specific) _getTopChromeWindow(window) { - return window.docShell.rootTreeItem.domWindow - .QueryInterface(Ci.nsIDOMChromeWindow); + return window.docShell.rootTreeItem.domWindow.QueryInterface( + Ci.nsIDOMChromeWindow + ); } _getAutoCompletePopup(window) { - return this._getTopChromeWindow(window).document - .getElementById("PopupAutoComplete"); + return this._getTopChromeWindow(window).document.getElementById( + "PopupAutoComplete" + ); } addAutoCompletePopupEventListener(window, eventname, listener) { - this._getAutoCompletePopup(window).addEventListener(eventname, - listener); + this._getAutoCompletePopup(window).addEventListener(eventname, listener); } removeAutoCompletePopupEventListener(window, eventname, listener) { - this._getAutoCompletePopup(window).removeEventListener(eventname, - listener); + this._getAutoCompletePopup(window).removeEventListener(eventname, listener); } get formHistory() { let tmp = {}; @@ -931,29 +1057,40 @@ class SpecialPowersAPI extends JSWindowActorChild { return WrapPrivileged.wrap(tmp.FormHistory); } getFormFillController(window) { - return Cc["@mozilla.org/satchel/form-fill-controller;1"] - .getService(Ci.nsIFormFillController); + return Cc["@mozilla.org/satchel/form-fill-controller;1"].getService( + Ci.nsIFormFillController + ); } attachFormFillControllerTo(window) { - this.getFormFillController() - .attachPopupElementToBrowser(window.docShell, - this._getAutoCompletePopup(window)); + this.getFormFillController().attachPopupElementToBrowser( + window.docShell, + this._getAutoCompletePopup(window) + ); } detachFormFillControllerFrom(window) { this.getFormFillController().detachFromBrowser(window.docShell); } isBackButtonEnabled(window) { - return !this._getTopChromeWindow(window).document - .getElementById("Browser:Back") - .hasAttribute("disabled"); + return !this._getTopChromeWindow(window) + .document.getElementById("Browser:Back") + .hasAttribute("disabled"); } // XXX end of problematic APIs addChromeEventListener(type, listener, capture, allowUntrusted) { - this.docShell.chromeEventHandler.addEventListener(type, listener, capture, allowUntrusted); + this.docShell.chromeEventHandler.addEventListener( + type, + listener, + capture, + allowUntrusted + ); } removeChromeEventListener(type, listener, capture) { - this.docShell.chromeEventHandler.removeEventListener(type, listener, capture); + this.docShell.chromeEventHandler.removeEventListener( + type, + listener, + capture + ); } // Note: each call to registerConsoleListener MUST be paired with a @@ -1007,16 +1144,23 @@ class SpecialPowersAPI extends JSWindowActorChild { } snapshotWindowWithOptions(win, rect, bgcolor, options) { - var el = this.document.createElementNS("http://www.w3.org/1999/xhtml", "canvas"); + var el = this.document.createElementNS( + "http://www.w3.org/1999/xhtml", + "canvas" + ); if (rect === undefined) { - rect = { top: win.scrollY, left: win.scrollX, - width: win.innerWidth, height: win.innerHeight }; + rect = { + top: win.scrollY, + left: win.scrollX, + width: win.innerWidth, + height: win.innerHeight, + }; } if (bgcolor === undefined) { bgcolor = "rgb(255,255,255)"; } if (options === undefined) { - options = { }; + options = {}; } el.width = rect.width; @@ -1028,16 +1172,22 @@ class SpecialPowersAPI extends JSWindowActorChild { flags |= options[option] && ctx[option]; } - ctx.drawWindow(win, - rect.left, rect.top, rect.width, rect.height, - bgcolor, - flags); + ctx.drawWindow( + win, + rect.left, + rect.top, + rect.width, + rect.height, + bgcolor, + flags + ); return el; } snapshotWindow(win, withCaret, rect, bgcolor) { - return this.snapshotWindowWithOptions(win, rect, bgcolor, - { DRAWWINDOW_DRAW_CARET: withCaret }); + return this.snapshotWindowWithOptions(win, rect, bgcolor, { + DRAWWINDOW_DRAW_CARET: withCaret, + }); } snapshotRect(win, rect, bgcolor) { @@ -1099,7 +1249,7 @@ class SpecialPowersAPI extends JSWindowActorChild { Cc["@mozilla.org/memory-reporter-manager;1"] .getService(Ci.nsIMemoryReporterManager) .getReports(() => {}, null, () => {}, null, false); - } catch (e) { } + } catch (e) {} } setGCZeal(zeal) { @@ -1108,14 +1258,17 @@ class SpecialPowersAPI extends JSWindowActorChild { isMainProcess() { try { - return Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT; - } catch (e) { } + return ( + Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT + ); + } catch (e) {} return true; } get XPCOMABI() { - if (this._xpcomabi != null) + if (this._xpcomabi != null) { return this._xpcomabi; + } var xulRuntime = Services.appinfo.QueryInterface(Ci.nsIXULRuntime); @@ -1129,15 +1282,17 @@ class SpecialPowersAPI extends JSWindowActorChild { executeSoon(aFun, aWin) { // Create the runnable in the scope of aWin to avoid running into COWs. var runnable = {}; - if (aWin) - runnable = Cu.createObjectIn(aWin); + if (aWin) { + runnable = Cu.createObjectIn(aWin); + } runnable.run = aFun; Cu.dispatch(runnable, aWin); } get OS() { - if (this._os != null) + if (this._os != null) { return this._os; + } this._os = Services.appinfo.OS; return this._os; @@ -1161,23 +1316,29 @@ class SpecialPowersAPI extends JSWindowActorChild { getDOMRequestService() { var serv = Services.DOMRequest; var res = {}; - var props = ["createRequest", "createCursor", "fireError", "fireSuccess", - "fireDone", "fireDetailedError"]; + var props = [ + "createRequest", + "createCursor", + "fireError", + "fireSuccess", + "fireDone", + "fireDetailedError", + ]; for (var i in props) { let prop = props[i]; - res[prop] = function() { return serv[prop].apply(serv, arguments); }; + res[prop] = function() { + return serv[prop].apply(serv, arguments); + }; } return res; } addCategoryEntry(category, entry, value, persists, replace) { - Services.catMan - .addCategoryEntry(category, entry, value, persists, replace); + Services.catMan.addCategoryEntry(category, entry, value, persists, replace); } deleteCategoryEntry(category, entry, persists) { - Services.catMan - .deleteCategoryEntry(category, entry, persists); + Services.catMan.deleteCategoryEntry(category, entry, persists); } openDialog(win, args) { return win.openDialog.apply(win, args); @@ -1261,12 +1422,14 @@ class SpecialPowersAPI extends JSWindowActorChild { _spawnTask(task, args, caller, taskId) { let sb = new SpecialPowersSandbox(null, data => { - this.sendAsyncMessage("ProxiedAssert", {taskId, data}); + this.sendAsyncMessage("ProxiedAssert", { taskId, data }); }); sb.sandbox.SpecialPowers = this; Object.defineProperty(sb.sandbox, "content", { - get: () => { return this.contentWindow; }, + get: () => { + return this.contentWindow; + }, enumerable: true, }); @@ -1294,12 +1457,14 @@ class SpecialPowersAPI extends JSWindowActorChild { focus(aWindow) { // This is called inside TestRunner._makeIframe without aWindow, because of assertions in oop mochitests // With aWindow, it is called in SimpleTest.waitForFocus to allow popup window opener focus switching - if (aWindow) + if (aWindow) { aWindow.focus(); + } try { - let actor = (aWindow ? aWindow.getWindowGlobalChild().getActor("SpecialPowers") - : this); + let actor = aWindow + ? aWindow.getWindowGlobalChild().getActor("SpecialPowers") + : this; actor.sendAsyncMessage("SpecialPowers.Focus", {}); } catch (e) { Cu.reportError(e); @@ -1307,11 +1472,13 @@ class SpecialPowersAPI extends JSWindowActorChild { } getClipboardData(flavor, whichClipboard) { - if (whichClipboard === undefined) + if (whichClipboard === undefined) { whichClipboard = Services.clipboard.kGlobalClipboard; + } - var xferable = Cc["@mozilla.org/widget/transferable;1"]. - createInstance(Ci.nsITransferable); + var xferable = Cc["@mozilla.org/widget/transferable;1"].createInstance( + Ci.nsITransferable + ); xferable.init(this.docShell); xferable.addDataFlavor(flavor); Services.clipboard.getData(xferable, whichClipboard); @@ -1320,16 +1487,17 @@ class SpecialPowersAPI extends JSWindowActorChild { xferable.getTransferData(flavor, data); } catch (e) {} data = data.value || null; - if (data == null) + if (data == null) { return ""; + } return data.QueryInterface(Ci.nsISupportsString).data; } clipboardCopyString(str) { - Cc["@mozilla.org/widget/clipboardhelper;1"]. - getService(Ci.nsIClipboardHelper). - copyString(str); + Cc["@mozilla.org/widget/clipboardhelper;1"] + .getService(Ci.nsIClipboardHelper) + .copyString(str); } supportsSelectionClipboard() { @@ -1339,30 +1507,31 @@ class SpecialPowersAPI extends JSWindowActorChild { swapFactoryRegistration(cid, contractID, newFactory) { newFactory = Cu.waiveXrays(newFactory); - var componentRegistrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); + var componentRegistrar = Components.manager.QueryInterface( + Ci.nsIComponentRegistrar + ); var currentCID = componentRegistrar.contractIDToCID(contractID); - var currentFactory = Components.manager.getClassObject(Cc[contractID], - Ci.nsIFactory); + var currentFactory = Components.manager.getClassObject( + Cc[contractID], + Ci.nsIFactory + ); if (cid) { componentRegistrar.unregisterFactory(currentCID, currentFactory); } else { - let uuidGenerator = Cc["@mozilla.org/uuid-generator;1"] - .getService(Ci.nsIUUIDGenerator); + let uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].getService( + Ci.nsIUUIDGenerator + ); cid = uuidGenerator.generateUUID(); } // Restore the original factory. - componentRegistrar.registerFactory(cid, - "", - contractID, - newFactory); - return {"originalCID": currentCID}; + componentRegistrar.registerFactory(cid, "", contractID, newFactory); + return { originalCID: currentCID }; } _getElement(aWindow, id) { - return ((typeof(id) == "string") ? - aWindow.document.getElementById(id) : id); + return typeof id == "string" ? aWindow.document.getElementById(id) : id; } dispatchEvent(aWindow, target, event) { @@ -1374,7 +1543,7 @@ class SpecialPowersAPI extends JSWindowActorChild { delete SpecialPowersAPI.prototype.isDebugBuild; var debug = Cc["@mozilla.org/xpcom/debug;1"].getService(Ci.nsIDebug2); - return SpecialPowersAPI.prototype.isDebugBuild = debug.isDebugBuild; + return (SpecialPowersAPI.prototype.isDebugBuild = debug.isDebugBuild); } assertionCount() { var debugsvc = Cc["@mozilla.org/xpcom/debug;1"].getService(Ci.nsIDebug2); @@ -1392,7 +1561,7 @@ class SpecialPowersAPI extends JSWindowActorChild { let principal; let secMan = Services.scriptSecurityManager; - if (typeof(arg) == "string") { + if (typeof arg == "string") { // It's an URL. let uri = Services.io.newURI(arg); principal = secMan.createCodebasePrincipal(uri, {}); @@ -1419,17 +1588,18 @@ class SpecialPowersAPI extends JSWindowActorChild { if (typeof allow !== "boolean") { permission = allow; } else { - permission = allow ? Ci.nsIPermissionManager.ALLOW_ACTION - : Ci.nsIPermissionManager.DENY_ACTION; + permission = allow + ? Ci.nsIPermissionManager.ALLOW_ACTION + : Ci.nsIPermissionManager.DENY_ACTION; } var msg = { - "op": "add", - "type": type, - "permission": permission, - "principal": principal, - "expireType": (typeof expireType === "number") ? expireType : 0, - "expireTime": (typeof expireTime === "number") ? expireTime : 0, + op: "add", + type, + permission, + principal, + expireType: typeof expireType === "number" ? expireType : 0, + expireTime: typeof expireTime === "number" ? expireTime : 0, }; await this.sendQuery("SPPermissionManager", msg); @@ -1442,9 +1612,9 @@ class SpecialPowersAPI extends JSWindowActorChild { } var msg = { - "op": "remove", - "type": type, - "principal": principal, + op: "remove", + type, + principal, }; await this.sendQuery("SPPermissionManager", msg); @@ -1457,9 +1627,9 @@ class SpecialPowersAPI extends JSWindowActorChild { } var msg = { - "op": "has", - "type": type, - "principal": principal, + op: "has", + type, + principal, }; return this.sendQuery("SPPermissionManager", msg); @@ -1472,10 +1642,10 @@ class SpecialPowersAPI extends JSWindowActorChild { } var msg = { - "op": "test", - "type": type, - "value": value, - "principal": principal, + op: "test", + type, + value, + principal, }; return this.sendQuery("SPPermissionManager", msg); } @@ -1493,9 +1663,9 @@ class SpecialPowersAPI extends JSWindowActorChild { return; } var msg = { - "op": "notify", - "observerTopic": topic, - "observerData": data, + op: "notify", + observerTopic: topic, + observerData: data, }; await this.sendQuery("SPObserverService", msg); } @@ -1509,7 +1679,7 @@ class SpecialPowersAPI extends JSWindowActorChild { } cleanUpSTSData(origin, flags) { - return this.sendQuery("SPCleanUpSTSData", {origin, flags: flags || 0}); + return this.sendQuery("SPCleanUpSTSData", { origin, flags: flags || 0 }); } async requestDumpCoverageCounters(cb) { @@ -1549,49 +1719,54 @@ class SpecialPowersAPI extends JSWindowActorChild { // between this content process and the chrome process. let id = this._nextExtensionID++; - handler = Cu.waiveXrays(handler); ext = Cu.waiveXrays(ext); let sp = this; let state = "uninitialized"; let extension = { - get state() { return state; }, + get state() { + return state; + }, startup() { state = "pending"; - return sp.sendQuery("SPStartupExtension", {id}).then( + return sp.sendQuery("SPStartupExtension", { id }).then( () => { state = "running"; - }, () => { + }, + () => { state = "failed"; sp._extensionListeners.delete(listener); return Promise.reject("startup failed"); - }); + } + ); }, unload() { state = "unloading"; - return sp.sendQuery("SPUnloadExtension", {id}).finally(() => { + return sp.sendQuery("SPUnloadExtension", { id }).finally(() => { sp._extensionListeners.delete(listener); state = "unloaded"; }); }, sendMessage(...args) { - sp.sendAsyncMessage("SPExtensionMessage", {id, args}); + sp.sendAsyncMessage("SPExtensionMessage", { id, args }); }, }; - this.sendAsyncMessage("SPLoadExtension", {ext, id}); + this.sendAsyncMessage("SPLoadExtension", { ext, id }); - let listener = (msg) => { + let listener = msg => { if (msg.data.id == id) { if (msg.data.type == "extensionSetId") { extension.id = msg.data.args[0]; extension.uuid = msg.data.args[1]; } else if (msg.data.type in handler) { - handler[msg.data.type](...Cu.cloneInto(msg.data.args, this.contentWindow)); + handler[msg.data.type]( + ...Cu.cloneInto(msg.data.args, this.contentWindow) + ); } else { dump(`Unexpected: ${msg.data.type}\n`); } @@ -1603,7 +1778,11 @@ class SpecialPowersAPI extends JSWindowActorChild { } invalidateExtensionStorageCache() { - this.notifyObserversInParentProcess(null, "extension-invalidate-storage-cache", ""); + this.notifyObserversInParentProcess( + null, + "extension-invalidate-storage-cache", + "" + ); } allowMedia(window, enable) { @@ -1612,14 +1791,17 @@ class SpecialPowersAPI extends JSWindowActorChild { createChromeCache(name, url) { let principal = this._getPrincipalFromArg(url); - return WrapPrivileged.wrap(new this.contentWindow.CacheStorage(name, principal)); + return WrapPrivileged.wrap( + new this.contentWindow.CacheStorage(name, principal) + ); } loadChannelAndReturnStatus(url, loadUsingSystemPrincipal) { - const BinaryInputStream = - Components.Constructor("@mozilla.org/binaryinputstream;1", - "nsIBinaryInputStream", - "setInputStream"); + const BinaryInputStream = Components.Constructor( + "@mozilla.org/binaryinputstream;1", + "nsIBinaryInputStream", + "setInputStream" + ); return new Promise(function(resolve) { let listener = { @@ -1635,15 +1817,15 @@ class SpecialPowersAPI extends JSWindowActorChild { }, onStopRequest(request, status) { - /* testing here that the redirect was not followed. If it was followed + /* testing here that the redirect was not followed. If it was followed we would see a http status of 200 and status of NS_OK */ let httpStatus = this.httpStatus; - resolve({status, httpStatus}); + resolve({ status, httpStatus }); }, }; let uri = NetUtil.newURI(url); - let channel = NetUtil.newChannel({uri, loadUsingSystemPrincipal}); + let channel = NetUtil.newChannel({ uri, loadUsingSystemPrincipal }); channel.loadFlags |= Ci.nsIChannel.LOAD_DOCUMENT_URI; channel.QueryInterface(Ci.nsIHttpChannelInternal); @@ -1653,8 +1835,9 @@ class SpecialPowersAPI extends JSWindowActorChild { } get ParserUtils() { - if (this._pu != null) + if (this._pu != null) { return this._pu; + } let pu = Cc["@mozilla.org/parserutils;1"].getService(Ci.nsIParserUtils); // We need to create and return our own wrapper. @@ -1667,9 +1850,13 @@ class SpecialPowersAPI extends JSWindowActorChild { }, parseFragment(fragment, flags, isXML, baseURL, element) { let baseURI = baseURL ? NetUtil.newURI(baseURL) : null; - return pu.parseFragment(WrapPrivileged.unwrap(fragment), - flags, isXML, baseURI, - WrapPrivileged.unwrap(element)); + return pu.parseFragment( + WrapPrivileged.unwrap(fragment), + flags, + isXML, + baseURI, + WrapPrivileged.unwrap(element) + ); }, }; return this._pu; @@ -1677,8 +1864,9 @@ class SpecialPowersAPI extends JSWindowActorChild { createDOMWalker(node, showAnonymousContent) { node = WrapPrivileged.unwrap(node); - let walker = Cc["@mozilla.org/inspector/deep-tree-walker;1"]. - createInstance(Ci.inIDeepTreeWalker); + let walker = Cc["@mozilla.org/inspector/deep-tree-walker;1"].createInstance( + Ci.inIDeepTreeWalker + ); walker.showAnonymousContent = showAnonymousContent; walker.init(node.ownerDocument, NodeFilter.SHOW_ALL); walker.currentNode = node; @@ -1693,8 +1881,10 @@ class SpecialPowersAPI extends JSWindowActorChild { } observeMutationEvents(mo, node, nativeAnonymousChildList, subtree) { - WrapPrivileged.unwrap(mo).observe(WrapPrivileged.unwrap(node), - {nativeAnonymousChildList, subtree}); + WrapPrivileged.unwrap(mo).observe(WrapPrivileged.unwrap(node), { + nativeAnonymousChildList, + subtree, + }); } doCommand(window, cmd) { @@ -1703,8 +1893,8 @@ class SpecialPowersAPI extends JSWindowActorChild { setCommandNode(window, node) { return window.docShell.contentViewer - .QueryInterface(Ci.nsIContentViewerEdit) - .setCommandNode(node); + .QueryInterface(Ci.nsIContentViewerEdit) + .setCommandNode(node); } /* Bug 1339006 Runnables of nsIURIClassifier.classify may be labeled by @@ -1715,8 +1905,9 @@ class SpecialPowersAPI extends JSWindowActorChild { */ doUrlClassify(principal, eventTarget, callback) { - let classifierService = - Cc["@mozilla.org/url-classifier/dbservice;1"].getService(Ci.nsIURIClassifier); + let classifierService = Cc[ + "@mozilla.org/url-classifier/dbservice;1" + ].getService(Ci.nsIURIClassifier); let wrapCallback = (...args) => { Services.tm.dispatchToMainThread(() => { @@ -1728,37 +1919,54 @@ class SpecialPowersAPI extends JSWindowActorChild { }); }; - return classifierService.classify(WrapPrivileged.unwrap(principal), eventTarget, - wrapCallback); + return classifierService.classify( + WrapPrivileged.unwrap(principal), + eventTarget, + wrapCallback + ); } // TODO: Bug 1353701 - Supports custom event target for labelling. doUrlClassifyLocal(uri, tables, callback) { - let classifierService = - Cc["@mozilla.org/url-classifier/dbservice;1"].getService(Ci.nsIURIClassifier); + let classifierService = Cc[ + "@mozilla.org/url-classifier/dbservice;1" + ].getService(Ci.nsIURIClassifier); let wrapCallback = results => { Services.tm.dispatchToMainThread(() => { if (typeof callback == "function") { callback(WrapPrivileged.wrap(results)); } else { - callback.onClassifyComplete.call(undefined, WrapPrivileged.wrap(results)); + callback.onClassifyComplete.call( + undefined, + WrapPrivileged.wrap(results) + ); } }); }; - let feature = classifierService.createFeatureWithTables("test", tables.split(","), []); - return classifierService.asyncClassifyLocalWithFeatures(WrapPrivileged.unwrap(uri), - [feature], - Ci.nsIUrlClassifierFeature.blacklist, - wrapCallback); + let feature = classifierService.createFeatureWithTables( + "test", + tables.split(","), + [] + ); + return classifierService.asyncClassifyLocalWithFeatures( + WrapPrivileged.unwrap(uri), + [feature], + Ci.nsIUrlClassifierFeature.blacklist, + wrapCallback + ); } } SpecialPowersAPI.prototype._proxiedObservers = { "specialpowers-http-notify-request": function(aMessage) { let uri = aMessage.json.uri; - Services.obs.notifyObservers(null, "specialpowers-http-notify-request", uri); + Services.obs.notifyObservers( + null, + "specialpowers-http-notify-request", + uri + ); }, "specialpowers-service-worker-shutdown": function(aMessage) { @@ -1785,8 +1993,8 @@ SpecialPowersAPI.prototype._permissionObserver = { _callBack: null, _nextCallback: null, _obsDataMap: { - "deleted": "remove", - "added": "add", + deleted: "remove", + added: "add", }, observe(permission, aData) { if (this._self._applyingPermissions) { @@ -1798,12 +2006,18 @@ SpecialPowersAPI.prototype._permissionObserver = { } } else { var found = false; - for (var i = 0; !found && i < this._self._permissionsUndoStack.length; i++) { + for ( + var i = 0; + !found && i < this._self._permissionsUndoStack.length; + i++ + ) { var undos = this._self._permissionsUndoStack[i]; for (var j = 0; j < undos.length; j++) { var undo = undos[j]; - if (undo.op == this._obsDataMap[aData] && - undo.type == permission.type) { + if ( + undo.op == this._obsDataMap[aData] && + undo.type == permission.type + ) { // Remove this undo item if it has been done by others(not // specialpowers itself.) undos.splice(j, 1); @@ -1820,7 +2034,8 @@ SpecialPowersAPI.prototype._permissionObserver = { }, }; -SpecialPowersAPI.prototype.EARLY_BETA_OR_EARLIER = AppConstants.EARLY_BETA_OR_EARLIER; +SpecialPowersAPI.prototype.EARLY_BETA_OR_EARLIER = + AppConstants.EARLY_BETA_OR_EARLIER; // Due to an unfortunate accident of history, when this API was // subclassed using `Thing.prototype = new SpecialPowersAPI()`, existing diff --git a/testing/specialpowers/content/SpecialPowersAPIParent.jsm b/testing/specialpowers/content/SpecialPowersAPIParent.jsm index 7271a1fed366..667f57fa8955 100644 --- a/testing/specialpowers/content/SpecialPowersAPIParent.jsm +++ b/testing/specialpowers/content/SpecialPowersAPIParent.jsm @@ -6,8 +6,10 @@ var EXPORTED_SYMBOLS = ["SpecialPowersAPIParent", "SpecialPowersError"]; -var {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); -var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +var { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); +var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); XPCOMUtils.defineLazyModuleGetters(this, { ExtensionData: "resource://gre/modules/Extension.jsm", @@ -27,28 +29,39 @@ function parseKeyValuePairs(text) { var lines = text.split("\n"); var data = {}; for (let i = 0; i < lines.length; i++) { - if (lines[i] == "") + if (lines[i] == "") { continue; + } // can't just .split() because the value might contain = characters let eq = lines[i].indexOf("="); if (eq != -1) { - let [key, value] = [lines[i].substring(0, eq), - lines[i].substring(eq + 1)]; - if (key && value) + let [key, value] = [ + lines[i].substring(0, eq), + lines[i].substring(eq + 1), + ]; + if (key && value) { data[key] = value.replace(/\\n/g, "\n").replace(/\\\\/g, "\\"); + } } } return data; } function parseKeyValuePairsFromFile(file) { - var fstream = Cc["@mozilla.org/network/file-input-stream;1"]. - createInstance(Ci.nsIFileInputStream); + var fstream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance( + Ci.nsIFileInputStream + ); fstream.init(file, -1, 0, 0); - var is = Cc["@mozilla.org/intl/converter-input-stream;1"]. - createInstance(Ci.nsIConverterInputStream); - is.init(fstream, "UTF-8", 1024, Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER); + var is = Cc["@mozilla.org/intl/converter-input-stream;1"].createInstance( + Ci.nsIConverterInputStream + ); + is.init( + fstream, + "UTF-8", + 1024, + Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER + ); var str = {}; var contents = ""; while (is.readString(4096, str) != 0) { @@ -60,8 +73,7 @@ function parseKeyValuePairsFromFile(file) { } function getTestPlugin(pluginName) { - var ph = Cc["@mozilla.org/plugin/host;1"] - .getService(Ci.nsIPluginHost); + var ph = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost); var tags = ph.getPluginTags(); var name = pluginName || "Test Plug-in"; for (var tag of tags) { @@ -78,9 +90,9 @@ const PREF_TYPES = { [Ci.nsIPrefBranch.PREF_INT]: "INT", [Ci.nsIPrefBranch.PREF_BOOL]: "BOOL", [Ci.nsIPrefBranch.PREF_STRING]: "CHAR", - "number": "INT", - "boolean": "BOOL", - "string": "CHAR", + number: "INT", + boolean: "BOOL", + string: "CHAR", }; // We share a single preference environment stack between all @@ -90,7 +102,9 @@ let inPrefEnvOp = false; function doPrefEnvOp(fn) { if (inPrefEnvOp) { - throw new Error("Reentrant preference environment operations not supported"); + throw new Error( + "Reentrant preference environment operations not supported" + ); } inPrefEnvOp = true; try { @@ -122,8 +136,8 @@ class SpecialPowersAPIParent extends JSWindowActorParent { id = null; } if (id) { - message.dumpIDs.push({id, extension: "dmp"}); - message.dumpIDs.push({id, extension: "extra"}); + message.dumpIDs.push({ id, extension: "dmp" }); + message.dumpIDs.push({ id, extension: "extra" }); } } @@ -138,13 +152,17 @@ class SpecialPowersAPIParent extends JSWindowActorParent { let pluginID = aSubject.getPropertyAsAString("pluginDumpID"); let extra = this._getExtraData(pluginID); - if (extra && ("additional_minidumps" in extra)) { + if (extra && "additional_minidumps" in extra) { let dumpNames = extra.additional_minidumps.split(","); for (let name of dumpNames) { - message.dumpIDs.push({id: pluginID + "-" + name, extension: "dmp"}); + message.dumpIDs.push({ + id: pluginID + "-" + name, + extension: "dmp", + }); } } - } else { // ipc:content-shutdown + } else { + // ipc:content-shutdown if (!aSubject.hasKey("abnormal")) { return; // This is a normal shutdown, ignore it } @@ -245,7 +263,9 @@ class SpecialPowersAPIParent extends JSWindowActorParent { let observers = []; - for (let {value: contractID} of Services.catMan.enumerateCategory(topic)) { + for (let { value: contractID } of Services.catMan.enumerateCategory( + topic + )) { let factoryFunction; if (contractID.substring(0, serviceMarker.length) == serviceMarker) { contractID = contractID.substring(serviceMarker.length); @@ -260,13 +280,12 @@ class SpecialPowersAPIParent extends JSWindowActorParent { let observer = handler.QueryInterface(Ci.nsIObserver); observers.push(observer); } - } catch (e) { } + } catch (e) {} } // Next enumerate the registered observers. for (let observer of Services.obs.enumerateObservers(topic)) { - if (observer instanceof Ci.nsIObserver && - !observers.includes(observer)) { + if (observer instanceof Ci.nsIObserver && !observers.includes(observer)) { observers.push(observer); } } @@ -274,7 +293,7 @@ class SpecialPowersAPIParent extends JSWindowActorParent { observers.forEach(function(observer) { try { observer.observe(subject, topic, data); - } catch (e) { } + } catch (e) {} }); } @@ -335,11 +354,12 @@ class SpecialPowersAPIParent extends JSWindowActorParent { value = pref[1]; } - /* If pref is not found or invalid it doesn't exist. */ if (type !== "INVALID") { - if ((Services.prefs.prefHasUserValue(name) && action == "clear") || - action == "set") { + if ( + (Services.prefs.prefHasUserValue(name) && action == "clear") || + action == "set" + ) { originalValue = this._getPref(name, type); } } else if (action == "set") { @@ -356,10 +376,10 @@ class SpecialPowersAPIParent extends JSWindowActorParent { throw new Error("Unexpected preference type"); } - pendingActions.push({action, type, name, value, iid}); + pendingActions.push({ action, type, name, value, iid }); /* Push original preference value or clear into cleanup array */ - var cleanupTodo = {type, name, value: originalValue, iid}; + var cleanupTodo = { type, name, value: originalValue, iid }; if (originalValue == null) { cleanupTodo.action = "clear"; } else { @@ -432,7 +452,8 @@ class SpecialPowersAPIParent extends JSWindowActorParent { * messageManager callback function * This will get requests from our API in the window and process them in chrome for it **/ - receiveMessage(aMessage) { // eslint-disable-line complexity + receiveMessage(aMessage) { + // eslint-disable-line complexity // We explicitly return values in the below code so that this function // doesn't trigger a flurry of warnings about "does not always return // a value". @@ -452,21 +473,34 @@ class SpecialPowersAPIParent extends JSWindowActorParent { let { prefName, prefValue, iid, defaultValue } = aMessage.json; if (aMessage.json.op == "get") { - if (!prefName || !prefType) - throw new SpecialPowersError("Invalid parameters for get in SPPrefService"); + if (!prefName || !prefType) { + throw new SpecialPowersError( + "Invalid parameters for get in SPPrefService" + ); + } // return null if the pref doesn't exist - if (defaultValue === undefined && prefs.getPrefType(prefName) == prefs.PREF_INVALID) + if ( + defaultValue === undefined && + prefs.getPrefType(prefName) == prefs.PREF_INVALID + ) { return null; + } return this._getPref(prefName, prefType, defaultValue, iid); } else if (aMessage.json.op == "set") { - if (!prefName || !prefType || prefValue === undefined) - throw new SpecialPowersError("Invalid parameters for set in SPPrefService"); + if (!prefName || !prefType || prefValue === undefined) { + throw new SpecialPowersError( + "Invalid parameters for set in SPPrefService" + ); + } return this._setPref(prefName, prefType, prefValue, iid); } else if (aMessage.json.op == "clear") { - if (!prefName) - throw new SpecialPowersError("Invalid parameters for clear in SPPrefService"); + if (!prefName) { + throw new SpecialPowersError( + "Invalid parameters for clear in SPPrefService" + ); + } prefs.clearUserPref(prefName); } else { @@ -487,17 +521,21 @@ class SpecialPowersAPIParent extends JSWindowActorParent { case "delete-crash-dump-files": return this._deleteCrashDumpFiles(aMessage.json.filenames); case "find-crash-dump-files": - return this._findCrashDumpFiles(aMessage.json.crashDumpFilesToIgnore); + return this._findCrashDumpFiles( + aMessage.json.crashDumpFilesToIgnore + ); case "delete-pending-crash-dump-files": return this._deletePendingCrashDumpFiles(); default: - throw new SpecialPowersError("Invalid operation for SPProcessCrashService"); + throw new SpecialPowersError( + "Invalid operation for SPProcessCrashService" + ); } return undefined; // See comment at the beginning of this function. } case "SPProcessCrashManagerWait": { - let promises = aMessage.json.crashIds.map((crashId) => { + let promises = aMessage.json.crashIds.map(crashId => { return Services.crashmanager.ensureCrashIsPresent(crashId); }); return Promise.all(promises); @@ -509,20 +547,33 @@ class SpecialPowersAPIParent extends JSWindowActorParent { switch (msg.op) { case "add": - Services.perms.addFromPrincipal(principal, msg.type, msg.permission, msg.expireType, msg.expireTime); + Services.perms.addFromPrincipal( + principal, + msg.type, + msg.permission, + msg.expireType, + msg.expireTime + ); break; case "remove": Services.perms.removeFromPrincipal(principal, msg.type); break; case "has": - let hasPerm = Services.perms.testPermissionFromPrincipal(principal, msg.type); + let hasPerm = Services.perms.testPermissionFromPrincipal( + principal, + msg.type + ); return hasPerm == Ci.nsIPermissionManager.ALLOW_ACTION; case "test": - let testPerm = Services.perms.testPermissionFromPrincipal(principal, msg.type); + let testPerm = Services.perms.testPermissionFromPrincipal( + principal, + msg.type + ); return testPerm == msg.value; default: throw new SpecialPowersError( - "Invalid operation for SPPermissionManager"); + "Invalid operation for SPPermissionManager" + ); } return undefined; // See comment at the beginning of this function. } @@ -548,7 +599,9 @@ class SpecialPowersAPIParent extends JSWindowActorParent { this._registerObservers._add(topic); break; default: - throw new SpecialPowersError("Invalid operation for SPObserverervice"); + throw new SpecialPowersError( + "Invalid operation for SPObserverervice" + ); } return undefined; // See comment at the beginning of this function. } @@ -561,8 +614,9 @@ class SpecialPowersAPIParent extends JSWindowActorParent { if (aMessage.json.url) { scriptName = aMessage.json.url; } else if (aMessage.json.function) { - scriptName = aMessage.json.function.name - || ""; + scriptName = + aMessage.json.function.name || + ""; } else { throw new SpecialPowersError("SPLoadChromeScript: Invalid script"); } @@ -575,19 +629,25 @@ class SpecialPowersAPIParent extends JSWindowActorParent { data => { this.sendAsyncMessage("Assert", data); }, - aMessage.data); + aMessage.data + ); Object.assign(sb.sandbox, { sendAsyncMessage: (name, message) => { - this.sendAsyncMessage("SPChromeScriptMessage", - { id, name, message }); + this.sendAsyncMessage("SPChromeScriptMessage", { + id, + name, + message, + }); }, addMessageListener: (name, listener) => { this._chromeScriptListeners.push({ id, name, listener }); }, removeMessageListener: (name, listener) => { let index = this._chromeScriptListeners.findIndex(function(obj) { - return obj.id == id && obj.name == name && obj.listener == listener; + return ( + obj.id == id && obj.name == name && obj.listener == listener + ); }); if (index >= 0) { this._chromeScriptListeners.splice(index, 1); @@ -601,9 +661,15 @@ class SpecialPowersAPIParent extends JSWindowActorParent { Cu.evalInSandbox(jsScript, sb.sandbox, "1.8", scriptName, 1); } catch (e) { throw new SpecialPowersError( - "Error while executing chrome script '" + scriptName + "':\n" + - e + "\n" + - e.fileName + ":" + e.lineNumber); + "Error while executing chrome script '" + + scriptName + + "':\n" + + e + + "\n" + + e.fileName + + ":" + + e.lineNumber + ); } return undefined; // See comment at the beginning of this function. } @@ -636,8 +702,9 @@ class SpecialPowersAPIParent extends JSWindowActorParent { let origin = aMessage.data.origin; let flags = aMessage.data.flags; let uri = Services.io.newURI(origin); - let sss = Cc["@mozilla.org/ssservice;1"]. - getService(Ci.nsISiteSecurityService); + let sss = Cc["@mozilla.org/ssservice;1"].getService( + Ci.nsISiteSecurityService + ); sss.removeState(Ci.nsISiteSecurityService.HEADER_HSTS, uri, flags); return undefined; } @@ -651,14 +718,18 @@ class SpecialPowersAPIParent extends JSWindowActorParent { } case "SPCheckServiceWorkers": { - let swm = Cc["@mozilla.org/serviceworkers/manager;1"] - .getService(Ci.nsIServiceWorkerManager); + let swm = Cc["@mozilla.org/serviceworkers/manager;1"].getService( + Ci.nsIServiceWorkerManager + ); let regs = swm.getAllRegistrations(); // XXX This code is shared with specialpowers.js. let workers = new Array(regs.length); for (let i = 0; i < regs.length; ++i) { - let { scope, scriptSpec } = regs.queryElementAt(i, Ci.nsIServiceWorkerRegistrationInfo); + let { scope, scriptSpec } = regs.queryElementAt( + i, + Ci.nsIServiceWorkerRegistrationInfo + ); workers[i] = { scope, scriptSpec }; } return { workers }; @@ -670,12 +741,20 @@ class SpecialPowersAPIParent extends JSWindowActorParent { let extension = ExtensionTestCommon.generate(ext); let resultListener = (...args) => { - this.sendAsyncMessage("SPExtensionMessage", {id, type: "testResult", args}); + this.sendAsyncMessage("SPExtensionMessage", { + id, + type: "testResult", + args, + }); }; let messageListener = (...args) => { args.shift(); - this.sendAsyncMessage("SPExtensionMessage", {id, type: "testMessage", args}); + this.sendAsyncMessage("SPExtensionMessage", { + id, + type: "testMessage", + args, + }); }; // Register pass/fail handlers. @@ -703,38 +782,48 @@ class SpecialPowersAPIParent extends JSWindowActorParent { } // ext is always the "real" Extension object, even when "extension" // is a MockExtension. - this.sendAsyncMessage("SPExtensionMessage", {id, type: "extensionSetId", args: [ext.id, ext.uuid]}); + this.sendAsyncMessage("SPExtensionMessage", { + id, + type: "extensionSetId", + args: [ext.id, ext.uuid], + }); }); // Make sure the extension passes the packaging checks when // they're run on a bare archive rather than a running instance, // as the add-on manager runs them. let extensionData = new ExtensionData(extension.rootURI); - return extensionData.loadManifest().then( - () => { - return extensionData.initAllLocales().then(() => { - if (extensionData.errors.length) { - return Promise.reject("Extension contains packaging errors"); + return extensionData + .loadManifest() + .then( + () => { + return extensionData.initAllLocales().then(() => { + if (extensionData.errors.length) { + return Promise.reject("Extension contains packaging errors"); + } + return undefined; + }); + }, + () => { + // loadManifest() will throw if we're loading an embedded + // extension, so don't worry about locale errors in that + // case. + } + ) + .then(async () => { + // browser tests do not call startup in ExtensionXPCShellUtils or MockExtension, + // in that case we have an ID here and we need to set the override. + if (extension.id) { + await ExtensionTestCommon.setIncognitoOverride(extension); + } + return extension.startup().then( + () => {}, + e => { + dump(`Extension startup failed: ${e}\n${e.stack}`); + throw e; } - return undefined; - }); - }, - () => { - // loadManifest() will throw if we're loading an embedded - // extension, so don't worry about locale errors in that - // case. - } - ).then(async () => { - // browser tests do not call startup in ExtensionXPCShellUtils or MockExtension, - // in that case we have an ID here and we need to set the override. - if (extension.id) { - await ExtensionTestCommon.setIncognitoOverride(extension); - } - return extension.startup().then(() => {}, e => { - dump(`Extension startup failed: ${e}\n${e.stack}`); - throw e; + ); }); - }); } case "SPExtensionMessage": { @@ -754,20 +843,24 @@ class SpecialPowersAPIParent extends JSWindowActorParent { } case "Spawn": { - let {browsingContext, task, args, caller} = aMessage.data; + let { browsingContext, task, args, caller } = aMessage.data; - let spParent = browsingContext.currentWindowGlobal.getActor("SpecialPowers"); + let spParent = browsingContext.currentWindowGlobal.getActor( + "SpecialPowers" + ); let taskId = nextTaskID++; spParent._taskActors.set(taskId, this); - return spParent.sendQuery("Spawn", {task, args, caller, taskId}).finally(() => { - spParent._taskActors.delete(taskId); - }); + return spParent + .sendQuery("Spawn", { task, args, caller, taskId }) + .finally(() => { + spParent._taskActors.delete(taskId); + }); } case "ProxiedAssert": { - let {taskId, data} = aMessage.data; + let { taskId, data } = aMessage.data; let actor = this._taskActors.get(taskId); actor.sendAsyncMessage("Assert", data); @@ -783,7 +876,9 @@ class SpecialPowersAPIParent extends JSWindowActorParent { } default: - throw new SpecialPowersError(`Unrecognized Special Powers API: ${aMessage.name}`); + throw new SpecialPowersError( + `Unrecognized Special Powers API: ${aMessage.name}` + ); } // We throw an exception before reaching this explicit return because diff --git a/testing/specialpowers/content/SpecialPowersChild.jsm b/testing/specialpowers/content/SpecialPowersChild.jsm index f763af1e5b12..79cd94f25785 100644 --- a/testing/specialpowers/content/SpecialPowersChild.jsm +++ b/testing/specialpowers/content/SpecialPowersChild.jsm @@ -5,12 +5,20 @@ * order to be used as a replacement for UniversalXPConnect */ -var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -var EXPORTED_SYMBOLS = ["SpecialPowers", "SpecialPowersChild", "attachSpecialPowersToWindow"]; +var EXPORTED_SYMBOLS = [ + "SpecialPowers", + "SpecialPowersChild", + "attachSpecialPowersToWindow", +]; -const {bindDOMWindowUtils, SpecialPowersAPI} = ChromeUtils.import("resource://specialpowers/SpecialPowersAPI.jsm"); -const {ExtensionUtils} = ChromeUtils.import("resource://gre/modules/ExtensionUtils.jsm"); +const { bindDOMWindowUtils, SpecialPowersAPI } = ChromeUtils.import( + "resource://specialpowers/SpecialPowersAPI.jsm" +); +const { ExtensionUtils } = ChromeUtils.import( + "resource://gre/modules/ExtensionUtils.jsm" +); Cu.forcePermissiveCOWs(); @@ -22,12 +30,14 @@ class SpecialPowersChild extends SpecialPowersAPI { this.DOMWindowUtils = null; this._encounteredCrashDumpFiles = []; - this._unexpectedCrashDumpFiles = { }; + this._unexpectedCrashDumpFiles = {}; this._crashDumpDir = null; this._serviceWorkerRegistered = false; this._serviceWorkerCleanUpRequests = new Map(); Object.defineProperty(this, "Components", { - configurable: true, enumerable: true, value: this.getFullComponents(), + configurable: true, + enumerable: true, + value: this.getFullComponents(), }); this._createFilesOnError = null; this._createFilesOnSuccess = null; @@ -56,8 +66,12 @@ class SpecialPowersChild extends SpecialPowersAPI { return this.contentWindow; } - toString() { return "[SpecialPowers]"; } - sanityCheck() { return "foo"; } + toString() { + return "[SpecialPowers]"; + } + sanityCheck() { + return "foo"; + } _addMessageListener(msgname, listener) { this._messageListeners.get(msgname).add(listener); @@ -72,7 +86,9 @@ class SpecialPowersChild extends SpecialPowersAPI { } unregisterProcessCrashObservers() { - this.sendAsyncMessage("SPProcessCrashService", { op: "unregister-observer" }); + this.sendAsyncMessage("SPProcessCrashService", { + op: "unregister-observer", + }); } receiveMessage(aMessage) { @@ -122,7 +138,7 @@ class SpecialPowersChild extends SpecialPowersAPI { break; case "Spawn": - let {task, args, caller, taskId} = aMessage.data; + let { task, args, caller, taskId } = aMessage.data; return this._spawnTask(task, args, caller, taskId); default: @@ -141,7 +157,10 @@ class SpecialPowersChild extends SpecialPowersAPI { // file to be created in the profile directory. If the request has a |data| field // then that data will be written to the file. createFiles(fileRequests, onCreation, onError) { - return this.sendQuery("SpecialPowers.CreateFiles", fileRequests).then(onCreation, onError); + return this.sendQuery("SpecialPowers.CreateFiles", fileRequests).then( + onCreation, + onError + ); } // Remove the files that were created using |SpecialPowers.createFiles()|. @@ -158,15 +177,21 @@ class SpecialPowersChild extends SpecialPowersAPI { // For the time being, if parent_intercept is false, we can assume that // ServiceWorkers registered by the current test are all known to the SWM in // this process. - if (!Services.prefs.getBoolPref("dom.serviceWorkers.parent_intercept", false)) { - let swm = Cc["@mozilla.org/serviceworkers/manager;1"] - .getService(Ci.nsIServiceWorkerManager); + if ( + !Services.prefs.getBoolPref("dom.serviceWorkers.parent_intercept", false) + ) { + let swm = Cc["@mozilla.org/serviceworkers/manager;1"].getService( + Ci.nsIServiceWorkerManager + ); let regs = swm.getAllRegistrations(); // XXX This is shared with SpecialPowersAPIParent.jsm let workers = new Array(regs.length); for (let i = 0; i < workers.length; ++i) { - let { scope, scriptSpec } = regs.queryElementAt(i, Ci.nsIServiceWorkerRegistrationInfo); + let { scope, scriptSpec } = regs.queryElementAt( + i, + Ci.nsIServiceWorkerRegistrationInfo + ); workers[i] = { scope, scriptSpec }; } diff --git a/testing/specialpowers/content/SpecialPowersParent.jsm b/testing/specialpowers/content/SpecialPowersParent.jsm index 898e6e8f4266..b95b6e65d2ea 100644 --- a/testing/specialpowers/content/SpecialPowersParent.jsm +++ b/testing/specialpowers/content/SpecialPowersParent.jsm @@ -11,9 +11,11 @@ var EXPORTED_SYMBOLS = ["SpecialPowersParent"]; -var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {SpecialPowersAPIParent} = ChromeUtils.import("resource://specialpowers/SpecialPowersAPIParent.jsm"); +const { SpecialPowersAPIParent } = ChromeUtils.import( + "resource://specialpowers/SpecialPowersAPIParent.jsm" +); class SpecialPowersParent extends SpecialPowersAPIParent { constructor() { @@ -82,8 +84,9 @@ class SpecialPowersParent extends SpecialPowersAPIParent { // difficult. For the time being, let the child process know when a test // registers a service worker so it can ask, synchronously, at the end if // the service worker had unregister called on it. - let swm = Cc["@mozilla.org/serviceworkers/manager;1"] - .getService(Ci.nsIServiceWorkerManager); + let swm = Cc["@mozilla.org/serviceworkers/manager;1"].getService( + Ci.nsIServiceWorkerManager + ); let self = this; this._serviceWorkerListener = { onRegister() { @@ -100,13 +103,14 @@ class SpecialPowersParent extends SpecialPowersAPIParent { uninit() { var obs = Services.obs; obs.removeObserver(this._observer, "http-on-modify-request"); - this._registerObservers._topics.splice(0).forEach((element) => { + this._registerObservers._topics.splice(0).forEach(element => { obs.removeObserver(this._registerObservers, element); }); this._removeProcessCrashObservers(); - let swm = Cc["@mozilla.org/serviceworkers/manager;1"] - .getService(Ci.nsIServiceWorkerManager); + let swm = Cc["@mozilla.org/serviceworkers/manager;1"].getService( + Ci.nsIServiceWorkerManager + ); swm.removeListener(this._serviceWorkerListener); } @@ -161,16 +165,26 @@ class SpecialPowersParent extends SpecialPowersAPIParent { } else { testFile.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, filePerms); } - let outStream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream); - outStream.init(testFile, 0x02 | 0x08 | 0x20, // PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE - filePerms, 0); + let outStream = Cc[ + "@mozilla.org/network/file-output-stream;1" + ].createInstance(Ci.nsIFileOutputStream); + outStream.init( + testFile, + 0x02 | 0x08 | 0x20, // PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE + filePerms, + 0 + ); if (request.data) { outStream.write(request.data, request.data.length); } outStream.close(); - promises.push(File.createFromFileName(testFile.path, request.options).then(function(file) { - filePaths.push(file); - })); + promises.push( + File.createFromFileName(testFile.path, request.options).then( + function(file) { + filePaths.push(file); + } + ) + ); createdFiles.push(testFile); }); @@ -202,7 +216,6 @@ class SpecialPowersParent extends SpecialPowersAPIParent { } onRegister() { - this.sendAsyncMessage("SPServiceWorkerRegistered", - { registered: true }); + this.sendAsyncMessage("SPServiceWorkerRegistered", { registered: true }); } } diff --git a/testing/specialpowers/content/SpecialPowersSandbox.jsm b/testing/specialpowers/content/SpecialPowersSandbox.jsm index 73225511780e..9b1cd35abc05 100644 --- a/testing/specialpowers/content/SpecialPowersSandbox.jsm +++ b/testing/specialpowers/content/SpecialPowersSandbox.jsm @@ -12,8 +12,11 @@ var EXPORTED_SYMBOLS = ["SpecialPowersSandbox"]; -ChromeUtils.defineModuleGetter(this, "Assert", - "resource://testing-common/Assert.jsm"); +ChromeUtils.defineModuleGetter( + this, + "Assert", + "resource://testing-common/Assert.jsm" +); class SpecialPowersSandbox { constructor(name, reportCallback, opts = {}) { @@ -22,9 +25,13 @@ class SpecialPowersSandbox { this._Assert = null; - this.sandbox = Cu.Sandbox(Cu.getGlobalForObject({}), - Object.assign({wantGlobalProperties: ["ChromeUtils"]}, - opts.sandboxOptions)); + this.sandbox = Cu.Sandbox( + Cu.getGlobalForObject({}), + Object.assign( + { wantGlobalProperties: ["ChromeUtils"] }, + opts.sandboxOptions + ) + ); for (let prop of ["assert", "Assert"]) { Object.defineProperty(this.sandbox, prop, { @@ -56,16 +63,22 @@ class SpecialPowersSandbox { report(err, name, stack) { let diag; if (err) { - diag = `got ${uneval(err.actual)}, expected ${uneval(err.expected)} ` + - `(operator ${err.operator})`; + diag = + `got ${uneval(err.actual)}, expected ${uneval(err.expected)} ` + + `(operator ${err.operator})`; } - this.reportCallback({name, diag, passed: !err, stack}); + this.reportCallback({ name, diag, passed: !err, stack }); } execute(task, args, caller) { - let func = Cu.evalInSandbox(`(${task})`, this.sandbox, undefined, - caller.filename, caller.lineNumber); + let func = Cu.evalInSandbox( + `(${task})`, + this.sandbox, + undefined, + caller.filename, + caller.lineNumber + ); return func(...args); } } diff --git a/testing/specialpowers/content/WrapPrivileged.jsm b/testing/specialpowers/content/WrapPrivileged.jsm index 8f5e02a16788..1d95adabd408 100644 --- a/testing/specialpowers/content/WrapPrivileged.jsm +++ b/testing/specialpowers/content/WrapPrivileged.jsm @@ -32,8 +32,9 @@ Cu.forcePermissiveCOWs(); var EXPORTED_SYMBOLS = ["WrapPrivileged"]; function isWrappable(x) { - if (typeof x === "object") + if (typeof x === "object") { return x !== null; + } return typeof x === "function"; } @@ -50,12 +51,22 @@ function wrapIfUnwrapped(x) { } function isObjectOrArray(obj) { - if (Object(obj) !== obj) + if (Object(obj) !== obj) { return false; - let arrayClasses = ["Object", "Array", "Int8Array", "Uint8Array", - "Int16Array", "Uint16Array", "Int32Array", - "Uint32Array", "Float32Array", "Float64Array", - "Uint8ClampedArray"]; + } + let arrayClasses = [ + "Object", + "Array", + "Int8Array", + "Uint8Array", + "Int16Array", + "Uint16Array", + "Int32Array", + "Uint32Array", + "Float32Array", + "Float64Array", + "Uint8ClampedArray", + ]; let className = Cu.getClassName(obj, true); return arrayClasses.includes(className); } @@ -80,10 +91,13 @@ function isObjectOrArray(obj) { // XrayWrapper for security reasons. For test code, we generally want to see // through that sort of thing. function waiveXraysIfAppropriate(obj, propName) { - if (propName == "toString" || isObjectOrArray(obj) || - /Opaque/.test(Object.prototype.toString.call(obj))) { + if ( + propName == "toString" || + isObjectOrArray(obj) || + /Opaque/.test(Object.prototype.toString.call(obj)) + ) { return XPCNativeWrapper.unwrap(obj); -} + } return obj; } @@ -101,24 +115,27 @@ function doApply(fun, invocant, args) { // clamping for Xrayed DOM objects reached from literals, so passing things // like {l : xoWin.location} won't work. Hopefully the rabbit hole doesn't // go that deep. - args = args.map(x => isObjectOrArray(x) ? Cu.waiveXrays(x) : x); + args = args.map(x => (isObjectOrArray(x) ? Cu.waiveXrays(x) : x)); return Reflect.apply(fun, invocant, args); } function wrapPrivileged(obj) { // Primitives pass straight through. - if (!isWrappable(obj)) + if (!isWrappable(obj)) { return obj; + } // No double wrapping. - if (isWrapper(obj)) + if (isWrapper(obj)) { throw new Error("Trying to double-wrap object!"); + } let dummy; - if (typeof obj === "function") + if (typeof obj === "function") { dummy = function() {}; - else + } else { dummy = Object.create(null); + } return new Proxy(dummy, new SpecialPowersHandler(obj)); } @@ -128,12 +145,14 @@ function unwrapPrivileged(x) { // expect to have a wrapper. The proxy pretends to be the type that it's // emulating, so we can just as easily check isWrappable() on a proxy as // we can on an unwrapped object. - if (!isWrappable(x)) + if (!isWrappable(x)) { return x; + } // If we have a wrappable type, make sure it's wrapped. - if (!isWrapper(x)) + if (!isWrapper(x)) { throw new Error("Trying to unwrap a non-wrapped object!"); + } var obj = x.SpecialPowers_wrappedObject; // unwrapped. @@ -159,7 +178,9 @@ SpecialPowersHandler.prototype = { // We want to invoke "obj" as a constructor, but using unwrappedArgs as // the arguments. Make sure to wrap and re-throw exceptions! try { - return wrapIfUnwrapped(Reflect.construct(this.wrappedObject, unwrappedArgs)); + return wrapIfUnwrapped( + Reflect.construct(this.wrappedObject, unwrappedArgs) + ); } catch (e) { throw wrapIfUnwrapped(e); } @@ -172,7 +193,9 @@ SpecialPowersHandler.prototype = { var unwrappedArgs = Array.prototype.slice.call(args).map(unwrapIfWrapped); try { - return wrapIfUnwrapped(doApply(this.wrappedObject, invocant, unwrappedArgs)); + return wrapIfUnwrapped( + doApply(this.wrappedObject, invocant, unwrappedArgs) + ); } catch (e) { // Wrap exceptions and re-throw them. throw wrapIfUnwrapped(e); @@ -180,15 +203,17 @@ SpecialPowersHandler.prototype = { }, has(target, prop) { - if (prop === "SpecialPowers_wrappedObject") + if (prop === "SpecialPowers_wrappedObject") { return true; + } return Reflect.has(this.wrappedObject, prop); }, get(target, prop, receiver) { - if (prop === "SpecialPowers_wrappedObject") + if (prop === "SpecialPowers_wrappedObject") { return this.wrappedObject; + } let obj = waiveXraysIfAppropriate(this.wrappedObject, prop); let val = Reflect.get(obj, prop); @@ -204,29 +229,37 @@ SpecialPowersHandler.prototype = { }, set(target, prop, val, receiver) { - if (prop === "SpecialPowers_wrappedObject") + if (prop === "SpecialPowers_wrappedObject") { return false; + } let obj = waiveXraysIfAppropriate(this.wrappedObject, prop); return Reflect.set(obj, prop, unwrapIfWrapped(val)); }, delete(target, prop) { - if (prop === "SpecialPowers_wrappedObject") + if (prop === "SpecialPowers_wrappedObject") { return false; + } return Reflect.deleteProperty(this.wrappedObject, prop); }, defineProperty(target, prop, descriptor) { - throw new Error("Can't call defineProperty on SpecialPowers wrapped object"); + throw new Error( + "Can't call defineProperty on SpecialPowers wrapped object" + ); }, getOwnPropertyDescriptor(target, prop) { // Handle our special API. if (prop === "SpecialPowers_wrappedObject") { - return { value: this.wrappedObject, writeable: true, - configurable: true, enumerable: false }; + return { + value: this.wrappedObject, + writeable: true, + configurable: true, + enumerable: false, + }; } let obj = waiveXraysIfAppropriate(this.wrappedObject, prop); @@ -239,8 +272,12 @@ SpecialPowersHandler.prototype = { // Symbol.hasInstance already. Once we get rid of JS engine class // instance hooks (bug 1448218) and always use Symbol.hasInstance, we // can remove this bit (bug 1448400). - return { value: wrapPrivileged(specialPowersHasInstance), - writeable: true, configurable: true, enumerable: false }; + return { + value: wrapPrivileged(specialPowersHasInstance), + writeable: true, + configurable: true, + enumerable: false, + }; } return undefined; @@ -248,8 +285,9 @@ SpecialPowersHandler.prototype = { // Transitively maintain the wrapper membrane. function wrapIfExists(key) { - if (key in desc) + if (key in desc) { desc[key] = wrapIfUnwrapped(desc[key]); + } } wrapIfExists("value"); @@ -269,20 +307,23 @@ SpecialPowersHandler.prototype = { let props = ["SpecialPowers_wrappedObject"]; // Do the normal thing. - let flt = (a) => !props.includes(a); + let flt = a => !props.includes(a); props = props.concat(Reflect.ownKeys(this.wrappedObject).filter(flt)); // If we've got an Xray wrapper, include the expandos as well. if ("wrappedJSObject" in this.wrappedObject) { - props = props.concat(Reflect.ownKeys(this.wrappedObject.wrappedJSObject) - .filter(flt)); + props = props.concat( + Reflect.ownKeys(this.wrappedObject.wrappedJSObject).filter(flt) + ); } return props; }, preventExtensions(target) { - throw new Error("Can't call preventExtensions on SpecialPowers wrapped object"); + throw new Error( + "Can't call preventExtensions on SpecialPowers wrapped object" + ); }, }; @@ -297,15 +338,15 @@ function wrapCallbackObject(obj) { obj = Cu.waiveXrays(obj); var wrapper = {}; for (var i in obj) { - if (typeof obj[i] == "function") + if (typeof obj[i] == "function") { wrapper[i] = wrapCallback(obj[i]); - else + } else { wrapper[i] = obj[i]; + } } return wrapper; } - var WrapPrivileged = { wrap: wrapIfUnwrapped, unwrap: unwrapIfWrapped, diff --git a/testing/talos/talos/bootstrap.js b/testing/talos/talos/bootstrap.js index 366bc79960f4..86a663099bd2 100644 --- a/testing/talos/talos/bootstrap.js +++ b/testing/talos/talos/bootstrap.js @@ -11,9 +11,11 @@ // Reads the chrome.manifest from a legacy non-restartless extension and loads // its overlays into the appropriate top-level windows. -const {AppConstants} = ChromeUtils.import("resource://gre/modules/AppConstants.jsm"); -const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { AppConstants } = ChromeUtils.import( + "resource://gre/modules/AppConstants.jsm" +); +const { NetUtil } = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const windowTracker = { init() { @@ -23,10 +25,11 @@ const windowTracker = { async observe(window, topic, data) { if (topic === "domwindowopened") { await new Promise(resolve => - window.addEventListener("DOMWindowCreated", resolve, {once: true})); + window.addEventListener("DOMWindowCreated", resolve, { once: true }) + ); - let {document} = window; - let {documentURI} = document; + let { document } = window; + let { documentURI } = document; if (documentURI !== AppConstants.BROWSER_CHROME_URL) { return; @@ -37,13 +40,15 @@ const windowTracker = { }; function readSync(uri) { - let channel = NetUtil.newChannel({uri, loadUsingSystemPrincipal: true}); + let channel = NetUtil.newChannel({ uri, loadUsingSystemPrincipal: true }); let buffer = NetUtil.readInputStream(channel.open()); return new TextDecoder().decode(buffer); } function startup(data, reason) { - Services.scriptloader.loadSubScript(data.resourceURI.resolve("content/initialize_browser.js")); + Services.scriptloader.loadSubScript( + data.resourceURI.resolve("content/initialize_browser.js") + ); windowTracker.init(); } diff --git a/testing/talos/talos/pageloader/api.js b/testing/talos/talos/pageloader/api.js index 54c87ecdc243..d440f2a2928d 100644 --- a/testing/talos/talos/pageloader/api.js +++ b/testing/talos/talos/pageloader/api.js @@ -37,18 +37,28 @@ * * ***** END LICENSE BLOCK ***** */ -const {AppConstants} = ChromeUtils.import("resource://gre/modules/AppConstants.jsm"); -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); -const {setTimeout} = ChromeUtils.import("resource://gre/modules/Timer.jsm"); +const { AppConstants } = ChromeUtils.import( + "resource://gre/modules/AppConstants.jsm" +); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); +const { setTimeout } = ChromeUtils.import("resource://gre/modules/Timer.jsm"); -XPCOMUtils.defineLazyServiceGetter(this, "aomStartup", - "@mozilla.org/addons/addon-manager-startup;1", - "amIAddonManagerStartup"); +XPCOMUtils.defineLazyServiceGetter( + this, + "aomStartup", + "@mozilla.org/addons/addon-manager-startup;1", + "amIAddonManagerStartup" +); -XPCOMUtils.defineLazyServiceGetter(this, "env", - "@mozilla.org/process/environment;1", - "nsIEnvironment"); +XPCOMUtils.defineLazyServiceGetter( + this, + "env", + "@mozilla.org/process/environment;1", + "nsIEnvironment" +); async function talosStart() { // Tests are driven from pageloader.xul. We need to be careful to open @@ -60,7 +70,10 @@ async function talosStart() { defaultWin = await new Promise(resolve => { const listener = { onOpenWindow(win) { - if (win.docShell.domWindow.location.href == AppConstants.BROWSER_CHROME_URL) { + if ( + win.docShell.domWindow.location.href == + AppConstants.BROWSER_CHROME_URL + ) { Services.wm.removeListener(listener); resolve(win); } @@ -76,8 +89,13 @@ async function talosStart() { let args = {}; args.wrappedJSObject = args; - let newWin = Services.ww.openWindow(null, chromeURL, "_blank", - "chrome,dialog=no,all", args); + let newWin = Services.ww.openWindow( + null, + chromeURL, + "_blank", + "chrome,dialog=no,all", + args + ); await new Promise(resolve => { newWin.addEventListener("load", resolve); @@ -88,7 +106,11 @@ async function talosStart() { /* globals ExtensionAPI */ this.pageloader = class extends ExtensionAPI { onStartup() { - const manifestURI = Services.io.newURI("manifest.json", null, this.extension.rootURI); + const manifestURI = Services.io.newURI( + "manifest.json", + null, + this.extension.rootURI + ); this.chromeHandle = aomStartup.registerChrome(manifestURI, [ ["content", "pageloader", "chrome/"], ]); diff --git a/testing/talos/talos/pageloader/chrome/MozillaFileLogger.js b/testing/talos/talos/pageloader/chrome/MozillaFileLogger.js index 63f752b5884f..9ff3644bec45 100644 --- a/testing/talos/talos/pageloader/chrome/MozillaFileLogger.js +++ b/testing/talos/talos/pageloader/chrome/MozillaFileLogger.js @@ -2,7 +2,7 @@ * MozillaFileLogger, a log listener that can write to a local file. */ -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); // double logging to account for normal mode and ipc mode (mobile_profile only) // Ideally we would remove the dump() and just do ipc logging @@ -16,46 +16,52 @@ const LF_CID = "@mozilla.org/file/local;1"; // File status flags. It is a bitwise OR of the following bit flags. // Only one of the first three flags below may be used. -const PR_READ_ONLY = 0x01; // Open for reading only. -const PR_WRITE_ONLY = 0x02; // Open for writing only. -const PR_READ_WRITE = 0x04; // Open for reading and writing. +const PR_READ_ONLY = 0x01; // Open for reading only. +const PR_WRITE_ONLY = 0x02; // Open for writing only. +const PR_READ_WRITE = 0x04; // Open for reading and writing. // If the file does not exist, the file is created. // If the file exists, this flag has no effect. -const PR_CREATE_FILE = 0x08; +const PR_CREATE_FILE = 0x08; // The file pointer is set to the end of the file prior to each write. -const PR_APPEND = 0x10; +const PR_APPEND = 0x10; // If the file exists, its length is truncated to 0. -const PR_TRUNCATE = 0x20; +const PR_TRUNCATE = 0x20; // If set, each write will wait for both the file data // and file status to be physically updated. -const PR_SYNC = 0x40; +const PR_SYNC = 0x40; // If the file does not exist, the file is created. If the file already // exists, no action and NULL is returned. -const PR_EXCL = 0x80; +const PR_EXCL = 0x80; /** Init the file logger with the absolute path to the file. It will create and append if the file already exists **/ var MozillaFileLogger = {}; - MozillaFileLogger.init = function(path) { MozillaFileLogger._file = Cc[LF_CID].createInstance(Ci.nsIFile); MozillaFileLogger._file.initWithPath(path); - MozillaFileLogger._foStream = Cc[FOSTREAM_CID].createInstance(Ci.nsIFileOutputStream); - MozillaFileLogger._foStream.init(this._file, PR_WRITE_ONLY | PR_CREATE_FILE | PR_APPEND, - 0o664, 0); + MozillaFileLogger._foStream = Cc[FOSTREAM_CID].createInstance( + Ci.nsIFileOutputStream + ); + MozillaFileLogger._foStream.init( + this._file, + PR_WRITE_ONLY | PR_CREATE_FILE | PR_APPEND, + 0o664, + 0 + ); }; MozillaFileLogger.getLogCallback = function() { return function(msg) { var data = msg.num + " " + msg.level + " " + msg.info.join(" ") + "\n"; - if (MozillaFileLogger._foStream) + if (MozillaFileLogger._foStream) { MozillaFileLogger._foStream.write(data, data.length); + } if (data.includes("SimpleTest FINISH")) { MozillaFileLogger.close(); @@ -66,14 +72,16 @@ MozillaFileLogger.getLogCallback = function() { // This is only used from chrome space by the reftest harness MozillaFileLogger.log = function(msg) { try { - if (MozillaFileLogger._foStream) + if (MozillaFileLogger._foStream) { MozillaFileLogger._foStream.write(msg, msg.length); + } } catch (ex) {} }; MozillaFileLogger.close = function() { - if (MozillaFileLogger._foStream) + if (MozillaFileLogger._foStream) { MozillaFileLogger._foStream.close(); + } MozillaFileLogger._foStream = null; MozillaFileLogger._file = null; diff --git a/testing/talos/talos/pageloader/chrome/Profiler.js b/testing/talos/talos/pageloader/chrome/Profiler.js index 8f0df3f1031d..29225f37da4f 100644 --- a/testing/talos/talos/pageloader/chrome/Profiler.js +++ b/testing/talos/talos/pageloader/chrome/Profiler.js @@ -46,7 +46,9 @@ var Profiler; try { // eslint-disable-next-line mozilla/use-services _profiler = Cc["@mozilla.org/tools/profiler;1"].getService(Ci.nsIProfiler); - } catch (ex) { (typeof(dumpLog) == "undefined" ? dump : dumpLog)(ex + "\n"); } + } catch (ex) { + (typeof dumpLog == "undefined" ? dump : dumpLog)(ex + "\n"); + } // Parses an url query string into a JS object. function searchToObject(locationSearch) { @@ -73,11 +75,17 @@ var Profiler; * - gecko_profile_dir */ initFromObject: function Profiler__initFromObject(obj) { - if (obj && - ("gecko_profile_dir" in obj) && typeof obj.gecko_profile_dir == "string" && - ("gecko_profile_interval" in obj) && Number.isFinite(obj.gecko_profile_interval * 1) && - ("gecko_profile_entries" in obj) && Number.isFinite(obj.gecko_profile_entries * 1) && - ("gecko_profile_threads" in obj) && typeof obj.gecko_profile_threads == "string") { + if ( + obj && + "gecko_profile_dir" in obj && + typeof obj.gecko_profile_dir == "string" && + "gecko_profile_interval" in obj && + Number.isFinite(obj.gecko_profile_interval * 1) && + "gecko_profile_entries" in obj && + Number.isFinite(obj.gecko_profile_entries * 1) && + "gecko_profile_threads" in obj && + typeof obj.gecko_profile_threads == "string" + ) { profiler_interval = obj.gecko_profile_interval; profiler_entries = obj.gecko_profile_entries; profiler_threadsArray = obj.gecko_profile_threads.split(","); @@ -85,15 +93,20 @@ var Profiler; enabled = true; } }, - initFromURLQueryParams: function Profiler__initFromURLQueryParams(locationSearch) { + initFromURLQueryParams: function Profiler__initFromURLQueryParams( + locationSearch + ) { this.initFromObject(searchToObject(locationSearch)); }, beginTest: function Profiler__beginTest(testName) { currentTest = testName; if (_profiler && enabled) { - _profiler.StartProfiler(profiler_entries, profiler_interval, - ["js", "leaf", "stackwalk", "threads"], - profiler_threadsArray); + _profiler.StartProfiler( + profiler_entries, + profiler_interval, + ["js", "leaf", "stackwalk", "threads"], + profiler_threadsArray + ); if (_profiler.PauseSampling) { _profiler.PauseSampling(); } @@ -101,7 +114,9 @@ var Profiler; }, finishTest: function Profiler__finishTest() { if (_profiler && enabled) { - _profiler.dumpProfileToFile(profiler_dir + "/" + currentTest + ".profile"); + _profiler.dumpProfileToFile( + profiler_dir + "/" + currentTest + ".profile" + ); _profiler.StopProfiler(); } }, @@ -110,36 +125,45 @@ var Profiler; return undefined; } return new Promise((resolve, reject) => { - Services.profiler.getProfileDataAsync().then((profile) => { - let profileFile = profiler_dir + "/" + currentTest + ".profile"; + Services.profiler.getProfileDataAsync().then( + profile => { + let profileFile = profiler_dir + "/" + currentTest + ".profile"; - const {NetUtil} = Cu.import("resource://gre/modules/NetUtil.jsm"); - const {FileUtils} = Cu.import("resource://gre/modules/FileUtils.jsm"); + const { NetUtil } = Cu.import("resource://gre/modules/NetUtil.jsm"); + const { FileUtils } = Cu.import( + "resource://gre/modules/FileUtils.jsm" + ); - var file = Cc["@mozilla.org/file/local;1"]. - createInstance(Ci.nsIFile); - file.initWithPath(profileFile); + var file = Cc["@mozilla.org/file/local;1"].createInstance( + Ci.nsIFile + ); + file.initWithPath(profileFile); - var ostream = FileUtils.openSafeFileOutputStream(file); + var ostream = FileUtils.openSafeFileOutputStream(file); - var converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]. - createInstance(Ci.nsIScriptableUnicodeConverter); - converter.charset = "UTF-8"; - var istream = converter.convertToInputStream(JSON.stringify(profile)); + var converter = Cc[ + "@mozilla.org/intl/scriptableunicodeconverter" + ].createInstance(Ci.nsIScriptableUnicodeConverter); + converter.charset = "UTF-8"; + var istream = converter.convertToInputStream( + JSON.stringify(profile) + ); - // The last argument (the callback) is optional. - NetUtil.asyncCopy(istream, ostream, function(status) { - if (!Components.isSuccessCode(status)) { - reject(); - return; - } + // The last argument (the callback) is optional. + NetUtil.asyncCopy(istream, ostream, function(status) { + if (!Components.isSuccessCode(status)) { + reject(); + return; + } - resolve(); - }); - }, (error) => { - Cu.reportError("Failed to gather profile: " + error); - reject(); - }); + resolve(); + }); + }, + error => { + Cu.reportError("Failed to gather profile: " + error); + reject(); + } + ); }); }, finishStartupProfiling: function Profiler__finishStartupProfiling() { @@ -153,7 +177,9 @@ var Profiler; if (_profiler.ResumeSampling) { _profiler.ResumeSampling(); } - _profiler.AddMarker(explicit ? name : 'Start of test "' + (name || test_name) + '"'); + _profiler.AddMarker( + explicit ? name : 'Start of test "' + (name || test_name) + '"' + ); } }, pause: function Profiler__pause(name, explicit) { @@ -161,12 +187,16 @@ var Profiler; if (_profiler.PauseSampling) { _profiler.PauseSampling(); } - _profiler.AddMarker(explicit ? name : 'End of test "' + (name || test_name) + '"'); + _profiler.AddMarker( + explicit ? name : 'End of test "' + (name || test_name) + '"' + ); } }, mark: function Profiler__mark(marker, explicit) { if (_profiler) { - _profiler.AddMarker(explicit ? marker : 'Profiler: "' + (marker || test_name) + '"'); + _profiler.AddMarker( + explicit ? marker : 'Profiler: "' + (marker || test_name) + '"' + ); } }, }; diff --git a/testing/talos/talos/pageloader/chrome/lh_fnbpaint.js b/testing/talos/talos/pageloader/chrome/lh_fnbpaint.js index a74b1d92352a..7e17119f8b19 100644 --- a/testing/talos/talos/pageloader/chrome/lh_fnbpaint.js +++ b/testing/talos/talos/pageloader/chrome/lh_fnbpaint.js @@ -1,29 +1,41 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var gErr = "Abort: firstNonBlankPaint value is not available after loading the page"; +var gErr = + "Abort: firstNonBlankPaint value is not available after loading the page"; var gRetryCounter = 0; function _contentFNBPaintHandler() { var x = content.window.performance.timing.timeToNonBlankPaint; if (typeof x == "undefined") { - sendAsyncMessage("PageLoader:Error", {"msg": gErr}); + sendAsyncMessage("PageLoader:Error", { msg: gErr }); } if (x > 0) { dump("received fnbpaint value\n"); - sendAsyncMessage("PageLoader:LoadEvent", {"time": x, - "name": "fnbpaint"}); + sendAsyncMessage("PageLoader:LoadEvent", { time: x, name: "fnbpaint" }); gRetryCounter = 0; } else { gRetryCounter += 1; if (gRetryCounter <= 10) { - dump("\nfnbpaint is not yet available (0), retry number " + gRetryCounter + "...\n"); + dump( + "\nfnbpaint is not yet available (0), retry number " + + gRetryCounter + + "...\n" + ); content.setTimeout(_contentFNBPaintHandler, 100); } else { - dump("\nunable to get a value for fnbpaint after " + gRetryCounter + " retries\n"); - sendAsyncMessage("PageLoader:Error", {"msg": gErr}); + dump( + "\nunable to get a value for fnbpaint after " + + gRetryCounter + + " retries\n" + ); + sendAsyncMessage("PageLoader:Error", { msg: gErr }); } } } -addEventListener("load", contentLoadHandlerCallback(_contentFNBPaintHandler), true); // eslint-disable-line no-undef +addEventListener( + "load", + contentLoadHandlerCallback(_contentFNBPaintHandler), + true +); // eslint-disable-line no-undef diff --git a/testing/talos/talos/pageloader/chrome/lh_hero.js b/testing/talos/talos/pageloader/chrome/lh_hero.js index cdfc856e3040..7ec20bed7844 100644 --- a/testing/talos/talos/pageloader/chrome/lh_hero.js +++ b/testing/talos/talos/pageloader/chrome/lh_hero.js @@ -2,33 +2,35 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - function _contentHeroHandler(isload) { var obs = null; var el = content.window.document.querySelector("[elementtiming]"); if (el) { function callback(entries, observer) { entries.forEach(entry => { - sendAsyncMessage("PageLoader:LoadEvent", - {"time": Date.now(), // eslint-disable-line - "name": "tphero"}); + sendAsyncMessage("PageLoader:LoadEvent", { + time: Date.now(), // eslint-disable-line + name: "tphero", + }); obs.disconnect(); }); } // we want the element 100% visible on the viewport - var options = {root: null, rootMargin: "0px", threshold: [1]}; + var options = { root: null, rootMargin: "0px", threshold: [1] }; try { obs = new content.window.IntersectionObserver(callback, options); obs.observe(el); } catch (err) { - sendAsyncMessage("PageLoader:Error", {"msg": err.message}); + sendAsyncMessage("PageLoader:Error", { msg: err.message }); } } else if (isload) { // If the hero element is added from a settimeout handler, it might not run before 'load' - setTimeout(function() { _contentHeroHandler(false); }, 5000); + setTimeout(function() { + _contentHeroHandler(false); + }, 5000); } else { var err = "Could not find a tag with an elmenttiming attr on the page"; - sendAsyncMessage("PageLoader:Error", {"msg": err}); + sendAsyncMessage("PageLoader:Error", { msg: err }); } return obs; } @@ -37,4 +39,8 @@ function _contentHeroLoadHandler() { _contentHeroHandler(true); } -addEventListener("load", contentLoadHandlerCallback(_contentHeroLoadHandler), true); // eslint-disable-line no-undef +addEventListener( + "load", + contentLoadHandlerCallback(_contentHeroLoadHandler), + true +); // eslint-disable-line no-undef diff --git a/testing/talos/talos/pageloader/chrome/lh_moz.js b/testing/talos/talos/pageloader/chrome/lh_moz.js index 80f6ef627f2c..ad281eebf1c0 100644 --- a/testing/talos/talos/pageloader/chrome/lh_moz.js +++ b/testing/talos/talos/pageloader/chrome/lh_moz.js @@ -4,14 +4,21 @@ function _contentPaintHandler() { var utils = content.windowUtils; if (utils.isMozAfterPaintPending) { - addEventListener("MozAfterPaint", function afterpaint(e) { - removeEventListener("MozAfterPaint", afterpaint, true); - sendAsyncMessage("PageLoader:LoadEvent", {}); - }, true); + addEventListener( + "MozAfterPaint", + function afterpaint(e) { + removeEventListener("MozAfterPaint", afterpaint, true); + sendAsyncMessage("PageLoader:LoadEvent", {}); + }, + true + ); } else { sendAsyncMessage("PageLoader:LoadEvent", {}); } } - -addEventListener("load", contentLoadHandlerCallback(_contentPaintHandler), true); // eslint-disable-line no-undef +addEventListener( + "load", + contentLoadHandlerCallback(_contentPaintHandler), + true +); // eslint-disable-line no-undef diff --git a/testing/talos/talos/pageloader/chrome/pageloader.js b/testing/talos/talos/pageloader/chrome/pageloader.js index d9be94dc3593..06c72df7d3f7 100644 --- a/testing/talos/talos/pageloader/chrome/pageloader.js +++ b/testing/talos/talos/pageloader/chrome/pageloader.js @@ -5,10 +5,15 @@ /* import-globals-from report.js */ /* eslint mozilla/avoid-Date-timing: "off" */ -var {AppConstants} = ChromeUtils.import("resource://gre/modules/AppConstants.jsm"); -var {E10SUtils} = ChromeUtils.import("resource://gre/modules/E10SUtils.jsm"); -ChromeUtils.defineModuleGetter(this, "TalosParentProfiler", - "resource://talos-powers/TalosParentProfiler.jsm"); +var { AppConstants } = ChromeUtils.import( + "resource://gre/modules/AppConstants.jsm" +); +var { E10SUtils } = ChromeUtils.import("resource://gre/modules/E10SUtils.jsm"); +ChromeUtils.defineModuleGetter( + this, + "TalosParentProfiler", + "resource://talos-powers/TalosParentProfiler.jsm" +); var NUM_CYCLES = 5; var numPageCycles = 1; @@ -54,7 +59,7 @@ var content; // These are binary flags. Use 1/2/4/8/... var TEST_DOES_OWN_TIMING = 1; -var EXECUTE_SCROLL_TEST = 2; +var EXECUTE_SCROLL_TEST = 2; var browserWindow = null; @@ -129,7 +134,10 @@ function plInit() { NUM_CYCLES = Services.prefs.getIntPref("talos.tpcycles", 1); numPageCycles = Services.prefs.getIntPref("talos.tppagecycles", 1); timeout = Services.prefs.getIntPref("talos.tptimeout", -1); - useMozAfterPaint = Services.prefs.getBoolPref("talos.tpmozafterpaint", false); + useMozAfterPaint = Services.prefs.getBoolPref( + "talos.tpmozafterpaint", + false + ); useHero = Services.prefs.getBoolPref("talos.tphero", false); useFNBPaint = Services.prefs.getBoolPref("talos.fnbpaint", false); loadNoCache = Services.prefs.getBoolPref("talos.tploadnocache", false); @@ -138,8 +146,9 @@ function plInit() { // for pageloader tests the profiling info is found in an env variable // because it is not available early enough to set it as a browser pref - var env = Cc["@mozilla.org/process/environment;1"]. - getService(Ci.nsIEnvironment); + var env = Cc["@mozilla.org/process/environment;1"].getService( + Ci.nsIEnvironment + ); if (env.exists("TPPROFILINGINFO")) { profilingInfo = env.get("TPPROFILINGINFO"); @@ -165,7 +174,9 @@ function plInit() { plStop(true); } - pageUrls = pages.map(function(p) { return p.url.spec.toString(); }); + pageUrls = pages.map(function(p) { + return p.url.spec.toString(); + }); report = new Report(); pageIndex = 0; @@ -174,8 +185,9 @@ function plInit() { } // Create a new chromed browser window for content - var blank = Cc["@mozilla.org/supports-string;1"] - .createInstance(Ci.nsISupportsString); + var blank = Cc["@mozilla.org/supports-string;1"].createInstance( + Ci.nsISupportsString + ); blank.data = "about:blank"; let toolbars = "all"; @@ -183,8 +195,13 @@ function plInit() { toolbars = "titlebar,resizable"; } - browserWindow = Services.ww.openWindow(null, AppConstants.BROWSER_CHROME_URL, "_blank", - `chrome,${toolbars},dialog=no,width=${winWidth},height=${winHeight}`, blank); + browserWindow = Services.ww.openWindow( + null, + AppConstants.BROWSER_CHROME_URL, + "_blank", + `chrome,${toolbars},dialog=no,width=${winWidth},height=${winHeight}`, + blank + ); gPaintWindow = browserWindow; // get our window out of the way @@ -207,34 +224,77 @@ function plInit() { // instance which adds the load listener and injects tpRecordTime), all the // pages should be able to load in the same mode as the initial page - due // to this reinitialization on the switch. - let remoteType = E10SUtils.getRemoteTypeForURI(pageUrls[0], /* remote */ true, /* fission */ false); + let remoteType = E10SUtils.getRemoteTypeForURI( + pageUrls[0], + /* remote */ true, + /* fission */ false + ); let tabbrowser = browserWindow.gBrowser; if (remoteType) { - tabbrowser.updateBrowserRemoteness(tabbrowser.initialBrowser, { remoteType }); + tabbrowser.updateBrowserRemoteness(tabbrowser.initialBrowser, { + remoteType, + }); } else { - tabbrowser.updateBrowserRemoteness(tabbrowser.initialBrowser, { remoteType: E10SUtils.NOT_REMOTE }); + tabbrowser.updateBrowserRemoteness(tabbrowser.initialBrowser, { + remoteType: E10SUtils.NOT_REMOTE, + }); } browserWindow.resizeTo(winWidth, winHeight); browserWindow.moveTo(0, 0); browserWindow.focus(); content = browserWindow.gBrowser; - content.selectedBrowser.messageManager.loadFrameScript("chrome://pageloader/content/utils.js", false, true); + content.selectedBrowser.messageManager.loadFrameScript( + "chrome://pageloader/content/utils.js", + false, + true + ); // pick the right load handler if (useFNBPaint) { - content.selectedBrowser.messageManager.loadFrameScript("chrome://pageloader/content/lh_fnbpaint.js", false, true); + content.selectedBrowser.messageManager.loadFrameScript( + "chrome://pageloader/content/lh_fnbpaint.js", + false, + true + ); } else if (useMozAfterPaint) { - content.selectedBrowser.messageManager.loadFrameScript("chrome://pageloader/content/lh_moz.js", false, true); + content.selectedBrowser.messageManager.loadFrameScript( + "chrome://pageloader/content/lh_moz.js", + false, + true + ); } else if (useHero) { - content.selectedBrowser.messageManager.loadFrameScript("chrome://pageloader/content/lh_hero.js", false, true); + content.selectedBrowser.messageManager.loadFrameScript( + "chrome://pageloader/content/lh_hero.js", + false, + true + ); } else { - content.selectedBrowser.messageManager.loadFrameScript("chrome://pageloader/content/lh_dummy.js", false, true); + content.selectedBrowser.messageManager.loadFrameScript( + "chrome://pageloader/content/lh_dummy.js", + false, + true + ); } - content.selectedBrowser.messageManager.loadFrameScript("chrome://pageloader/content/talos-content.js", false); - content.selectedBrowser.messageManager.loadFrameScript("resource://talos-powers/TalosContentProfiler.js", false, true); - content.selectedBrowser.messageManager.loadFrameScript("chrome://pageloader/content/tscroll.js", false, true); - content.selectedBrowser.messageManager.loadFrameScript("chrome://pageloader/content/Profiler.js", false, true); + content.selectedBrowser.messageManager.loadFrameScript( + "chrome://pageloader/content/talos-content.js", + false + ); + content.selectedBrowser.messageManager.loadFrameScript( + "resource://talos-powers/TalosContentProfiler.js", + false, + true + ); + content.selectedBrowser.messageManager.loadFrameScript( + "chrome://pageloader/content/tscroll.js", + false, + true + ); + content.selectedBrowser.messageManager.loadFrameScript( + "chrome://pageloader/content/Profiler.js", + false, + true + ); // Ensure that any webextensions that need to do setup have a chance // to do so. e.g. the 'tabswitch' talos test registers a about:tabswitch @@ -259,11 +319,16 @@ function plPageFlags() { var ContentListener = { receiveMessage(message) { switch (message.name) { - case "PageLoader:LoadEvent": return plLoadHandlerMessage(message); - case "PageLoader:Error": return plErrorMessage(message); - case "PageLoader:RecordTime": return plRecordTimeMessage(message); - case "PageLoader:IdleCallbackSet": return plIdleCallbackSet(); - case "PageLoader:IdleCallbackReceived": return plIdleCallbackReceived(); + case "PageLoader:LoadEvent": + return plLoadHandlerMessage(message); + case "PageLoader:Error": + return plErrorMessage(message); + case "PageLoader:RecordTime": + return plRecordTimeMessage(message); + case "PageLoader:IdleCallbackSet": + return plIdleCallbackSet(); + case "PageLoader:IdleCallbackReceived": + return plIdleCallbackReceived(); } return undefined; }, @@ -273,7 +338,9 @@ var ContentListener = { var removeLastAddedMsgListener = null; function plLoadPage() { if (profilingInfo) { - TalosParentProfiler.beginTest(getCurrentPageShortName() + "_pagecycle_" + pageCycle); + TalosParentProfiler.beginTest( + getCurrentPageShortName() + "_pagecycle_" + pageCycle + ); } var pageName = pages[pageIndex].url.spec; @@ -295,7 +362,10 @@ function plLoadPage() { mm.removeMessageListener("PageLoader:LoadEvent", ContentListener); mm.removeMessageListener("PageLoader:RecordTime", ContentListener); mm.removeMessageListener("PageLoader:IdleCallbackSet", ContentListener); - mm.removeMessageListener("PageLoader:IdleCallbackReceived", ContentListener); + mm.removeMessageListener( + "PageLoader:IdleCallbackReceived", + ContentListener + ); mm.removeMessageListener("PageLoader:Error", ContentListener); }; failTimeout.register(loadFail, timeout); @@ -330,7 +400,8 @@ function startAndLoadURI(pageName) { } } -function getTestName() { // returns tp5n +function getTestName() { + // returns tp5n var pageName = pages[pageIndex].url.spec; let parts = pageName.split("/"); if (parts.length > 4) { @@ -360,12 +431,28 @@ function loadFail() { if (numRetries >= maxRetries) { dumpLine("__FAILTimeout in " + getTestName() + "__FAIL"); - dumpLine("__FAILTimeout (" + numRetries + "/" + maxRetries + ") exceeded on " + pageName + "__FAIL"); + dumpLine( + "__FAILTimeout (" + + numRetries + + "/" + + maxRetries + + ") exceeded on " + + pageName + + "__FAIL" + ); TalosParentProfiler.finishTest().then(() => { plStop(true); }); } else { - dumpLine("__WARNTimeout (" + numRetries + "/" + maxRetries + ") exceeded on " + pageName + "__WARN"); + dumpLine( + "__WARNTimeout (" + + numRetries + + "/" + + maxRetries + + ") exceeded on " + + pageName + + "__WARN" + ); // TODO: make this a cleaner cleanup pageCycle--; content.removeEventListener("load", plLoadHandler, true); @@ -467,9 +554,11 @@ function waitForFNBPaint() { } function forceContentGC() { - return new Promise((resolve) => { + return new Promise(resolve => { let mm = browserWindow.gBrowser.selectedBrowser.messageManager; - mm.addMessageListener("Talos:ForceGC:OK", function onTalosContentForceGC(msg) { + mm.addMessageListener("Talos:ForceGC:OK", function onTalosContentForceGC( + msg + ) { mm.removeMessageListener("Talos:ForceGC:OK", onTalosContentForceGC); resolve(); }); @@ -497,7 +586,7 @@ function plRecordTime(time) { recordedName = pageUrls[pageIndex]; } } - if (typeof(time) == "string") { + if (typeof time == "string") { var times = time.split(","); var names = recordedName.split(","); for (var t = 0; t < times.length; t++) { @@ -510,17 +599,31 @@ function plRecordTime(time) { } else { report.recordTime(recordedName, time); } - dumpLine("Cycle " + (cycle + 1) + "(" + pageCycle + "): loaded " + pageName + " (next: " + nextName + ")"); + dumpLine( + "Cycle " + + (cycle + 1) + + "(" + + pageCycle + + "): loaded " + + pageName + + " (next: " + + nextName + + ")" + ); } function plLoadHandlerCapturing(evt) { // make sure we pick up the right load event - if (evt.type != "load" || - evt.originalTarget.defaultView.frameElement) - return; + if (evt.type != "load" || evt.originalTarget.defaultView.frameElement) { + return; + } // set the tpRecordTime function (called from test pages we load) to store a global time. - content.contentWindow.wrappedJSObject.tpRecordTime = function(time, startTime, testName) { + content.contentWindow.wrappedJSObject.tpRecordTime = function( + time, + startTime, + testName + ) { gTime = time; gStartTime = startTime; recordedName = testName; @@ -542,20 +645,26 @@ function sendScroll() { const SCROLL_TEST_NUM_STEPS = 100; // The page doesn't really use tpRecordTime. Instead, we trigger the scroll test, // and the scroll test will call tpRecordTime which will take us to the next page - let details = {target: "content", stepSize: SCROLL_TEST_STEP_PX, opt_numSteps: SCROLL_TEST_NUM_STEPS}; + let details = { + target: "content", + stepSize: SCROLL_TEST_STEP_PX, + opt_numSteps: SCROLL_TEST_NUM_STEPS, + }; let mm = content.selectedBrowser.messageManager; mm.sendAsyncMessage("PageLoader:ScrollTest", { details }); } function plWaitForPaintingCapturing() { - if (gPaintListener) + if (gPaintListener) { return; + } var utils = gPaintWindow.windowUtils; if (utils.isMozAfterPaintPending && useMozAfterPaint) { - if (!gPaintListener) + if (!gPaintListener) { gPaintWindow.addEventListener("MozAfterPaint", plPaintedCapturing, true); + } gPaintListener = true; return; } @@ -573,13 +682,15 @@ function _loadHandlerCapturing() { failTimeout.clear(); if (!(plPageFlags() & TEST_DOES_OWN_TIMING)) { - dumpLine("tp: Capturing onload handler used with page that doesn't do its own timing?"); + dumpLine( + "tp: Capturing onload handler used with page that doesn't do its own timing?" + ); plStop(true); } if (useMozAfterPaint) { if (gStartTime != null && gStartTime >= 0) { - gTime = (new Date()) - gStartTime; + gTime = new Date() - gStartTime; gStartTime = -1; } } @@ -596,9 +707,9 @@ function _loadHandlerCapturing() { // the onload handler function plLoadHandler(evt) { // make sure we pick up the right load event - if (evt.type != "load" || - evt.originalTarget.defaultView.frameElement) - return; + if (evt.type != "load" || evt.originalTarget.defaultView.frameElement) { + return; + } content.removeEventListener("load", plLoadHandler, true); setTimeout(waitForPainted, 0); @@ -613,8 +724,9 @@ function waitForPainted() { return; } - if (!gPaintListener) + if (!gPaintListener) { gPaintWindow.addEventListener("MozAfterPaint", plPainted, true); + } gPaintListener = true; } @@ -636,13 +748,15 @@ function _loadHandler(paint_time = 0) { end_time = Date.now(); } - var duration = (end_time - start_time); + var duration = end_time - start_time; TalosParentProfiler.pause("Bubbling load handler fired."); // does this page want to do its own timing? // if so, we shouldn't be here if (plPageFlags() & TEST_DOES_OWN_TIMING) { - dumpLine("tp: Bubbling onload handler used with page that does its own timing?"); + dumpLine( + "tp: Bubbling onload handler used with page that does its own timing?" + ); plStop(true); } @@ -657,23 +771,24 @@ function plLoadHandlerMessage(message) { // of the load handler, so in future versions // we can record several times per load. if (message.json.time !== undefined) { - paint_time = message.json.time; - if (message.json.name == "fnbpaint") { - // we've received fnbpaint; no longer pending for this current pageload - isFNBPaintPending = false; - } + paint_time = message.json.time; + if (message.json.name == "fnbpaint") { + // we've received fnbpaint; no longer pending for this current pageload + isFNBPaintPending = false; + } } failTimeout.clear(); - if ((plPageFlags() & EXECUTE_SCROLL_TEST)) { + if (plPageFlags() & EXECUTE_SCROLL_TEST) { // Let the page settle down after its load event, then execute the scroll test. setTimeout(sendScroll, 500); - } else if ((plPageFlags() & TEST_DOES_OWN_TIMING)) { + } else if (plPageFlags() & TEST_DOES_OWN_TIMING) { var time; - if (typeof(gStartTime) != "number") + if (typeof gStartTime != "number") { gStartTime = Date.parse(gStartTime); + } if (gTime !== -1) { if (useMozAfterPaint && gStartTime >= 0) { time = Date.now() - gStartTime; @@ -705,7 +820,6 @@ function plRecordTimeMessage(message) { _loadHandlerCapturing(); } - // error function plErrorMessage(message) { if (message.json.msg) { @@ -714,7 +828,6 @@ function plErrorMessage(message) { plStop(true); } - function plStop(force) { plStopAll(force); } @@ -755,21 +868,30 @@ function plStopAll(force) { if (isIdleCallbackPending) { mm.removeMessageListener("PageLoader:IdleCallbackSet", ContentListener); - mm.removeMessageListener("PageLoader:IdleCallbackReceived", ContentListener); + mm.removeMessageListener( + "PageLoader:IdleCallbackReceived", + ContentListener + ); } - mm.loadFrameScript("data:,removeEventListener('load', _contentLoadHandler, true);", false, true); + mm.loadFrameScript( + "data:,removeEventListener('load', _contentLoadHandler, true);", + false, + true + ); } - if (MozillaFileLogger && MozillaFileLogger._foStream) + if (MozillaFileLogger && MozillaFileLogger._foStream) { MozillaFileLogger.close(); + } goQuitApplication(); } /* Returns array */ function plLoadURLsFromURI(manifestUri) { - var fstream = Cc["@mozilla.org/network/file-input-stream;1"] - .createInstance(Ci.nsIFileInputStream); + var fstream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance( + Ci.nsIFileInputStream + ); var uriFile = manifestUri.QueryInterface(Ci.nsIFileURL); @@ -781,8 +903,8 @@ function plLoadURLsFromURI(manifestUri) { try { fstream.init(uriFile.file, -1, 0, 0); } catch (ex) { - dumpLine("tp: the file %s doesn't exist" % uriFile.file); - return null; + dumpLine("tp: the file %s doesn't exist" % uriFile.file); + return null; } var lstream = fstream.QueryInterface(Ci.nsILineInputStream); @@ -790,7 +912,7 @@ function plLoadURLsFromURI(manifestUri) { var url_array = []; var lineNo = 0; - var line = {value: null}; + var line = { value: null }; var baseVsRefIndex = 0; var more; do { @@ -804,8 +926,9 @@ function plLoadURLsFromURI(manifestUri) { // strip leading and trailing whitespace s = s.replace(/^\s*/, "").replace(/\s*$/, ""); - if (!s) + if (!s) { continue; + } var flags = 0; var urlspec = s; @@ -815,19 +938,34 @@ function plLoadURLsFromURI(manifestUri) { var items = s.split(/\s+/); if (items[0] == "include") { if (items.length != 2) { - dumpLine("tp: Error on line " + lineNo + " in " + manifestUri.spec + ": include must be followed by the manifest to include!"); + dumpLine( + "tp: Error on line " + + lineNo + + " in " + + manifestUri.spec + + ": include must be followed by the manifest to include!" + ); return null; } var subManifest = Services.io.newURI(items[1], null, manifestUri); if (subManifest == null) { - dumpLine("tp: invalid URI on line " + manifestUri.spec + ":" + lineNo + " : '" + line.value + "'"); + dumpLine( + "tp: invalid URI on line " + + manifestUri.spec + + ":" + + lineNo + + " : '" + + line.value + + "'" + ); return null; } var subItems = plLoadURLsFromURI(subManifest); - if (subItems == null) + if (subItems == null) { return null; + } url_array = url_array.concat(subItems); } else { // For scrollTest flag, we accept "normal" pages but treat them as TEST_DOES_OWN_TIMING @@ -838,14 +976,16 @@ function plLoadURLsFromURI(manifestUri) { // Note that if we have the scrollTest flag but the item already has "%", then we do // nothing (the scroll test will not execute, and the page will report with its // own tpRecordTime and not the one from the scroll test). - if (scrollTest && items.length == 1) { // scroll enabled and no "%" + if (scrollTest && items.length == 1) { + // scroll enabled and no "%" items.unshift("%"); flags |= EXECUTE_SCROLL_TEST; } if (items.length == 2) { - if (items[0].includes("%")) + if (items[0].includes("%")) { flags |= TEST_DOES_OWN_TIMING; + } urlspec = items[1]; } else if (items.length == 3) { @@ -861,11 +1001,23 @@ function plLoadURLsFromURI(manifestUri) { var urlspecBase = items[1].slice(0, -1); var urlspecRef = items[2]; } else { - dumpLine("tp: Error on line " + lineNo + " in " + manifestUri.spec + ": unknown manifest format!"); + dumpLine( + "tp: Error on line " + + lineNo + + " in " + + manifestUri.spec + + ": unknown manifest format!" + ); return null; } } else if (items.length != 1) { - dumpLine("tp: Error on line " + lineNo + " in " + manifestUri.spec + ": whitespace must be %-escaped!"); + dumpLine( + "tp: Error on line " + + lineNo + + " in " + + manifestUri.spec + + ": whitespace must be %-escaped!" + ); return null; } @@ -874,8 +1026,9 @@ function plLoadURLsFromURI(manifestUri) { if (!baseVsRef) { url = Services.io.newURI(urlspec, null, manifestUri); - if (pageFilterRegexp && !pageFilterRegexp.test(url.spec)) + if (pageFilterRegexp && !pageFilterRegexp.test(url.spec)) { continue; + } url_array.push({ url, flags }); } else { @@ -885,14 +1038,16 @@ function plLoadURLsFromURI(manifestUri) { // the results we use the url as the results key; but we might use the same test page as a reference // page in the same test suite, so we need to add a prefix so this results key is always unique url = Services.io.newURI(urlspecBase, null, manifestUri); - if (pageFilterRegexp && !pageFilterRegexp.test(url.spec)) + if (pageFilterRegexp && !pageFilterRegexp.test(url.spec)) { continue; + } var pre = "base_page_" + baseVsRefIndex + "_"; url_array.push({ url, flags, pre }); url = Services.io.newURI(urlspecRef, null, manifestUri); - if (pageFilterRegexp && !pageFilterRegexp.test(url.spec)) + if (pageFilterRegexp && !pageFilterRegexp.test(url.spec)) { continue; + } pre = "ref_page_" + baseVsRefIndex + "_"; url_array.push({ url, flags, pre }); } @@ -903,8 +1058,9 @@ function plLoadURLsFromURI(manifestUri) { } function dumpLine(str) { - if (MozillaFileLogger && MozillaFileLogger._foStream) + if (MozillaFileLogger && MozillaFileLogger._foStream) { MozillaFileLogger.log(str + "\n"); + } dump(str); dump("\n"); } diff --git a/testing/talos/talos/pageloader/chrome/quit.js b/testing/talos/talos/pageloader/chrome/quit.js index bed2764559d2..0261295c1cdd 100644 --- a/testing/talos/talos/pageloader/chrome/quit.js +++ b/testing/talos/talos/pageloader/chrome/quit.js @@ -44,16 +44,16 @@ function canQuitApplication() { try { - var cancelQuit = Cc["@mozilla.org/supports-PRBool;1"] - .createInstance(Ci.nsISupportsPRBool); + var cancelQuit = Cc["@mozilla.org/supports-PRBool;1"].createInstance( + Ci.nsISupportsPRBool + ); Services.obs.notifyObservers(cancelQuit, "quit-application-requested"); // Something aborted the quit process. if (cancelQuit.data) { return false; } - } catch (ex) { - } + } catch (ex) {} return true; } diff --git a/testing/talos/talos/pageloader/chrome/report.js b/testing/talos/talos/pageloader/chrome/report.js index bbd55e0ce20d..52936052cb93 100644 --- a/testing/talos/talos/pageloader/chrome/report.js +++ b/testing/talos/talos/pageloader/chrome/report.js @@ -8,7 +8,9 @@ function findCommonPrefixLength(strs) { // only one page in the manifest // i.e. http://localhost/tests/perf-reftest/bloom-basic.html var place = strs[0].lastIndexOf("/"); - if (place < 0) place = 0; + if (place < 0) { + place = 0; + } return place; } @@ -32,8 +34,9 @@ function findCommonPrefixLength(strs) { } } - if (failed) + if (failed) { break; + } len++; } while (true); @@ -68,11 +71,15 @@ Report.prototype.getReport = function() { for (var i = 0; i < pages.length; i++) { // don't report any measurements that were reported for about:blank // some tests (like about-preferences) use it as a dummy test page - if (pages[i] == "about:blank") + if (pages[i] == "about:blank") { continue; - report += "|" + - i + ";" + - pages[i].substr(prefixLen) + ";" + + } + report += + "|" + + i + + ";" + + pages[i].substr(prefixLen) + + ";" + this.timeVals[pages[i]].join(";") + "\n"; } @@ -83,7 +90,7 @@ Report.prototype.getReport = function() { report += "_x_x_mozilla_cycle_collect," + this.totalCCTime + "\n"; report += "__end_cc_report\n"; } - var now = (new Date()).getTime(); // eslint-disable-line mozilla/avoid-Date-timing + var now = new Date().getTime(); // eslint-disable-line mozilla/avoid-Date-timing report += "__startTimestamp" + now + "__endTimestamp\n"; // timestamp for determning shutdown time, used by talos return report; @@ -92,20 +99,23 @@ Report.prototype.getReport = function() { Report.prototype.getReportSummary = function() { function average(arr) { var sum = 0; - for (var i in arr) + for (var i in arr) { sum += arr[i]; + } return sum / (arr.length || 1); } function median(arr) { - if (!arr.length) - return 0; // As good indication for "not available" as any other value. + if (!arr.length) { + return 0; + } // As good indication for "not available" as any other value. var sorted = arr.slice(0).sort(); var mid = Math.floor(arr.length / 2); - if (sorted.length % 2) + if (sorted.length % 2) { return sorted[mid]; + } return average(sorted.slice(mid, mid + 2)); } @@ -118,8 +128,12 @@ Report.prototype.getReportSummary = function() { } var avg = average(arr); - var squareDiffArr = arr.map( function(v) { return Math.pow(v - avg, 2); } ); - var sum = squareDiffArr.reduce( function(a, b) { return a + b; } ); + var squareDiffArr = arr.map(function(v) { + return Math.pow(v - avg, 2); + }); + var sum = squareDiffArr.reduce(function(a, b) { + return a + b; + }); var rv = Math.sqrt(sum / (arr.length - 1)); return rv; } @@ -133,20 +147,35 @@ Report.prototype.getReportSummary = function() { for (var i = 0; i < pages.length; i++) { var results = this.timeVals[pages[i]].map(function(v) { - return Number(v); - }); + return Number(v); + }); - report += "\n[#" + i + "] " + pages[i].substr(prefixLen) - + " Cycles:" + results.length - + " Average:" + average(results).toFixed(2) - + " Median:" + median(results).toFixed(2) - + " stddev:" + stddev(results).toFixed(2) - + " (" + (100 * stddev(results) / median(results)).toFixed(1) + "%)" - + (results.length < 5 ? "" : (" stddev-sans-first:" + stddev(results.slice(1)).toFixed(2))) - + "\nValues: " + results.map(function(v) { - return v.toFixed(1); - }).join(" ") - + "\n"; + report += + "\n[#" + + i + + "] " + + pages[i].substr(prefixLen) + + " Cycles:" + + results.length + + " Average:" + + average(results).toFixed(2) + + " Median:" + + median(results).toFixed(2) + + " stddev:" + + stddev(results).toFixed(2) + + " (" + + ((100 * stddev(results)) / median(results)).toFixed(1) + + "%)" + + (results.length < 5 + ? "" + : " stddev-sans-first:" + stddev(results.slice(1)).toFixed(2)) + + "\nValues: " + + results + .map(function(v) { + return v.toFixed(1); + }) + .join(" ") + + "\n"; } report += "-------- Summary: end --------\n"; diff --git a/testing/talos/talos/pageloader/chrome/tscroll.js b/testing/talos/talos/pageloader/chrome/tscroll.js index 9323ad2e9d47..d26508487c33 100644 --- a/testing/talos/talos/pageloader/chrome/tscroll.js +++ b/testing/talos/talos/pageloader/chrome/tscroll.js @@ -20,10 +20,11 @@ function testScroll(target, stepSize, opt_reportFunc, opt_numSteps) { // the path if non-empty (e.g. with tscrollx), or the last dir otherwise (e.g. // 'mydir' for 'http://my.domain/dir1/mydir/'). var href = win.location.href; - var testBaseName = href.split("/tp5n/")[1] - || href.split("/").pop() - || href.split("/").splice(-2, 1)[0] - || "REALLY_WEIRD_URI"; + var testBaseName = + href.split("/tp5n/")[1] || + href.split("/").pop() || + href.split("/").splice(-2, 1)[0] || + "REALLY_WEIRD_URI"; // Verbatim copy from talos-powers/content/TalosPowersContent.js // If the origin changes, this copy should be updated. @@ -35,9 +36,13 @@ function testScroll(target, stepSize, opt_reportFunc, opt_numSteps) { let win = opt_custom_window || window; let replyEvent = "TalosPowers:ParentExec:ReplyEvent:" + this.replyId++; if (callback) { - win.addEventListener(replyEvent, function(e) { - callback(e.detail); - }, {once: true}); + win.addEventListener( + replyEvent, + function(e) { + callback(e.detail); + }, + { once: true } + ); } win.dispatchEvent( new win.CustomEvent("TalosPowers:ParentExec:QueryEvent", { @@ -116,34 +121,64 @@ function testScroll(target, stepSize, opt_reportFunc, opt_numSteps) { function P_MozAfterPaint() { return new Promise(function(resolve) { - win.addEventListener("MozAfterPaint", () => resolve(), { once: true}); + win.addEventListener("MozAfterPaint", () => resolve(), { once: true }); }); } function myNow() { - return (win.performance && win.performance.now) ? - win.performance.now() : - Date.now(); // eslint-disable-line mozilla/avoid-Date-timing + return win.performance && win.performance.now + ? win.performance.now() + : Date.now(); // eslint-disable-line mozilla/avoid-Date-timing } var isWindow = target.self === target; - var getPos = isWindow ? function() { return target.pageYOffset; } - : function() { return target.scrollTop; }; + var getPos = isWindow + ? function() { + return target.pageYOffset; + } + : function() { + return target.scrollTop; + }; - var gotoTop = isWindow ? function() { target.scroll(0, 0); ensureScroll(); } - : function() { target.scrollTop = 0; ensureScroll(); }; + var gotoTop = isWindow + ? function() { + target.scroll(0, 0); + ensureScroll(); + } + : function() { + target.scrollTop = 0; + ensureScroll(); + }; - var doScrollTick = isWindow ? function() { target.scrollBy(0, stepSize); ensureScroll(); } - : function() { target.scrollTop += stepSize; ensureScroll(); }; + var doScrollTick = isWindow + ? function() { + target.scrollBy(0, stepSize); + ensureScroll(); + } + : function() { + target.scrollTop += stepSize; + ensureScroll(); + }; - var setSmooth = isWindow ? function() { target.document.scrollingElement.style.scrollBehavior = "smooth"; } - : function() { target.style.scrollBehavior = "smooth"; }; + var setSmooth = isWindow + ? function() { + target.document.scrollingElement.style.scrollBehavior = "smooth"; + } + : function() { + target.style.scrollBehavior = "smooth"; + }; - var gotoBottom = isWindow ? function() { target.scrollTo(0, target.scrollMaxY); } - : function() { target.scrollTop = target.scrollHeight; }; + var gotoBottom = isWindow + ? function() { + target.scrollTo(0, target.scrollMaxY); + } + : function() { + target.scrollTop = target.scrollHeight; + }; - function ensureScroll() { // Ensure scroll by reading computed values. screenY is for X11. + function ensureScroll() { + // Ensure scroll by reading computed values. screenY is for X11. if (!this.dummyEnsureScroll) { this.dummyEnsureScroll = 1; } @@ -170,9 +205,12 @@ function testScroll(target, stepSize, opt_reportFunc, opt_numSteps) { doScrollTick(); /* stop scrolling if we can't scroll more, or if we've reached requested number of steps */ - if ((getPos() == lastScrollPos) || (opt_numSteps && (durations.length >= (opt_numSteps + 2)))) { + if ( + getPos() == lastScrollPos || + (opt_numSteps && durations.length >= opt_numSteps + 2) + ) { let profilerPaused = Promise.resolve(); - if (typeof(TalosContentProfiler) !== "undefined") { + if (typeof TalosContentProfiler !== "undefined") { profilerPaused = TalosContentProfiler.pause(testBaseName, true); } @@ -185,13 +223,15 @@ function testScroll(target, stepSize, opt_reportFunc, opt_numSteps) { durations.pop(); // Last step was 0. durations.pop(); // and the prev one was shorter and with end-of-page logic, ignore both. - if (win.talosDebug) - win.talosDebug.displayData = true; // In a browser: also display all data points. + if (win.talosDebug) { + win.talosDebug.displayData = true; + } // In a browser: also display all data points. // For analysis (otherwise, it's too many data points for talos): var sum = 0; - for (var i = 0; i < durations.length; i++) + for (var i = 0; i < durations.length; i++) { sum += Number(durations[i]); + } // Report average interval or (failsafe) 0 if no intervls were recorded result.values.push(durations.length ? sum / durations.length : 0); @@ -205,7 +245,7 @@ function testScroll(target, stepSize, opt_reportFunc, opt_numSteps) { P_MozAfterPaint().then(tick); } - if (typeof(TalosContentProfiler) !== "undefined") { + if (typeof TalosContentProfiler !== "undefined") { TalosContentProfiler.resume(testBaseName, true).then(() => { rAF(tick); }); @@ -236,10 +276,11 @@ function testScroll(target, stepSize, opt_reportFunc, opt_numSteps) { setTimeout(function() { stopFrameTimeRecording(handle, function(intervals) { function average(arr) { - var sum = 0; - for (var i = 0; i < arr.length; i++) - sum += arr[i]; - return arr.length ? sum / arr.length : 0; + var sum = 0; + for (var i = 0; i < arr.length; i++) { + sum += arr[i]; + } + return arr.length ? sum / arr.length : 0; } // remove two frames on each side of the recording to get a cleaner result @@ -255,23 +296,28 @@ function testScroll(target, stepSize, opt_reportFunc, opt_numSteps) { } P_setupReportFn() - .then(FP_wait(260)) - .then(gotoTop) - .then(P_rAF) - .then(P_syncScrollTest) - .then(gotoTop) - .then(FP_wait(260)) - .then(P_testAPZScroll) - .then(function() { - report(result.values.join(","), 0, result.names.join(",")); - }); + .then(FP_wait(260)) + .then(gotoTop) + .then(P_rAF) + .then(P_syncScrollTest) + .then(gotoTop) + .then(FP_wait(260)) + .then(P_testAPZScroll) + .then(function() { + report(result.values.join(","), 0, result.names.join(",")); + }); } // This code below here is unique to tscroll.js inside of pageloader try { function handleMessageFromChrome(message) { var payload = message.data.details; - testScroll(payload.target, payload.stepSize, "PageLoader:RecordTime", payload.opt_numSteps); + testScroll( + payload.target, + payload.stepSize, + "PageLoader:RecordTime", + payload.opt_numSteps + ); } addMessageListener("PageLoader:ScrollTest", handleMessageFromChrome); diff --git a/testing/talos/talos/pageloader/chrome/utils.js b/testing/talos/talos/pageloader/chrome/utils.js index 06963471b150..368395d96bdb 100644 --- a/testing/talos/talos/pageloader/chrome/utils.js +++ b/testing/talos/talos/pageloader/chrome/utils.js @@ -3,7 +3,6 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ var idleCallbackHandle; - function _idleCallbackHandler() { content.window.cancelIdleCallback(idleCallbackHandle); sendAsyncMessage("PageLoader:IdleCallbackReceived", {}); @@ -18,7 +17,11 @@ function contentLoadHandlerCallback(cb) { function _handler(e) { if (e.originalTarget.defaultView == content) { content.wrappedJSObject.tpRecordTime = Cu.exportFunction((t, s, n) => { - sendAsyncMessage("PageLoader:RecordTime", {time: t, startTime: s, testName: n}); + sendAsyncMessage("PageLoader:RecordTime", { + time: t, + startTime: s, + testName: n, + }); }, content); content.setTimeout(cb, 0); content.setTimeout(setIdleCallback, 0); diff --git a/testing/talos/talos/scripts/MozillaFileLogger.js b/testing/talos/talos/scripts/MozillaFileLogger.js index 7e9e53da25a1..c82f77bd9575 100644 --- a/testing/talos/talos/scripts/MozillaFileLogger.js +++ b/testing/talos/talos/scripts/MozillaFileLogger.js @@ -5,7 +5,7 @@ var ipcMode = false; // running in e10s build and need to use IPC? function contentDispatchEvent(type, data, sync) { - if (typeof(data) === "undefined") { + if (typeof data === "undefined") { data = {}; } @@ -31,7 +31,6 @@ function dumpLog(msg) { MozFileLogger.log(msg); } - netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); const FOSTREAM_CID = "@mozilla.org/network/file-output-stream;1"; @@ -39,41 +38,46 @@ const LF_CID = "@mozilla.org/file/local;1"; // File status flags. It is a bitwise OR of the following bit flags. // Only one of the first three flags below may be used. -const PR_READ_ONLY = 0x01; // Open for reading only. -const PR_WRITE_ONLY = 0x02; // Open for writing only. -const PR_READ_WRITE = 0x04; // Open for reading and writing. +const PR_READ_ONLY = 0x01; // Open for reading only. +const PR_WRITE_ONLY = 0x02; // Open for writing only. +const PR_READ_WRITE = 0x04; // Open for reading and writing. // If the file does not exist, the file is created. // If the file exists, this flag has no effect. -const PR_CREATE_FILE = 0x08; +const PR_CREATE_FILE = 0x08; // The file pointer is set to the end of the file prior to each write. -const PR_APPEND = 0x10; +const PR_APPEND = 0x10; // If the file exists, its length is truncated to 0. -const PR_TRUNCATE = 0x20; +const PR_TRUNCATE = 0x20; // If set, each write will wait for both the file data // and file status to be physically updated. -const PR_SYNC = 0x40; +const PR_SYNC = 0x40; // If the file does not exist, the file is created. If the file already // exists, no action and NULL is returned. -const PR_EXCL = 0x80; +const PR_EXCL = 0x80; /** Init the file logger with the absolute path to the file. It will create and append if the file already exists **/ var MozFileLogger = {}; - MozFileLogger.init = function(path) { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); MozFileLogger._file = Cc[LF_CID].createInstance(Ci.nsIFile); MozFileLogger._file.initWithPath(path); - MozFileLogger._foStream = Cc[FOSTREAM_CID].createInstance(Ci.nsIFileOutputStream); - MozFileLogger._foStream.init(this._file, PR_WRITE_ONLY | PR_CREATE_FILE | PR_APPEND, - 0o664, 0); + MozFileLogger._foStream = Cc[FOSTREAM_CID].createInstance( + Ci.nsIFileOutputStream + ); + MozFileLogger._foStream.init( + this._file, + PR_WRITE_ONLY | PR_CREATE_FILE | PR_APPEND, + 0o664, + 0 + ); }; MozFileLogger.getLogCallback = function() { @@ -81,8 +85,9 @@ MozFileLogger.getLogCallback = function() { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); var data = msg.num + " " + msg.level + " " + msg.info.join(" ") + "\n"; - if (MozFileLogger._foStream) + if (MozFileLogger._foStream) { MozFileLogger._foStream.write(data, data.length); + } if (data.includes("SimpleTest FINISH")) { MozFileLogger.close(); @@ -95,8 +100,9 @@ MozFileLogger.log = function(msg) { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); try { - if (MozFileLogger._foStream) + if (MozFileLogger._foStream) { MozFileLogger._foStream.write(msg, msg.length); + } } catch (ex) {} }; @@ -108,8 +114,9 @@ MozFileLogger.close = function() { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); - if (MozFileLogger._foStream) + if (MozFileLogger._foStream) { MozFileLogger._foStream.close(); + } MozFileLogger._foStream = null; MozFileLogger._file = null; diff --git a/testing/talos/talos/scripts/Profiler.js b/testing/talos/talos/scripts/Profiler.js index 68412f2807f1..2eb6fcc7b652 100644 --- a/testing/talos/talos/scripts/Profiler.js +++ b/testing/talos/talos/scripts/Profiler.js @@ -45,7 +45,9 @@ var Profiler; try { // eslint-disable-next-line mozilla/use-services _profiler = Cc["@mozilla.org/tools/profiler;1"].getService(Ci.nsIProfiler); - } catch (ex) { (typeof(dumpLog) == "undefined" ? dump : dumpLog)(ex + "\n"); } + } catch (ex) { + (typeof dumpLog == "undefined" ? dump : dumpLog)(ex + "\n"); + } // Parses an url query string into a JS object. function searchToObject(locationSearch) { @@ -72,11 +74,17 @@ var Profiler; * - gecko_profile_dir */ initFromObject: function Profiler__initFromObject(obj) { - if (obj && - ("gecko_profile_dir" in obj) && typeof obj.gecko_profile_dir == "string" && - ("gecko_profile_interval" in obj) && Number.isFinite(obj.gecko_profile_interval * 1) && - ("gecko_profile_entries" in obj) && Number.isFinite(obj.gecko_profile_entries * 1) && - ("gecko_profile_threads" in obj) && typeof obj.gecko_profile_threads == "string") { + if ( + obj && + "gecko_profile_dir" in obj && + typeof obj.gecko_profile_dir == "string" && + "gecko_profile_interval" in obj && + Number.isFinite(obj.gecko_profile_interval * 1) && + "gecko_profile_entries" in obj && + Number.isFinite(obj.gecko_profile_entries * 1) && + "gecko_profile_threads" in obj && + typeof obj.gecko_profile_threads == "string" + ) { profiler_interval = obj.gecko_profile_interval; profiler_entries = obj.gecko_profile_entries; profiler_threadsArray = obj.gecko_profile_threads.split(","); @@ -84,15 +92,20 @@ var Profiler; enabled = true; } }, - initFromURLQueryParams: function Profiler__initFromURLQueryParams(locationSearch) { + initFromURLQueryParams: function Profiler__initFromURLQueryParams( + locationSearch + ) { this.initFromObject(searchToObject(locationSearch)); }, beginTest: function Profiler__beginTest(testName) { currentTest = testName; if (_profiler && enabled) { - _profiler.StartProfiler(profiler_entries, profiler_interval, - ["js", "leaf", "stackwalk", "threads"], - profiler_threadsArray); + _profiler.StartProfiler( + profiler_entries, + profiler_interval, + ["js", "leaf", "stackwalk", "threads"], + profiler_threadsArray + ); if (_profiler.PauseSampling) { _profiler.PauseSampling(); } @@ -100,7 +113,9 @@ var Profiler; }, finishTest: function Profiler__finishTest() { if (_profiler && enabled) { - _profiler.dumpProfileToFile(profiler_dir + "/" + currentTest + ".profile"); + _profiler.dumpProfileToFile( + profiler_dir + "/" + currentTest + ".profile" + ); _profiler.StopProfiler(); } }, @@ -115,7 +130,9 @@ var Profiler; if (_profiler.ResumeSampling) { _profiler.ResumeSampling(); } - _profiler.AddMarker(explicit ? name : 'Start of test "' + (name || test_name) + '"'); + _profiler.AddMarker( + explicit ? name : 'Start of test "' + (name || test_name) + '"' + ); } }, pause: function Profiler__pause(name, explicit) { @@ -123,12 +140,16 @@ var Profiler; if (_profiler.PauseSampling) { _profiler.PauseSampling(); } - _profiler.AddMarker(explicit ? name : 'End of test "' + (name || test_name) + '"'); + _profiler.AddMarker( + explicit ? name : 'End of test "' + (name || test_name) + '"' + ); } }, mark: function Profiler__mark(marker, explicit) { if (_profiler) { - _profiler.AddMarker(explicit ? marker : 'Profiler: "' + (marker || test_name) + '"'); + _profiler.AddMarker( + explicit ? marker : 'Profiler: "' + (marker || test_name) + '"' + ); } }, }; diff --git a/testing/talos/talos/scripts/talos-debug.js b/testing/talos/talos/scripts/talos-debug.js index 9da53b59c721..3b08026b1782 100644 --- a/testing/talos/talos/scripts/talos-debug.js +++ b/testing/talos/talos/scripts/talos-debug.js @@ -23,7 +23,9 @@ window.talosDebug = { // End of config sum(values) { - return values.reduce(function(a, b) { return a + b; }); + return values.reduce(function(a, b) { + return a + b; + }); }, average(values) { @@ -34,12 +36,17 @@ window.talosDebug = { median(values) { var clone = values.slice(0); // eslint-disable-next-line no-nested-ternary - var sorted = clone.sort(function(a, b) { return (a > b) ? 1 : ((a < b) ? -1 : 0); }); + var sorted = clone.sort(function(a, b) { + return a > b ? 1 : a < b ? -1 : 0; + }); var len = values.length; - if (!len) + if (!len) { return 999999; - if (len % 2) // We have a middle number + } + if (len % 2) { + // We have a middle number return sorted[(len - 1) / 2]; + } return (sorted[len / 2] + sorted[len / 2 - 1]) / 2; // Average value of the two middle items. }, @@ -49,8 +56,15 @@ window.talosDebug = { } return Math.sqrt( - values.map(function(v) { return Math.pow(v - avg, 2); }) - .reduce(function(a, b) { return a + b; }) / (values.length - 1)); + values + .map(function(v) { + return Math.pow(v - avg, 2); + }) + .reduce(function(a, b) { + return a + b; + }) / + (values.length - 1) + ); }, // Estimate the number of warmup iterations of this data set (in a completely unscrientific way). @@ -78,7 +92,7 @@ window.talosDebug = { var stableFrom = -1; var overallAverage = d.median(values); // var overallStd = d.stddev(values, overallAverage); - for (var winWidth = MIN_WIDTH; winWidth < (MAX_WIDTH + 1); winWidth++) { + for (var winWidth = MIN_WIDTH; winWidth < MAX_WIDTH + 1; winWidth++) { var prevStd = windowStd(0, winWidth); for (var i = 1; i < values.length - winWidth - 3; i++) { var w0 = windowStd(i + 0, winWidth); @@ -86,8 +100,9 @@ window.talosDebug = { var w2 = windowStd(i + 2, winWidth); // var currWindow = values.slice(i, i + winWidth); if (w0 >= prevStd && !(w1 < w0 && w2 < w1)) { - if (i > stableFrom) + if (i > stableFrom) { stableFrom = i; + } break; } prevStd = w0; @@ -95,7 +110,7 @@ window.talosDebug = { } function withinPercentage(base, value, percentage) { - return Math.abs(base - value) < base * percentage / 100; + return Math.abs(base - value) < (base * percentage) / 100; } // Now go backwards as long as stddev decreases or doesn't increase in more than 1%. var baseStd = d.stddev(values.slice(stableFrom), overallAverage); @@ -104,7 +119,11 @@ window.talosDebug = { var current = d.stddev(values.slice(stableFrom - 1), overallAverage); // 100/len : the more items we have, the more sensitively we compare: // for 100 items, we're allowing 2% over baseStd. - if (stableFrom > 0 && (current < baseStd || withinPercentage(baseStd, current, 200 / (len ? len : 100)))) { + if ( + stableFrom > 0 && + (current < baseStd || + withinPercentage(baseStd, current, 200 / (len ? len : 100))) + ) { stableFrom--; } else { break; @@ -119,26 +138,44 @@ window.talosDebug = { var std = d.stddev(collection, d.average(collection)); var avg = d.average(collection); var med = d.median(collection); - return "Count: " + collection.length + - "\nAverage: " + avg.toFixed(d.fixed) + - "\nMedian: " + med.toFixed(d.fixed) + - "\nStdDev: " + std.toFixed(d.fixed) + " (" + (100 * std / (avg ? avg : 1)).toFixed(d.fixed) + "% of average)"; + return ( + "Count: " + + collection.length + + "\nAverage: " + + avg.toFixed(d.fixed) + + "\nMedian: " + + med.toFixed(d.fixed) + + "\nStdDev: " + + std.toFixed(d.fixed) + + " (" + + ((100 * std) / (avg ? avg : 1)).toFixed(d.fixed) + + "% of average)" + ); }, tpRecordTime(dataCSV) { var d = window.talosDebug; - if (d.disabled) + if (d.disabled) { return; + } - var collection = ("" + dataCSV).split(",").map(function(item) { return parseFloat(item); }); + var collection = ("" + dataCSV).split(",").map(function(item) { + return parseFloat(item); + }); var res = d.statsDisplay(collection); - var warmup = (d.ignore >= 0) ? d.ignore : d.detectWarmup(collection); + var warmup = d.ignore >= 0 ? d.ignore : d.detectWarmup(collection); if (warmup >= 0) { - res += "\n\nWarmup " + ((d.ignore >= 0) ? "requested: " : "auto-detected: ") + warmup; + res += + "\n\nWarmup " + + (d.ignore >= 0 ? "requested: " : "auto-detected: ") + + warmup; var warmedUp = collection.slice(warmup); if (warmup) { - res += "\nAfter ignoring first " + (warmup > 1 ? (warmup + " items") : "item") + ":\n"; + res += + "\nAfter ignoring first " + + (warmup > 1 ? warmup + " items" : "item") + + ":\n"; res += d.statsDisplay(warmedUp); } } else { @@ -147,18 +184,22 @@ window.talosDebug = { if (d.displayData) { var disp = collection.map(function(item) { - return item.toFixed(d.fixed); - }); - if (warmup >= 0) + return item.toFixed(d.fixed); + }); + if (warmup >= 0) { disp.splice(warmup, 0, "[warmed-up:]"); + } res += "\n\nRecorded:\n" + disp.join(", "); res += "\n\nStddev from item NN to last:\n"; disp = collection.map(function(value, index) { - return d.stddev(collection.slice(index), d.average(collection.slice(index))).toFixed(d.fixed); - }); - if (warmup >= 0) + return d + .stddev(collection.slice(index), d.average(collection.slice(index))) + .toFixed(d.fixed); + }); + if (warmup >= 0) { disp.splice(warmup, 0, "[warmed-up:]"); + } res += disp.join(", "); } else { res += "\n\n[set window.talosDebug.displayData=true for data]"; @@ -169,6 +210,6 @@ window.talosDebug = { }; // Enable testing outside of talos by providing an alternative report function. -if (typeof(tpRecordTime) === "undefined") { +if (typeof tpRecordTime === "undefined") { tpRecordTime = window.talosDebug.tpRecordTime; } diff --git a/testing/talos/talos/scripts/xpigen.js b/testing/talos/talos/scripts/xpigen.js index 3a7467ba52ed..9333776f53b7 100644 --- a/testing/talos/talos/scripts/xpigen.js +++ b/testing/talos/talos/scripts/xpigen.js @@ -14,15 +14,20 @@ function createXpiDataUri(base, files, callbacks) { // Synchronous XHR for http[s]/file (untested ftp), throws on any error // Note that on firefox, file:// XHR can't access files outside base dir function readBinFile(url) { - var r = new XMLHttpRequest(); + var r = new XMLHttpRequest(); r.open("GET", url, false); r.requestType = "arraybuffer"; r.overrideMimeType("text/plain; charset=x-user-defined"); - try { r.send(); } catch (e) { throw new Error(`FileNotRetrieved: ${url} - ${e}`); } + try { + r.send(); + } catch (e) { + throw new Error(`FileNotRetrieved: ${url} - ${e}`); + } // For 'file://' Firefox sets status=0 on success or throws otherwise // In Firefox 34-ish onwards, success status is 200. - if (!(r.readyState == 4 && (r.status == 0 || r.status == 200))) + if (!(r.readyState == 4 && (r.status == 0 || r.status == 200))) { throw new Error(`FileNotRetrieved: ${url} - ${r.status} ${r.statusText}`); + } return r.response; } @@ -32,41 +37,66 @@ function createXpiDataUri(base, files, callbacks) { // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding "use strict;"; function uint6ToB64(nUint6) { - return nUint6 < 26 ? nUint6 + 65 : nUint6 < 52 ? nUint6 + 71 : nUint6 < 62 ? - nUint6 - 4 : nUint6 === 62 ? 43 : nUint6 === 63 ? 47 : 65; + return nUint6 < 26 + ? nUint6 + 65 + : nUint6 < 52 + ? nUint6 + 71 + : nUint6 < 62 + ? nUint6 - 4 + : nUint6 === 62 + ? 43 + : nUint6 === 63 + ? 47 + : 65; } - var nMod3 = 2, sB64Enc = ""; + var nMod3 = 2, + sB64Enc = ""; for (var nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) { nMod3 = nIdx % 3; - if (nIdx > 0 && (nIdx * 4 / 3) % 76 === 0) { sB64Enc += "\r\n"; } - nUint24 |= aBytes[nIdx] << (16 >>> nMod3 & 24); + if (nIdx > 0 && ((nIdx * 4) / 3) % 76 === 0) { + sB64Enc += "\r\n"; + } + nUint24 |= aBytes[nIdx] << ((16 >>> nMod3) & 24); if (nMod3 === 2 || aBytes.length - nIdx === 1) { - sB64Enc += String.fromCharCode(uint6ToB64(nUint24 >>> 18 & 63), uint6ToB64(nUint24 >>> 12 & 63), - uint6ToB64(nUint24 >>> 6 & 63), uint6ToB64(nUint24 & 63)); + sB64Enc += String.fromCharCode( + uint6ToB64((nUint24 >>> 18) & 63), + uint6ToB64((nUint24 >>> 12) & 63), + uint6ToB64((nUint24 >>> 6) & 63), + uint6ToB64(nUint24 & 63) + ); nUint24 = 0; } } - return sB64Enc.substr(0, sB64Enc.length - 2 + nMod3) + (nMod3 === 2 ? "" : nMod3 === 1 ? "=" : "=="); + return ( + sB64Enc.substr(0, sB64Enc.length - 2 + nMod3) + + (nMod3 === 2 ? "" : nMod3 === 1 ? "=" : "==") + ); } // Create the zip/xpi try { function dummy() {} - var onsuccess = callbacks.onsuccess || dummy; - var onerror = callbacks.onerror || dummy; + var onsuccess = callbacks.onsuccess || dummy; + var onerror = callbacks.onerror || dummy; var onprogress = callbacks.onprogress || dummy; var zip = new JSZip(); for (var i = 0; i < files.length; i++) { - zip.file(files[i], readBinFile(base + files[i]), - {binary: true, compression: "deflate"}); - onprogress(100 * (i + 1) / (files.length + 1)); + zip.file(files[i], readBinFile(base + files[i]), { + binary: true, + compression: "deflate", + }); + onprogress((100 * (i + 1)) / (files.length + 1)); } - zip = zip.generate({type: "uint8array"}); + zip = zip.generate({ type: "uint8array" }); onprogress(100); - setTimeout(onsuccess, 0, "data:application/x-xpinstall;base64," + base64EncArr(zip)); + setTimeout( + onsuccess, + 0, + "data:application/x-xpinstall;base64," + base64EncArr(zip) + ); } catch (e) { setTimeout(onerror, 0, e); } diff --git a/testing/talos/talos/startup_test/sessionrestore/addon/api.js b/testing/talos/talos/startup_test/sessionrestore/addon/api.js index 87f91a82d1b9..5768c2d7cdf6 100644 --- a/testing/talos/talos/startup_test/sessionrestore/addon/api.js +++ b/testing/talos/talos/startup_test/sessionrestore/addon/api.js @@ -6,7 +6,9 @@ "use strict"; -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); XPCOMUtils.defineLazyModuleGetters(this, { BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm", @@ -34,7 +36,9 @@ this.sessionrestore = class extends ExtensionAPI { // the profile to disk. async function getTalosParentProfiler() { try { - var {TalosParentProfiler} = ChromeUtils.import("resource://talos-powers/TalosParentProfiler.jsm"); + var { TalosParentProfiler } = ChromeUtils.import( + "resource://talos-powers/TalosParentProfiler.jsm" + ); return TalosParentProfiler; } catch (err) { await new Promise(resolve => setTimeout(resolve, 500)); @@ -75,34 +79,48 @@ this.sessionrestore = class extends ExtensionAPI { if (!StartupPerformance.isRestored) { await SessionStartup.onceInitialized; - if (SessionStartup.sessionType == SessionStartup.NO_SESSION || - SessionStartup.sessionType == SessionStartup.DEFER_SESSION) { + if ( + SessionStartup.sessionType == SessionStartup.NO_SESSION || + SessionStartup.sessionType == SessionStartup.DEFER_SESSION + ) { // We should only hit this patch in sessionrestore_no_auto_restore - if (!Services.prefs.getBoolPref("talos.sessionrestore.norestore", false)) { + if ( + !Services.prefs.getBoolPref("talos.sessionrestore.norestore", false) + ) { throw new Error("Session was not restored!"); } - await this.finishProfiling("This test measures the time between process " + - "creation and sessionRestored."); + await this.finishProfiling( + "This test measures the time between process " + + "creation and sessionRestored." + ); didRestore = false; } else { await new Promise(resolve => { let observe = async () => { - Services.obs.removeObserver(observe, StartupPerformance.RESTORED_TOPIC); - await this.finishProfiling("This test measures the time between process " + - "creation and the last restored tab."); + Services.obs.removeObserver( + observe, + StartupPerformance.RESTORED_TOPIC + ); + await this.finishProfiling( + "This test measures the time between process " + + "creation and the last restored tab." + ); resolve(); }; - Services.obs.addObserver(observe, StartupPerformance.RESTORED_TOPIC); + Services.obs.addObserver( + observe, + StartupPerformance.RESTORED_TOPIC + ); }); } } let startup_info = Services.startup.getStartupInfo(); let restoreTime = didRestore - ? StartupPerformance.latestRestoredTimeStamp - : startup_info.sessionRestored; + ? StartupPerformance.latestRestoredTimeStamp + : startup_info.sessionRestored; let duration = restoreTime - startup_info.process; // Report data to Talos, if possible. diff --git a/testing/talos/talos/startup_test/startup_about_home_paint/addon/api.js b/testing/talos/talos/startup_test/startup_about_home_paint/addon/api.js index 2b3540269673..224cfbdd4bb8 100644 --- a/testing/talos/talos/startup_test/startup_about_home_paint/addon/api.js +++ b/testing/talos/talos/startup_test/startup_about_home_paint/addon/api.js @@ -4,7 +4,9 @@ /* globals ExtensionAPI */ -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); XPCOMUtils.defineLazyModuleGetters(this, { BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm", @@ -57,9 +59,9 @@ this.startup_about_home_paint = class extends ExtensionAPI { // eslint-disable-next-line mozilla/avoid-Date-timing dump("__startTimestamp" + Date.now() + "__endTimestamp\n"); - - let env = Cc["@mozilla.org/process/environment;1"] - .getService(Ci.nsIEnvironment); + let env = Cc["@mozilla.org/process/environment;1"].getService( + Ci.nsIEnvironment + ); if (env.exists("TPPROFILINGINFO")) { let profilingInfo = env.get("TPPROFILINGINFO"); @@ -86,7 +88,5 @@ this.startup_about_home_paint = class extends ExtensionAPI { } } - onShutdown() { - - } + onShutdown() {} }; diff --git a/testing/talos/talos/talos-powers/api.js b/testing/talos/talos/talos-powers/api.js index 0d86cd69907e..c8e6cfa0dcb9 100644 --- a/testing/talos/talos/talos-powers/api.js +++ b/testing/talos/talos/talos-powers/api.js @@ -4,7 +4,9 @@ /* globals ExtensionAPI */ -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); XPCOMUtils.defineLazyModuleGetters(this, { BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm", OS: "resource://gre/modules/osfile.jsm", @@ -12,9 +14,12 @@ XPCOMUtils.defineLazyModuleGetters(this, { PerTestCoverageUtils: "resource://testing-common/PerTestCoverageUtils.jsm", }); -XPCOMUtils.defineLazyServiceGetter(this, "resProto", - "@mozilla.org/network/protocol;1?name=resource", - "nsISubstitutingProtocolHandler"); +XPCOMUtils.defineLazyServiceGetter( + this, + "resProto", + "@mozilla.org/network/protocol;1?name=resource", + "nsISubstitutingProtocolHandler" +); // To support the 'new TextEncoder()' call inside of 'profilerFinish()' here, // we have to import TextEncoder. It's not automagically defined for us, @@ -42,8 +47,12 @@ TalosPowersService.prototype = { QueryInterface: ChromeUtils.generateQI([]), register() { - Cm.registerFactory(this.classID, this.classDescription, - this.contractID, this.factory); + Cm.registerFactory( + this.classID, + this.classDescription, + this.contractID, + this.factory + ); void Cc[this.contractID].getService(); }, @@ -107,10 +116,12 @@ TalosPowersService.prototype = { * The thread names to sample. */ profilerBegin(data) { - Services.profiler - .StartProfiler(data.entries, data.interval, - ["js", "leaf", "stackwalk", "threads"], - data.threadsArray); + Services.profiler.StartProfiler( + data.entries, + data.interval, + ["js", "leaf", "stackwalk", "threads"], + data.threadsArray + ); Services.profiler.PauseSampling(); }, @@ -128,23 +139,26 @@ TalosPowersService.prototype = { */ profilerFinish(profileFile) { return new Promise((resolve, reject) => { - Services.profiler.getProfileDataAsync().then((profile) => { - let encoder = new TextEncoder(); - let array = encoder.encode(JSON.stringify(profile)); + Services.profiler.getProfileDataAsync().then( + profile => { + let encoder = new TextEncoder(); + let array = encoder.encode(JSON.stringify(profile)); - OS.File.writeAtomic(profileFile, array, { - tmpPath: profileFile + ".tmp", - }).then(() => { - Services.profiler.StopProfiler(); - resolve(); - Services.obs.notifyObservers(null, "talos-profile-gathered"); - }); - }, (error) => { - Cu.reportError("Failed to gather profile: " + error); - // FIXME: We should probably send a message down to the - // child which causes it to reject the waiting Promise. - reject(); - }); + OS.File.writeAtomic(profileFile, array, { + tmpPath: profileFile + ".tmp", + }).then(() => { + Services.profiler.StopProfiler(); + resolve(); + Services.obs.notifyObservers(null, "talos-profile-gathered"); + }); + }, + error => { + Cu.reportError("Failed to gather profile: " + error); + // FIXME: We should probably send a message down to the + // child which causes it to reject the waiting Promise. + reject(); + } + ); }); }, @@ -231,7 +245,10 @@ TalosPowersService.prototype = { async forceQuit(messageData) { if (messageData && messageData.waitForSafeBrowsing) { - let SafeBrowsing = ChromeUtils.import("resource://gre/modules/SafeBrowsing.jsm", {}).SafeBrowsing; + let SafeBrowsing = ChromeUtils.import( + "resource://gre/modules/SafeBrowsing.jsm", + {} + ).SafeBrowsing; // Speed things up in case nobody else called this: SafeBrowsing.init(); @@ -275,13 +292,17 @@ TalosPowersService.prototype = { let obs = function(subject, topic) { Services.obs.removeObserver(this, topic); startupInfo = Services.startup.getStartupInfo(); - mm.sendAsyncMessage("TalosPowersContent:GetStartupInfo:Result", - startupInfo); + mm.sendAsyncMessage( + "TalosPowersContent:GetStartupInfo:Result", + startupInfo + ); }; Services.obs.addObserver(obs, "widget-first-paint"); } else { - mm.sendAsyncMessage("TalosPowersContent:GetStartupInfo:Result", - startupInfo); + mm.sendAsyncMessage( + "TalosPowersContent:GetStartupInfo:Result", + startupInfo + ); } }, @@ -327,7 +348,9 @@ TalosPowersService.prototype = { }, dumpAboutSupport(arg, callback, win) { - const {Troubleshoot} = ChromeUtils.import("resource://gre/modules/Troubleshoot.jsm"); + const { Troubleshoot } = ChromeUtils.import( + "resource://gre/modules/Troubleshoot.jsm" + ); Troubleshoot.snapshot(function(snapshot) { dump("about:support\t" + JSON.stringify(snapshot)); }); @@ -345,20 +368,32 @@ TalosPowersService.prototype = { } let command = msg.data.command; - if (!this.ParentExecServices.hasOwnProperty(command.name)) - throw new Error("TalosPowers:ParentExec: Invalid service '" + command.name + "'"); + if (!this.ParentExecServices.hasOwnProperty(command.name)) { + throw new Error( + "TalosPowers:ParentExec: Invalid service '" + command.name + "'" + ); + } - this.ParentExecServices[command.name](command.data, sendResult, msg.target.ownerGlobal); + this.ParentExecServices[command.name]( + command.data, + sendResult, + msg.target.ownerGlobal + ); }, - }; this.talos_powers = class extends ExtensionAPI { onStartup() { let uri = Services.io.newURI("content/", null, this.extension.rootURI); - resProto.setSubstitutionWithFlags("talos-powers", uri, resProto.ALLOW_CONTENT_ACCESS); + resProto.setSubstitutionWithFlags( + "talos-powers", + uri, + resProto.ALLOW_CONTENT_ACCESS + ); - frameScriptURL = this.extension.baseURI.resolve("chrome/talos-powers-content.js"); + frameScriptURL = this.extension.baseURI.resolve( + "chrome/talos-powers-content.js" + ); TalosPowersService.prototype.register(); } diff --git a/testing/talos/talos/talos-powers/chrome/talos-powers-content.js b/testing/talos/talos/talos-powers/chrome/talos-powers-content.js index d05bfbf8e8a9..b8ae56afa882 100644 --- a/testing/talos/talos/talos-powers/chrome/talos-powers-content.js +++ b/testing/talos/talos/talos-powers/chrome/talos-powers-content.js @@ -6,62 +6,87 @@ /* global docShell */ // eslint-env mozilla/frame-script -addEventListener("TalosContentProfilerCommand", (e) => { +addEventListener("TalosContentProfilerCommand", e => { let name = e.detail.name; let data = e.detail.data; sendAsyncMessage("TalosContentProfiler:Command", { name, data }); }); -addMessageListener("TalosContentProfiler:Response", (msg) => { +addMessageListener("TalosContentProfiler:Response", msg => { let name = msg.data.name; let data = msg.data.data; - let event = Cu.cloneInto({ - bubbles: true, - detail: { - name, - data, + let event = Cu.cloneInto( + { + bubbles: true, + detail: { + name, + data, + }, }, - }, content); + content + ); content.dispatchEvent( - new content.CustomEvent("TalosContentProfilerResponse", event)); + new content.CustomEvent("TalosContentProfilerResponse", event) + ); }); -addEventListener("TalosPowersContentForceCCAndGC", (e) => { +addEventListener("TalosPowersContentForceCCAndGC", e => { Cu.forceGC(); Cu.forceCC(); Cu.forceShrinkingGC(); sendSyncMessage("TalosPowersContent:ForceCCAndGC"); }); -addEventListener("TalosPowersContentFocus", (e) => { - if (content.location.protocol != "file:" && +addEventListener( + "TalosPowersContentFocus", + e => { + if ( + content.location.protocol != "file:" && content.location.hostname != "localhost" && - content.location.hostname != "127.0.0.1") { - throw new Error("TalosPowersContentFocus may only be used with local content"); - } - content.focus(); - let contentEvent = Cu.cloneInto({ - bubbles: true, - }, content); - content.dispatchEvent(new content.CustomEvent("TalosPowersContentFocused", contentEvent)); -}, true, true); - -addEventListener("TalosPowersContentGetStartupInfo", (e) => { - sendAsyncMessage("TalosPowersContent:GetStartupInfo"); - addMessageListener("TalosPowersContent:GetStartupInfo:Result", - function onResult(msg) { - removeMessageListener("TalosPowersContent:GetStartupInfo:Result", - onResult); - let event = Cu.cloneInto({ - bubbles: true, - detail: msg.data, - }, content); - + content.location.hostname != "127.0.0.1" + ) { + throw new Error( + "TalosPowersContentFocus may only be used with local content" + ); + } + content.focus(); + let contentEvent = Cu.cloneInto( + { + bubbles: true, + }, + content + ); content.dispatchEvent( - new content.CustomEvent("TalosPowersContentGetStartupInfoResult", - event)); - }); + new content.CustomEvent("TalosPowersContentFocused", contentEvent) + ); + }, + true, + true +); + +addEventListener("TalosPowersContentGetStartupInfo", e => { + sendAsyncMessage("TalosPowersContent:GetStartupInfo"); + addMessageListener( + "TalosPowersContent:GetStartupInfo:Result", + function onResult(msg) { + removeMessageListener( + "TalosPowersContent:GetStartupInfo:Result", + onResult + ); + let event = Cu.cloneInto( + { + bubbles: true, + detail: msg.data, + }, + content + ); + + content.dispatchEvent( + new content.CustomEvent("TalosPowersContentGetStartupInfoResult", event) + ); + } + ); }); /** @@ -69,15 +94,14 @@ addEventListener("TalosPowersContentGetStartupInfo", (e) => { * fire the TalosPowersGoQuitApplication custom event. This will * attempt to force-quit the browser. */ -addEventListener("TalosPowersGoQuitApplication", (e) => { +addEventListener("TalosPowersGoQuitApplication", e => { // If we're loaded in a low-priority background process, like // the background page thumbnailer, then we shouldn't be allowed // to quit the whole application. This is a workaround until // bug 1164459 is fixed. - let priority = docShell.QueryInterface(Ci.nsIDocumentLoader) - .loadGroup - .QueryInterface(Ci.nsISupportsPriority) - .priority; + let priority = docShell + .QueryInterface(Ci.nsIDocumentLoader) + .loadGroup.QueryInterface(Ci.nsISupportsPriority).priority; if (priority != Ci.nsISupportsPriority.PRIORITY_LOWEST) { sendAsyncMessage("Talos:ForceQuit", e.detail); } @@ -91,33 +115,51 @@ addEventListener("TalosPowersGoQuitApplication", (e) => { * The consumer API for this mechanism is at content/TalosPowersContent.js * and the callees are at ParentExecServices at components/TalosPowersService.js */ -addEventListener("TalosPowers:ParentExec:QueryEvent", function(e) { - if (content.location.protocol != "file:" && +addEventListener( + "TalosPowers:ParentExec:QueryEvent", + function(e) { + if ( + content.location.protocol != "file:" && content.location.hostname != "localhost" && - content.location.hostname != "127.0.0.1") { - throw new Error("TalosPowers:ParentExec may only be used with local content"); - } - let uniqueMessageId = "TalosPowers:ParentExec:" - + content.document.documentURI + Date.now() + Math.random(); // eslint-disable-line mozilla/avoid-Date-timing + content.location.hostname != "127.0.0.1" + ) { + throw new Error( + "TalosPowers:ParentExec may only be used with local content" + ); + } + let uniqueMessageId = + "TalosPowers:ParentExec:" + + content.document.documentURI + + Date.now() + + Math.random(); // eslint-disable-line mozilla/avoid-Date-timing - // Listener for the reply from the parent process - addMessageListener("TalosPowers:ParentExec:ReplyMsg", function done(reply) { - if (reply.data.id != uniqueMessageId) - return; + // Listener for the reply from the parent process + addMessageListener("TalosPowers:ParentExec:ReplyMsg", function done(reply) { + if (reply.data.id != uniqueMessageId) { + return; + } - removeMessageListener("TalosPowers:ParentExec:ReplyMsg", done); + removeMessageListener("TalosPowers:ParentExec:ReplyMsg", done); - // reply to content via an event - let contentEvent = Cu.cloneInto({ - bubbles: true, - detail: reply.data.result, - }, content); - content.dispatchEvent(new content.CustomEvent(e.detail.listeningTo, contentEvent)); - }); + // reply to content via an event + let contentEvent = Cu.cloneInto( + { + bubbles: true, + detail: reply.data.result, + }, + content + ); + content.dispatchEvent( + new content.CustomEvent(e.detail.listeningTo, contentEvent) + ); + }); - // Send the query to the parent process - sendAsyncMessage("TalosPowers:ParentExec:QueryMsg", { - command: e.detail.command, - id: uniqueMessageId, - }); -}, false, true); // wantsUntrusted since we're exposing to unprivileged + // Send the query to the parent process + sendAsyncMessage("TalosPowers:ParentExec:QueryMsg", { + command: e.detail.command, + id: uniqueMessageId, + }); + }, + false, + true +); // wantsUntrusted since we're exposing to unprivileged diff --git a/testing/talos/talos/talos-powers/content/TalosContentProfiler.js b/testing/talos/talos/talos-powers/content/TalosContentProfiler.js index fac826af7fca..1ebb8163a00d 100644 --- a/testing/talos/talos/talos-powers/content/TalosContentProfiler.js +++ b/testing/talos/talos/talos-powers/content/TalosContentProfiler.js @@ -57,10 +57,12 @@ var TalosContentProfiler; // If we're running as a frame script, we can send messages directly to // the parent, rather than going through the talos-powers-content.js // mediator, which ends up being more complicated. - if (typeof(sendAsyncMessage) !== "undefined") { + if (typeof sendAsyncMessage !== "undefined") { return new Promise(resolve => { sendAsyncMessage("TalosContentProfiler:Command", { name, data }); - addMessageListener("TalosContentProfiler:Response", function onMsg(msg) { + addMessageListener("TalosContentProfiler:Response", function onMsg( + msg + ) { if (msg.data.name != name) { return; } @@ -71,7 +73,7 @@ var TalosContentProfiler; }); } - return new Promise((resolve) => { + return new Promise(resolve => { var event = new CustomEvent("TalosContentProfilerCommand", { bubbles: true, detail: { @@ -81,7 +83,9 @@ var TalosContentProfiler; }); document.dispatchEvent(event); - addEventListener("TalosContentProfilerResponse", function onResponse(event) { + addEventListener("TalosContentProfilerResponse", function onResponse( + event + ) { if (event.detail.name != name) { return; } @@ -129,17 +133,25 @@ var TalosContentProfiler; */ initFromObject(obj = {}) { if (!initted) { - if (("gecko_profile_dir" in obj) && typeof obj.gecko_profile_dir == "string" && - ("gecko_profile_interval" in obj) && Number.isFinite(obj.gecko_profile_interval * 1) && - ("gecko_profile_entries" in obj) && Number.isFinite(obj.gecko_profile_entries * 1) && - ("gecko_profile_threads" in obj) && typeof obj.gecko_profile_threads == "string") { + if ( + "gecko_profile_dir" in obj && + typeof obj.gecko_profile_dir == "string" && + "gecko_profile_interval" in obj && + Number.isFinite(obj.gecko_profile_interval * 1) && + "gecko_profile_entries" in obj && + Number.isFinite(obj.gecko_profile_entries * 1) && + "gecko_profile_threads" in obj && + typeof obj.gecko_profile_threads == "string" + ) { interval = obj.gecko_profile_interval; entries = obj.gecko_profile_entries; threadsArray = obj.gecko_profile_threads.split(","); profileDir = obj.gecko_profile_dir; initted = true; } else { - console.error("Profiler could not init with object: " + JSON.stringify(obj)); + console.error( + "Profiler could not init with object: " + JSON.stringify(obj) + ); } } }, @@ -285,7 +297,7 @@ var TalosContentProfiler; // sendAsyncMessage is a hack-y mechanism to determine whether or not // we're running as a frame script. If we are, jam TalosContentProfiler // into the content scope. - if (typeof(sendAsyncMessage) !== "undefined") { + if (typeof sendAsyncMessage !== "undefined") { content.wrappedJSObject.TalosContentProfiler = TalosContentProfiler; } })(); diff --git a/testing/talos/talos/talos-powers/content/TalosParentProfiler.jsm b/testing/talos/talos/talos-powers/content/TalosParentProfiler.jsm index 4b24790a1f9b..8d206a8e1ad1 100644 --- a/testing/talos/talos/talos-powers/content/TalosParentProfiler.jsm +++ b/testing/talos/talos/talos-powers/content/TalosParentProfiler.jsm @@ -16,7 +16,7 @@ var EXPORTED_SYMBOLS = ["TalosParentProfiler"]; -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const TalosParentProfiler = { // Whether or not this TalosContentProfiler object has had initFromObject @@ -35,9 +35,9 @@ const TalosParentProfiler = { get TalosPowers() { // Use a bit of XPCOM hackery to get at the Talos Powers service // implementation... - return Cc["@mozilla.org/talos/talos-powers-service;1"] - .getService(Ci.nsISupports) - .wrappedJSObject; + return Cc["@mozilla.org/talos/talos-powers-service;1"].getService( + Ci.nsISupports + ).wrappedJSObject; }, /** @@ -52,17 +52,25 @@ const TalosParentProfiler = { */ initFromObject(obj = {}) { if (!this.initted) { - if (("gecko_profile_dir" in obj) && typeof obj.gecko_profile_dir == "string" && - ("gecko_profile_interval" in obj) && Number.isFinite(obj.gecko_profile_interval * 1) && - ("gecko_profile_entries" in obj) && Number.isFinite(obj.gecko_profile_entries * 1) && - ("gecko_profile_threads" in obj) && typeof obj.gecko_profile_threads == "string") { + if ( + "gecko_profile_dir" in obj && + typeof obj.gecko_profile_dir == "string" && + "gecko_profile_interval" in obj && + Number.isFinite(obj.gecko_profile_interval * 1) && + "gecko_profile_entries" in obj && + Number.isFinite(obj.gecko_profile_entries * 1) && + "gecko_profile_threads" in obj && + typeof obj.gecko_profile_threads == "string" + ) { this.interval = obj.gecko_profile_interval; this.entries = obj.gecko_profile_entries; this.threadsArray = obj.gecko_profile_threads.split(","); this.profileDir = obj.gecko_profile_dir; this.initted = true; } else { - console.error("Profiler could not init with object: " + JSON.stringify(obj)); + console.error( + "Profiler could not init with object: " + JSON.stringify(obj) + ); } } }, @@ -117,8 +125,9 @@ const TalosParentProfiler = { threadsArray: this.threadsArray, }); } else { - let msg = "You should not call beginTest without having first " + - "initted the Profiler"; + let msg = + "You should not call beginTest without having first " + + "initted the Profiler"; console.error(msg); } }, @@ -137,10 +146,11 @@ const TalosParentProfiler = { let profileFile = this.profileDir + "/" + this.currentTest + ".profile"; return this.TalosPowers.profilerFinish(profileFile); } - let msg = "You should not call finishTest without having first " + - "initted the Profiler"; - console.error(msg); - return Promise.reject(msg); + let msg = + "You should not call finishTest without having first " + + "initted the Profiler"; + console.error(msg); + return Promise.reject(msg); }, /** diff --git a/testing/talos/talos/talos-powers/content/TalosPowersContent.js b/testing/talos/talos/talos-powers/content/TalosPowersContent.js index 79137d82b33f..6dd0e84f5a5e 100644 --- a/testing/talos/talos/talos-powers/content/TalosPowersContent.js +++ b/testing/talos/talos/talos-powers/content/TalosPowersContent.js @@ -23,7 +23,9 @@ var TalosPowersParent; let pingPromise = new Promise(resolve => { TalosPowersParent.exec("ping", null, resolve); }); - let timeoutPromise = new Promise((resolve, reject) => { setTimeout(reject, 500); }); + let timeoutPromise = new Promise((resolve, reject) => { + setTimeout(reject, 500); + }); try { await Promise.race([pingPromise, timeoutPromise]); @@ -60,24 +62,30 @@ var TalosPowersParent; callback(); }); } - document.dispatchEvent(new CustomEvent("TalosPowersContentFocus", { - bubbles: true, - })); + document.dispatchEvent( + new CustomEvent("TalosPowersContentFocus", { + bubbles: true, + }) + ); }, getStartupInfo() { - return new Promise((resolve) => { + return new Promise(resolve => { var event = new CustomEvent("TalosPowersContentGetStartupInfo", { bubbles: true, }); document.dispatchEvent(event); - addEventListener("TalosPowersContentGetStartupInfoResult", - function onResult(e) { - removeEventListener("TalosPowersContentGetStartupInfoResult", - onResult); - resolve(e.detail); - }); + addEventListener( + "TalosPowersContentGetStartupInfoResult", + function onResult(e) { + removeEventListener( + "TalosPowersContentGetStartupInfoResult", + onResult + ); + resolve(e.detail); + } + ); }); }, @@ -103,9 +111,13 @@ var TalosPowersParent; let win = opt_custom_window || window; let replyEvent = "TalosPowers:ParentExec:ReplyEvent:" + this.replyId++; if (callback) { - win.addEventListener(replyEvent, function(e) { - callback(e.detail); - }, {once: true}); + win.addEventListener( + replyEvent, + function(e) { + callback(e.detail); + }, + { once: true } + ); } win.dispatchEvent( new win.CustomEvent("TalosPowers:ParentExec:QueryEvent", { @@ -120,7 +132,6 @@ var TalosPowersParent; }) ); }, - }; // End of possibly embedded code })(); diff --git a/testing/talos/talos/tests/a11y/a11y.js b/testing/talos/talos/tests/a11y/a11y.js index f0772db2ab7e..8fd27e8ce615 100644 --- a/testing/talos/talos/tests/a11y/a11y.js +++ b/testing/talos/talos/tests/a11y/a11y.js @@ -10,10 +10,11 @@ function initAccessibility() { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); if (!gAccService) { var service = Cc["@mozilla.org/accessibilityService;1"]; - if (service) { // fails if build lacks accessibility module - gAccService = - Cc["@mozilla.org/accessibilityService;1"] - .getService(Ci.nsIAccessibilityService); + if (service) { + // fails if build lacks accessibility module + gAccService = Cc["@mozilla.org/accessibilityService;1"].getService( + Ci.nsIAccessibilityService + ); } } return gAccService; @@ -22,8 +23,7 @@ function initAccessibility() { function getAccessible(aNode) { try { return gAccService.getAccessibleFor(aNode); - } catch (e) { - } + } catch (e) {} return null; } diff --git a/testing/talos/talos/tests/cpstartup/extension/api.js b/testing/talos/talos/tests/cpstartup/extension/api.js index c206cd671d14..3214ccc6f370 100644 --- a/testing/talos/talos/tests/cpstartup/extension/api.js +++ b/testing/talos/talos/tests/cpstartup/extension/api.js @@ -15,16 +15,19 @@ * the content side, just the overhead of spawning a new content process. */ -ChromeUtils.defineModuleGetter(this, "TalosParentProfiler", - "resource://talos-powers/TalosParentProfiler.jsm"); -ChromeUtils.defineModuleGetter(this, "Services", - "resource://gre/modules/Services.jsm"); +ChromeUtils.defineModuleGetter( + this, + "TalosParentProfiler", + "resource://talos-powers/TalosParentProfiler.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "Services", + "resource://gre/modules/Services.jsm" +); const PREALLOCATED_PREF = "dom.ipc.processPrelaunch.enabled"; -const MESSAGES = [ - "CPStartup:Go", - "Content:BrowserChildReady", -]; +const MESSAGES = ["CPStartup:Go", "Content:BrowserChildReady"]; /* global ExtensionAPI */ @@ -37,7 +40,9 @@ this.cpstartup = class extends ExtensionAPI { this.framescriptURL = this.extension.baseURI.resolve("/framescript.js"); Services.mm.loadFrameScript(this.framescriptURL, true); - this.originalPreallocatedEnabled = Services.prefs.getBoolPref(PREALLOCATED_PREF); + this.originalPreallocatedEnabled = Services.prefs.getBoolPref( + PREALLOCATED_PREF + ); Services.prefs.setBoolPref(PREALLOCATED_PREF, false); this.readyCallback = null; @@ -46,7 +51,10 @@ this.cpstartup = class extends ExtensionAPI { } onShutdown() { - Services.prefs.setBoolPref(PREALLOCATED_PREF, this.originalPreallocatedEnabled); + Services.prefs.setBoolPref( + PREALLOCATED_PREF, + this.originalPreallocatedEnabled + ); Services.mm.removeDelayedFrameScript(this.framescriptURL); for (let msgName of MESSAGES) { @@ -61,14 +69,17 @@ this.cpstartup = class extends ExtensionAPI { switch (msg.name) { case "CPStartup:Go": { this.openTab(gBrowser, msg.data.target).then(results => - this.reportResults(results)); + this.reportResults(results) + ); break; } case "Content:BrowserChildReady": { // Content has reported that it's ready to process an URL. if (!this.readyCallback) { - throw new Error("Content:BrowserChildReady fired without a readyCallback set"); + throw new Error( + "Content:BrowserChildReady fired without a readyCallback set" + ); } let tab = gBrowser.getTabForBrowser(browser); if (tab != this.tab) { @@ -78,7 +89,7 @@ this.cpstartup = class extends ExtensionAPI { // The child stopped the timer when it was ready to process the first URL, it's time to // calculate the difference and report it. let delta = msg.data.time - this.startStamp; - this.readyCallback({tab, delta}); + this.readyCallback({ tab, delta }); break; } } @@ -90,27 +101,31 @@ this.cpstartup = class extends ExtensionAPI { this.startStamp = Services.telemetry.msSystemNow(); this.tab = gBrowser.selectedTab = gBrowser.addTrustedTab(url); - let {tab, delta} = await this.whenTabReady(); + let { tab, delta } = await this.whenTabReady(); TalosParentProfiler.pause("tab opening end"); await this.removeTab(tab); return delta; } whenTabReady() { - return new Promise((resolve) => { + return new Promise(resolve => { this.readyCallback = resolve; }); } removeTab(tab) { - return new Promise((resolve) => { - let {messageManager: mm, frameLoader} = tab.linkedBrowser; - mm.addMessageListener("SessionStore:update", function onMessage(msg) { - if (msg.targetFrameLoader == frameLoader && msg.data.isFinal) { - mm.removeMessageListener("SessionStore:update", onMessage); - resolve(); - } - }, true); + return new Promise(resolve => { + let { messageManager: mm, frameLoader } = tab.linkedBrowser; + mm.addMessageListener( + "SessionStore:update", + function onMessage(msg) { + if (msg.targetFrameLoader == frameLoader && msg.data.isFinal) { + mm.removeMessageListener("SessionStore:update", onMessage); + resolve(); + } + }, + true + ); tab.ownerGlobal.gBrowser.removeTab(tab); }); diff --git a/testing/talos/talos/tests/cpstartup/extension/framescript.js b/testing/talos/talos/tests/cpstartup/extension/framescript.js index 45029e20695f..9626dc75cc1e 100644 --- a/testing/talos/talos/tests/cpstartup/extension/framescript.js +++ b/testing/talos/talos/tests/cpstartup/extension/framescript.js @@ -1,19 +1,34 @@ (function() { - addEventListener("CPStartup:Ping", e => { - let evt = new content.CustomEvent("CPStartup:Pong", {bubbles: true}); - content.dispatchEvent(evt); - }, false, true); + addEventListener( + "CPStartup:Ping", + e => { + let evt = new content.CustomEvent("CPStartup:Pong", { bubbles: true }); + content.dispatchEvent(evt); + }, + false, + true + ); - addEventListener("CPStartup:Go", e => { - sendAsyncMessage("CPStartup:Go", e.detail); - }, false, true); + addEventListener( + "CPStartup:Go", + e => { + sendAsyncMessage("CPStartup:Go", e.detail); + }, + false, + true + ); addMessageListener("CPStartup:FinalResults", msg => { - let evt = Cu.cloneInto({ - bubbles: true, - detail: msg.data, - }, content); + let evt = Cu.cloneInto( + { + bubbles: true, + detail: msg.data, + }, + content + ); - content.dispatchEvent(new content.CustomEvent("CPStartup:FinalResults", evt)); + content.dispatchEvent( + new content.CustomEvent("CPStartup:FinalResults", evt) + ); }); })(); diff --git a/testing/talos/talos/tests/devtools/addon/api.js b/testing/talos/talos/tests/devtools/addon/api.js index 1c73dd65716a..159c598e0973 100644 --- a/testing/talos/talos/tests/devtools/addon/api.js +++ b/testing/talos/talos/tests/devtools/addon/api.js @@ -1,7 +1,10 @@ "use strict"; -ChromeUtils.defineModuleGetter(this, "Services", - "resource://gre/modules/Services.jsm"); +ChromeUtils.defineModuleGetter( + this, + "Services", + "resource://gre/modules/Services.jsm" +); /* globals ExtensionAPI */ this.damp = class extends ExtensionAPI { @@ -9,7 +12,7 @@ this.damp = class extends ExtensionAPI { return { damp: { startTest() { - let {rootURI} = context.extension; + let { rootURI } = context.extension; let window = context.xulWindow; if (!("Damp" in window)) { let script = rootURI.resolve("content/damp.js"); diff --git a/testing/talos/talos/tests/devtools/addon/content/damp-tests.js b/testing/talos/talos/tests/devtools/addon/content/damp-tests.js index 87a91893521e..34d8bc12a5d6 100644 --- a/testing/talos/talos/tests/devtools/addon/content/damp-tests.js +++ b/testing/talos/talos/tests/devtools/addon/content/damp-tests.js @@ -28,7 +28,8 @@ module.exports = [ { name: "inspector.cold-open", path: "inspector/cold-open.js", - description: "Measure first open toolbox on inspector panel (incl. shared modules)", + description: + "Measure first open toolbox on inspector panel (incl. shared modules)", cold: true, }, { @@ -53,54 +54,74 @@ module.exports = [ { name: "simple.webconsole", path: "webconsole/simple.js", - description: "Measure open/close toolbox on webconsole panel against simple document", - }, { + description: + "Measure open/close toolbox on webconsole panel against simple document", + }, + { name: "simple.inspector", path: "inspector/simple.js", - description: "Measure open/close toolbox on inspector panel against simple document", - }, { + description: + "Measure open/close toolbox on inspector panel against simple document", + }, + { name: "simple.debugger", path: "debugger/simple.js", - description: "Measure open/close toolbox on debugger panel against simple document", - }, { + description: + "Measure open/close toolbox on debugger panel against simple document", + }, + { name: "simple.styleeditor", path: "styleeditor/simple.js", - description: "Measure open/close toolbox on style editor panel against simple document", - }, { + description: + "Measure open/close toolbox on style editor panel against simple document", + }, + { name: "simple.netmonitor", path: "netmonitor/simple.js", - description: "Measure open/close toolbox on network monitor panel against simple document", + description: + "Measure open/close toolbox on network monitor panel against simple document", }, // Run all tests against "complicated" document { name: "complicated.webconsole", path: "webconsole/complicated.js", - description: "Measure open/close toolbox on webconsole panel against complicated document", - }, { + description: + "Measure open/close toolbox on webconsole panel against complicated document", + }, + { name: "complicated.inspector", path: "inspector/complicated.js", - description: "Measure open/close toolbox on inspector panel against complicated document", - }, { + description: + "Measure open/close toolbox on inspector panel against complicated document", + }, + { name: "complicated.debugger", path: "debugger/complicated.js", - description: "Measure open/close toolbox on debugger panel against complicated document", - }, { + description: + "Measure open/close toolbox on debugger panel against complicated document", + }, + { name: "complicated.styleeditor", path: "styleeditor/complicated.js", - description: "Measure open/close toolbox on style editor panel against complicated document", - }, { + description: + "Measure open/close toolbox on style editor panel against complicated document", + }, + { name: "complicated.netmonitor", path: "netmonitor/complicated.js", - description: "Measure open/close toolbox on network monitor panel against complicated document", + description: + "Measure open/close toolbox on network monitor panel against complicated document", }, // Run all tests against a document specific to each tool { name: "custom.webconsole", path: "webconsole/custom.js", - }, { + }, + { name: "custom.inspector", path: "inspector/custom.js", - }, { + }, + { name: "custom.debugger", path: "debugger/custom.js", }, @@ -108,40 +129,54 @@ module.exports = [ { name: "console.bulklog", path: "webconsole/bulklog.js", - description: "Measure time for a bunch of sync console.log statements to appear", - }, { + description: + "Measure time for a bunch of sync console.log statements to appear", + }, + { name: "console.autocomplete", path: "webconsole/autocomplete.js", description: "Measure time for autocomplete popup to appear", - }, { + }, + { name: "console.streamlog", path: "webconsole/streamlog.js", - description: "Measure rAF on page during a stream of console.log statements", - }, { + description: + "Measure rAF on page during a stream of console.log statements", + }, + { name: "console.objectexpand", path: "webconsole/objectexpand.js", description: "Measure time to expand a large object and close the console", - }, { + }, + { name: "console.openwithcache", path: "webconsole/openwithcache.js", - description: "Measure time to render last logged messages in console for a page with 100 logged messages", - }, { + description: + "Measure time to render last logged messages in console for a page with 100 logged messages", + }, + { name: "console.typing", path: "webconsole/typing.js", description: "Measure time it takes to type something in the console input", - }, { + }, + { name: "inspector.mutations", path: "inspector/mutations.js", - description: "Measure the time to perform childList mutations when inspector is enabled", - }, { + description: + "Measure the time to perform childList mutations when inspector is enabled", + }, + { name: "inspector.layout", path: "inspector/layout.js", - description: "Measure the time to open/close toolbox on inspector with layout tab against big document with grid containers", - }, { + description: + "Measure the time to open/close toolbox on inspector with layout tab against big document with grid containers", + }, + { name: "panelsInBackground.reload", path: "toolbox/panels-in-background.js", description: "Measure page reload time when all panels are in background", - }, { + }, + { name: "server.protocoljs", path: "server/protocol.js", description: "Measure RDP/protocol.js performance", diff --git a/testing/talos/talos/tests/devtools/addon/content/damp.js b/testing/talos/talos/tests/devtools/addon/content/damp.js index d824856ca8df..2a8680594a5d 100644 --- a/testing/talos/talos/tests/devtools/addon/content/damp.js +++ b/testing/talos/talos/tests/devtools/addon/content/damp.js @@ -1,11 +1,16 @@ var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); -var { XPCOMUtils } = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); -const { AddonManager } = ChromeUtils.import("resource://gre/modules/AddonManager.jsm"); -const env = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment); +var { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); +const { AddonManager } = ChromeUtils.import( + "resource://gre/modules/AddonManager.jsm" +); +const env = Cc["@mozilla.org/process/environment;1"].getService( + Ci.nsIEnvironment +); XPCOMUtils.defineLazyGetter(this, "require", function() { - let { require } = - ChromeUtils.import("resource://devtools/shared/Loader.jsm"); + let { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm"); return require; }); @@ -25,20 +30,32 @@ function getMostRecentBrowserWindow() { let gmm = window.getGroupMessageManager("browsers"); -const frameScript = "data:," + encodeURIComponent(`(${ - function() { - addEventListener("load", function(event) { - let subframe = event.target != content.document; - sendAsyncMessage("browser-test-utils:loadEvent", - {subframe, url: event.target.documentURI}); - }, true); - } -})()`); +const frameScript = + "data:," + + encodeURIComponent( + `(${function() { + addEventListener( + "load", + function(event) { + let subframe = event.target != content.document; + sendAsyncMessage("browser-test-utils:loadEvent", { + subframe, + url: event.target.documentURI, + }); + }, + true + ); + }})()` + ); gmm.loadFrameScript(frameScript, true); // This is duplicated from BrowserTestUtils.jsm -function awaitBrowserLoaded(browser, includeSubFrames = false, wantLoad = null) { +function awaitBrowserLoaded( + browser, + includeSubFrames = false, + wantLoad = null +) { // If browser belongs to tabbrowser-tab, ensure it has been // inserted into the document. let tabbrowser = browser.ownerGlobal.gBrowser; @@ -49,7 +66,7 @@ function awaitBrowserLoaded(browser, includeSubFrames = false, wantLoad = null) function isWanted(url) { if (!wantLoad) { return true; - } else if (typeof(wantLoad) == "function") { + } else if (typeof wantLoad == "function") { return wantLoad(url); } // It's a string. @@ -59,8 +76,11 @@ function awaitBrowserLoaded(browser, includeSubFrames = false, wantLoad = null) return new Promise(resolve => { let mm = browser.ownerGlobal.messageManager; mm.addMessageListener("browser-test-utils:loadEvent", function onLoad(msg) { - if (msg.target == browser && (!msg.data.subframe || includeSubFrames) && - isWanted(msg.data.url)) { + if ( + msg.target == browser && + (!msg.data.subframe || includeSubFrames) && + isWanted(msg.data.url) + ) { mm.removeMessageListener("browser-test-utils:loadEvent", onLoad); resolve(msg.data.url); } @@ -101,7 +121,9 @@ Damp.prototype = { // before continuing. async function getTalosParentProfiler() { try { - var {TalosParentProfiler} = ChromeUtils.import("resource://talos-powers/TalosParentProfiler.jsm"); + var { TalosParentProfiler } = ChromeUtils.import( + "resource://talos-powers/TalosParentProfiler.jsm" + ); return TalosParentProfiler; } catch (err) { await new Promise(resolve => setTimeout(resolve, 500)); @@ -196,8 +218,10 @@ Damp.prototype = { async addTab(url) { // Disable opening animation to avoid intermittents and prevent having to wait for // animation's end. (See bug 1480953) - let tab = this._win.gBrowser.selectedTab = this._win.gBrowser.addTrustedTab(url, - { skipAnimation: true }); + let tab = (this._win.gBrowser.selectedTab = this._win.gBrowser.addTrustedTab( + url, + { skipAnimation: true } + )); let browser = tab.linkedBrowser; await awaitBrowserLoaded(browser); return tab; @@ -208,10 +232,14 @@ Damp.prototype = { window.performance.mark("pending paints.start"); while (utils.isMozAfterPaintPending) { await new Promise(done => { - window.addEventListener("MozAfterPaint", function listener() { - window.performance.mark("pending paint"); - done(); - }, { once: true }); + window.addEventListener( + "MozAfterPaint", + function listener() { + window.performance.mark("pending paint"); + done(); + }, + { once: true } + ); }); } window.performance.measure("pending paints", "pending paints.start"); @@ -220,7 +248,7 @@ Damp.prototype = { reloadPage(onReload) { return new Promise(resolve => { let browser = gBrowser.selectedBrowser; - if (typeof(onReload) == "function") { + if (typeof onReload == "function") { onReload().then(resolve); } else { resolve(awaitBrowserLoaded(browser)); @@ -293,7 +321,7 @@ Damp.prototype = { let promise = testMethod(); // If test method is an async function, ensure catching its exceptions - if (promise && typeof(promise.catch) == "function") { + if (promise && typeof promise.catch == "function") { promise.catch(e => { this.exception(e); }); @@ -310,8 +338,9 @@ Damp.prototype = { }, _log(str) { - if (window.MozillaFileLogger && window.MozillaFileLogger.log) + if (window.MozillaFileLogger && window.MozillaFileLogger.log) { window.MozillaFileLogger.log(str); + } window.dump(str); }, @@ -327,10 +356,16 @@ Damp.prototype = { var out = ""; for (var i in this._results) { res = this._results[i]; - var disp = [].concat(res.value).map(function(a) { return (isNaN(a) ? -1 : a.toFixed(1)); }).join(" "); + var disp = [] + .concat(res.value) + .map(function(a) { + return isNaN(a) ? -1 : a.toFixed(1); + }) + .join(" "); out += res.name + ": " + disp + "\n"; - if (!Array.isArray(res.value)) { // Waw intervals array is not reported to talos + if (!Array.isArray(res.value)) { + // Waw intervals array is not reported to talos testNames.push(res.name); testResults.push(res.value); } @@ -340,12 +375,14 @@ Damp.prototype = { if (DEBUG_SCREENSHOTS) { // When we are printing screenshots, we don't want to want to exit firefox // so that we have time to view them. - dump("All tests are finished, please review the screenshots and close the browser manually.\n"); + dump( + "All tests are finished, please review the screenshots and close the browser manually.\n" + ); return; } if (this.testDone) { - this.testDone({testResults, testNames}); + this.testDone({ testResults, testNames }); } else { // alert(out); } @@ -373,7 +410,9 @@ Damp.prototype = { }, startAllocationTracker() { - const { allocationTracker } = require("devtools/shared/test-helpers/allocation-tracker"); + const { + allocationTracker, + } = require("devtools/shared/test-helpers/allocation-tracker"); return allocationTracker(); }, @@ -437,7 +476,9 @@ Damp.prototype = { }, startTest(rootURI) { - let promise = new Promise(resolve => { this.testDone = resolve; }); + let promise = new Promise(resolve => { + this.testDone = resolve; + }); this.rootURI = rootURI; try { dump("Initialize the head file with a reference to this DAMP instance\n"); @@ -452,8 +493,9 @@ Damp.prototype = { let filter = Services.prefs.getCharPref("talos.subtests", ""); let DAMP_TESTS = require(rootURI.resolve("content/damp-tests.js")); - let tests = DAMP_TESTS.filter(test => !test.disabled) - .filter(test => test.name.includes(filter)); + let tests = DAMP_TESTS.filter(test => !test.disabled).filter(test => + test.name.includes(filter) + ); if (tests.length === 0) { this.error(`Unable to find any test matching '${filter}'`); @@ -473,12 +515,14 @@ Damp.prototype = { sequenceArray.push(test.path); } - this.waitBeforeRunningTests().then(() => { - this.TalosParentProfiler.resume("DAMP - start"); - this._doSequence(sequenceArray, this._doneInternal); - }).catch(e => { - this.exception(e); - }); + this.waitBeforeRunningTests() + .then(() => { + this.TalosParentProfiler.resume("DAMP - start"); + this._doSequence(sequenceArray, this._doneInternal); + }) + .catch(e => { + this.exception(e); + }); } catch (e) { this.exception(e); } diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/debugger/cold-open.js b/testing/talos/talos/tests/devtools/addon/content/tests/debugger/cold-open.js index a1d0b2ab2514..f3138cc5f18f 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/debugger/cold-open.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/debugger/cold-open.js @@ -4,7 +4,12 @@ "use strict"; -const { closeToolbox, testSetup, testTeardown, SIMPLE_URL } = require("../head"); +const { + closeToolbox, + testSetup, + testTeardown, + SIMPLE_URL, +} = require("../head"); const { openDebuggerAndLog } = require("./debugger-helpers"); const EXPECTED = { diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/debugger/complicated.js b/testing/talos/talos/tests/devtools/addon/content/tests/debugger/complicated.js index c59db956f219..f1818971ca13 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/debugger/complicated.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/debugger/complicated.js @@ -4,8 +4,16 @@ "use strict"; -const { closeToolboxAndLog, testSetup, testTeardown, COMPLICATED_URL } = require("../head"); -const { openDebuggerAndLog, reloadDebuggerAndLog } = require("./debugger-helpers"); +const { + closeToolboxAndLog, + testSetup, + testTeardown, + COMPLICATED_URL, +} = require("../head"); +const { + openDebuggerAndLog, + reloadDebuggerAndLog, +} = require("./debugger-helpers"); const EXPECTED = { sources: 14, diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/debugger/custom.js b/testing/talos/talos/tests/devtools/addon/content/tests/debugger/custom.js index 60a85152c3eb..702eab334336 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/debugger/custom.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/debugger/custom.js @@ -5,10 +5,24 @@ "use strict"; const Services = require("Services"); -const { closeToolboxAndLog, garbageCollect, runTest, testSetup, - testTeardown, PAGES_BASE_URL } = require("../head"); -const { createContext, openDebuggerAndLog, pauseDebugger, reloadDebuggerAndLog, - removeBreakpoints, resume, step, hoverOnToken } = require("./debugger-helpers"); +const { + closeToolboxAndLog, + garbageCollect, + runTest, + testSetup, + testTeardown, + PAGES_BASE_URL, +} = require("../head"); +const { + createContext, + openDebuggerAndLog, + pauseDebugger, + reloadDebuggerAndLog, + removeBreakpoints, + resume, + step, + hoverOnToken, +} = require("./debugger-helpers"); const EXPECTED = { sources: 107, diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/debugger/debugger-helpers.js b/testing/talos/talos/tests/devtools/addon/content/tests/debugger/debugger-helpers.js index 446ec3e9e46f..a6b458eeba84 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/debugger/debugger-helpers.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/debugger/debugger-helpers.js @@ -101,14 +101,11 @@ function waitForText(dbg, url, text) { } function waitForSymbols(dbg) { - return waitUntil( - () => { - const state = dbg.store.getState(); - const source = dbg.selectors.getSelectedSource(state); - return dbg.selectors.hasSymbols(state, source); - }, - "has file metadata" - ); + return waitUntil(() => { + const state = dbg.store.getState(); + const source = dbg.selectors.getSelectedSource(state); + return dbg.selectors.hasSymbols(state, source); + }, "has file metadata"); } function waitForSources(dbg, expectedSources) { @@ -132,13 +129,10 @@ async function waitForPaused(dbg) { const { selectors: { getSelectedScope, getIsPaused, getCurrentThread }, } = dbg; - const onStateChange = waitForState( - dbg, - state => { - const thread = getCurrentThread(state); - return getSelectedScope(state, thread) && getIsPaused(state, thread); - }, - ); + const onStateChange = waitForState(dbg, state => { + const thread = getCurrentThread(state); + return getSelectedScope(state, thread) && getIsPaused(state, thread); + }); return Promise.all([onLoadedScope, onStateChange]); } @@ -158,7 +152,7 @@ async function waitForElement(dbg, name) { } async function waitForLoadedScopes(dbg) { - const element = ".scopes-list .tree-node[aria-level=\"1\"]"; + const element = '.scopes-list .tree-node[aria-level="1"]'; return waitForElement(dbg, element); } @@ -184,7 +178,9 @@ function selectSource(dbg, url) { return waitForState( dbg, state => { - const { source, content } = dbg.selectors.getSelectedSourceWithContent(state); + const { source, content } = dbg.selectors.getSelectedSourceWithContent( + state + ); if (!content) { return false; } @@ -203,11 +199,16 @@ function evalInContent(dbg, tab, testFunction) { // inside of the content process and trigger debugger functionality // as needed const messageManager = tab.linkedBrowser.messageManager; - return messageManager.loadFrameScript("data:,(" + encodeURIComponent( - `function () { + return messageManager.loadFrameScript( + "data:,(" + + encodeURIComponent( + `function () { content.window.eval("${testFunction}"); }` - ) + ")()", true); + ) + + ")()", + true + ); } async function openDebuggerAndLog(label, expected) { @@ -219,7 +220,11 @@ async function openDebuggerAndLog(label, expected) { await waitForSymbols(dbg); }; - const toolbox = await openToolboxAndLog(label + ".jsdebugger", "jsdebugger", onLoad); + const toolbox = await openToolboxAndLog( + label + ".jsdebugger", + "jsdebugger", + onLoad + ); return toolbox; } exports.openDebuggerAndLog = openDebuggerAndLog; diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/debugger/simple.js b/testing/talos/talos/tests/devtools/addon/content/tests/debugger/simple.js index 6ab54fa7e97b..4b068c98abaa 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/debugger/simple.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/debugger/simple.js @@ -4,8 +4,16 @@ "use strict"; -const { closeToolboxAndLog, testSetup, testTeardown, SIMPLE_URL } = require("../head"); -const { openDebuggerAndLog, reloadDebuggerAndLog } = require("./debugger-helpers"); +const { + closeToolboxAndLog, + testSetup, + testTeardown, + SIMPLE_URL, +} = require("../head"); +const { + openDebuggerAndLog, + reloadDebuggerAndLog, +} = require("./debugger-helpers"); const EXPECTED = { sources: 1, diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/head.js b/testing/talos/talos/tests/devtools/addon/content/tests/head.js index 4eed745a2534..43268759594e 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/head.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/head.js @@ -18,7 +18,8 @@ const PAGES_BASE_URL = webserver + "/tests/devtools/addon/content/pages/"; exports.PAGES_BASE_URL = PAGES_BASE_URL; exports.SIMPLE_URL = PAGES_BASE_URL + "simple.html"; -exports.COMPLICATED_URL = webserver + "/tests/tp5n/bild.de/www.bild.de/index.html"; +exports.COMPLICATED_URL = + webserver + "/tests/tp5n/bild.de/www.bild.de/index.html"; let damp = null; /* @@ -85,7 +86,7 @@ const openToolbox = async function(tool = "webconsole", onLoad) { let showPromise = gDevTools.showToolbox(target, tool); let toolbox = await onToolboxCreated; - if (typeof(onLoad) == "function") { + if (typeof onLoad == "function") { let panel = await toolbox.getPanelWhenReady(tool); await onLoad(toolbox, panel); } @@ -95,7 +96,7 @@ const openToolbox = async function(tool = "webconsole", onLoad) { }; exports.openToolbox = openToolbox; -exports.closeToolbox = async function() { +exports.closeToolbox = async function() { let tab = getActiveTab(); let target = await TargetFactory.forTab(tab); await target.client.waitForRequestsToSettle(); diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/inspector/cold-open.js b/testing/talos/talos/tests/devtools/addon/content/tests/inspector/cold-open.js index 6a660ea25635..ce614a1a4eb1 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/inspector/cold-open.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/inspector/cold-open.js @@ -4,8 +4,13 @@ "use strict"; -const { openToolboxAndLog, closeToolbox, testSetup, - testTeardown, SIMPLE_URL } = require("../head"); +const { + openToolboxAndLog, + closeToolbox, + testSetup, + testTeardown, + SIMPLE_URL, +} = require("../head"); // This simple test is only called once using the flag coldRun module.exports = async function() { diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/inspector/complicated.js b/testing/talos/talos/tests/devtools/addon/content/tests/inspector/complicated.js index 3b3f59d612a2..87520d4adcdf 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/inspector/complicated.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/inspector/complicated.js @@ -5,8 +5,13 @@ "use strict"; const { reloadInspectorAndLog } = require("./inspector-helpers"); -const { openToolboxAndLog, closeToolboxAndLog, testSetup, - testTeardown, COMPLICATED_URL } = require("../head"); +const { + openToolboxAndLog, + closeToolboxAndLog, + testSetup, + testTeardown, + COMPLICATED_URL, +} = require("../head"); module.exports = async function() { await testSetup(COMPLICATED_URL); diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/inspector/custom.js b/testing/talos/talos/tests/devtools/addon/content/tests/inspector/custom.js index 5330c0b9aaec..d65885061f44 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/inspector/custom.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/inspector/custom.js @@ -4,9 +4,18 @@ "use strict"; -const { reloadInspectorAndLog, selectNodeFront } = require("./inspector-helpers"); -const { openToolboxAndLog, closeToolboxAndLog, runTest, testSetup, - testTeardown, PAGES_BASE_URL } = require("../head"); +const { + reloadInspectorAndLog, + selectNodeFront, +} = require("./inspector-helpers"); +const { + openToolboxAndLog, + closeToolboxAndLog, + runTest, + testSetup, + testTeardown, + PAGES_BASE_URL, +} = require("../head"); module.exports = async function() { await testSetup(PAGES_BASE_URL + "custom/inspector/index.html"); @@ -34,8 +43,14 @@ async function selectNodeWithManyRulesAndLog(toolbox) { // Retrieve the node front for the test node. let root = await inspector.walker.getRootNode(); - let referenceNodeFront = await inspector.walker.querySelector(root, ".no-css-rules"); - let testNodeFront = await inspector.walker.querySelector(root, ".many-css-rules"); + let referenceNodeFront = await inspector.walker.querySelector( + root, + ".no-css-rules" + ); + let testNodeFront = await inspector.walker.querySelector( + root, + ".many-css-rules" + ); // Select test node and measure the time to display the rule view with many rules. dump("Selecting .many-css-rules test node front\n"); @@ -59,7 +74,10 @@ async function collapseExpandAllAndLog(toolbox) { let root = await inspector.walker.getRootNode(); dump("Select expand-many-children node\n"); - let many = await inspector.walker.querySelector(root, ".expand-many-children"); + let many = await inspector.walker.querySelector( + root, + ".expand-many-children" + ); await selectNodeFront(inspector, many); dump("Expand all children of expand-many-children\n"); diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/inspector/layout.js b/testing/talos/talos/tests/devtools/addon/content/tests/inspector/layout.js index ada3c7b69662..924fe7c6cba2 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/inspector/layout.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/inspector/layout.js @@ -6,15 +6,23 @@ const Services = require("Services"); -const { openToolbox, closeToolbox, runTest, testSetup, - testTeardown, SIMPLE_URL } = require("../head"); +const { + openToolbox, + closeToolbox, + runTest, + testSetup, + testTeardown, + SIMPLE_URL, +} = require("../head"); module.exports = async function() { let tab = await testSetup(SIMPLE_URL); let messageManager = tab.linkedBrowser.messageManager; // Backup current sidebar tab preference - let sidebarTab = Services.prefs.getCharPref("devtools.inspector.activeSidebar"); + let sidebarTab = Services.prefs.getCharPref( + "devtools.inspector.activeSidebar" + ); // Set layoutview as the current inspector sidebar tab. Services.prefs.setCharPref("devtools.inspector.activeSidebar", "layoutview"); @@ -26,8 +34,10 @@ module.exports = async function() { const NODES = 5000; const GRID_NODES = 10; - messageManager.loadFrameScript("data:,(" + encodeURIComponent( - `function () { + messageManager.loadFrameScript( + "data:,(" + + encodeURIComponent( + `function () { let div = content.document.createElement("div"); div.innerHTML = new Array(${NODES}).join("
") + @@ -35,7 +45,10 @@ module.exports = async function() { content.document.body.appendChild(div); sendSyncMessage("setup-test-done"); }` - ) + ")()", false); + ) + + ")()", + false + ); }); // Record the time needed to open the toolbox. diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/inspector/mutations.js b/testing/talos/talos/tests/devtools/addon/content/tests/inspector/mutations.js index 7385194960e3..ebf8d7e21a43 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/inspector/mutations.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/inspector/mutations.js @@ -4,8 +4,14 @@ "use strict"; -const { openToolbox, closeToolbox, runTest, testSetup, - testTeardown, SIMPLE_URL } = require("../head"); +const { + openToolbox, + closeToolbox, + runTest, + testSetup, + testTeardown, + SIMPLE_URL, +} = require("../head"); /** * Measure the time necessary to perform successive childList mutations in the content @@ -22,8 +28,10 @@ module.exports = async function() { const LIMIT = 100; const DELAY = 5; - messageManager.loadFrameScript("data:,(" + encodeURIComponent( - `function () { + messageManager.loadFrameScript( + "data:,(" + + encodeURIComponent( + `function () { const LIMIT = ${LIMIT}; addMessageListener("start-mutations-test", function () { let addElement = function(index) { @@ -38,7 +46,10 @@ module.exports = async function() { addElement(0); }); }` - ) + ")()", false); + ) + + ")()", + false + ); let test = runTest("inspector.mutations"); diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/inspector/simple.js b/testing/talos/talos/tests/devtools/addon/content/tests/inspector/simple.js index 177c7ca63cb9..bce5fefbf642 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/inspector/simple.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/inspector/simple.js @@ -5,8 +5,13 @@ "use strict"; const { reloadInspectorAndLog } = require("./inspector-helpers"); -const { openToolboxAndLog, closeToolboxAndLog, testSetup, - testTeardown, SIMPLE_URL } = require("../head"); +const { + openToolboxAndLog, + closeToolboxAndLog, + testSetup, + testTeardown, + SIMPLE_URL, +} = require("../head"); module.exports = async function() { await testSetup(SIMPLE_URL); diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/netmonitor/cold-open.js b/testing/talos/talos/tests/devtools/addon/content/tests/netmonitor/cold-open.js index 78c75bc027e0..141b15589463 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/netmonitor/cold-open.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/netmonitor/cold-open.js @@ -4,8 +4,13 @@ "use strict"; -const { openToolboxAndLog, closeToolbox, testSetup, - testTeardown, SIMPLE_URL } = require("../head"); +const { + openToolboxAndLog, + closeToolbox, + testSetup, + testTeardown, + SIMPLE_URL, +} = require("../head"); module.exports = async function() { await testSetup(SIMPLE_URL); diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/netmonitor/complicated.js b/testing/talos/talos/tests/devtools/addon/content/tests/netmonitor/complicated.js index 2e685e91bf8a..6746b82cb536 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/netmonitor/complicated.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/netmonitor/complicated.js @@ -4,18 +4,30 @@ "use strict"; -const { openToolboxAndLog, closeToolboxAndLog, reloadPageAndLog, testSetup, - testTeardown, COMPLICATED_URL } = require("../head"); +const { + openToolboxAndLog, + closeToolboxAndLog, + reloadPageAndLog, + testSetup, + testTeardown, + COMPLICATED_URL, +} = require("../head"); const { exportHar, waitForNetworkRequests } = require("./netmonitor-helpers"); const EXPECTED_REQUESTS = 280; module.exports = async function() { await testSetup(COMPLICATED_URL); - const toolbox = await openToolboxAndLog("complicated.netmonitor", "netmonitor"); + const toolbox = await openToolboxAndLog( + "complicated.netmonitor", + "netmonitor" + ); - const requestsDone = waitForNetworkRequests("complicated.netmonitor", toolbox, - EXPECTED_REQUESTS); + const requestsDone = waitForNetworkRequests( + "complicated.netmonitor", + toolbox, + EXPECTED_REQUESTS + ); await reloadPageAndLog("complicated.netmonitor", toolbox); await requestsDone; diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/netmonitor/netmonitor-helpers.js b/testing/talos/talos/tests/devtools/addon/content/tests/netmonitor/netmonitor-helpers.js index a99494664921..70eee6eb6702 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/netmonitor/netmonitor-helpers.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/netmonitor/netmonitor-helpers.js @@ -44,7 +44,10 @@ async function waitForAllRequestsFinished(expectedRequests) { function maybeResolve() { // Have all the requests finished yet? - if (payloadReady >= expectedRequests && timingsUpdated >= expectedRequests) { + if ( + payloadReady >= expectedRequests && + timingsUpdated >= expectedRequests + ) { // All requests are done - unsubscribe from events and resolve! window.api.off(EVENTS.PAYLOAD_READY, onPayloadReady); window.api.off(EVENTS.RECEIVED_EVENT_TIMINGS, onTimingsUpdated); @@ -57,7 +60,11 @@ async function waitForAllRequestsFinished(expectedRequests) { }); } -exports.waitForNetworkRequests = async function(label, toolbox, expectedRequests) { +exports.waitForNetworkRequests = async function( + label, + toolbox, + expectedRequests +) { let test = runTest(label + ".requestsFinished.DAMP"); await waitForAllRequestsFinished(expectedRequests); test.done(); diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/netmonitor/simple.js b/testing/talos/talos/tests/devtools/addon/content/tests/netmonitor/simple.js index b6b50616f0de..e84e820225c0 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/netmonitor/simple.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/netmonitor/simple.js @@ -4,8 +4,14 @@ "use strict"; -const { openToolboxAndLog, closeToolboxAndLog, reloadPageAndLog, testSetup, - testTeardown, SIMPLE_URL } = require("../head"); +const { + openToolboxAndLog, + closeToolboxAndLog, + reloadPageAndLog, + testSetup, + testTeardown, + SIMPLE_URL, +} = require("../head"); const { exportHar, waitForNetworkRequests } = require("./netmonitor-helpers"); const EXPECTED_REQUESTS = 1; @@ -14,8 +20,11 @@ module.exports = async function() { await testSetup(SIMPLE_URL); const toolbox = await openToolboxAndLog("simple.netmonitor", "netmonitor"); - const requestsDone = waitForNetworkRequests("simple.netmonitor", toolbox, - EXPECTED_REQUESTS); + const requestsDone = waitForNetworkRequests( + "simple.netmonitor", + toolbox, + EXPECTED_REQUESTS + ); await reloadPageAndLog("simple.netmonitor", toolbox); await requestsDone; diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/server/actor.js b/testing/talos/talos/tests/devtools/addon/content/tests/server/actor.js index daf436821e84..47ea88e97735 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/server/actor.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/server/actor.js @@ -21,4 +21,3 @@ exports.DampTestActor = protocol.ActorClassWithSpec(dampTestSpec, { return arg; }, }); - diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/server/protocol.js b/testing/talos/talos/tests/devtools/addon/content/tests/server/protocol.js index d4e4248d3b76..f7d1c01f76cd 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/server/protocol.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/server/protocol.js @@ -4,8 +4,14 @@ "use strict"; -const { openToolbox, closeToolbox, testSetup, testTeardown, runTest, - SIMPLE_URL } = require("../head"); +const { + openToolbox, + closeToolbox, + testSetup, + testTeardown, + runTest, + SIMPLE_URL, +} = require("../head"); const protocol = require("devtools/shared/protocol"); const { FrontClassWithSpec } = protocol; @@ -34,8 +40,10 @@ module.exports = async function() { let url = module.uri.replace(/protocol\.js$/, "actor.js"); // Register a test actor within the content process - messageManager.loadFrameScript("data:,(" + encodeURIComponent( - `function () { + messageManager.loadFrameScript( + "data:,(" + + encodeURIComponent( + `function () { const { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm", {}); const { ActorRegistry } = require("devtools/server/actors/utils/actor-registry"); @@ -45,7 +53,10 @@ module.exports = async function() { type: { target: true } }); }` - ) + ")()", true); + ) + + ")()", + true + ); // Create test payloads let bigString = ""; @@ -58,7 +69,7 @@ module.exports = async function() { bigObject["attribute-" + i] = bigString; } - let bigArray = Array.from({length: ARRAY_SIZE}, (_, i) => bigObject); + let bigArray = Array.from({ length: ARRAY_SIZE }, (_, i) => bigObject); // Open against options to avoid noise from tools let toolbox = await openToolbox("options"); diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/server/spec.js b/testing/talos/talos/tests/devtools/addon/content/tests/server/spec.js index d0d7ffd1270a..92a67535e1ed 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/server/spec.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/server/spec.js @@ -5,7 +5,7 @@ "use strict"; const protocol = require("devtools/shared/protocol"); -const {Arg, Option, RetVal, types} = protocol; +const { Arg, Option, RetVal, types } = protocol; types.addDictType("test.option", { "attribute-1": "string", @@ -22,7 +22,7 @@ const dampTestSpec = protocol.generateActorSpec({ typeName: "dampTest", events: { - "testEvent": { arg: Arg(0, "array:json") }, + testEvent: { arg: Arg(0, "array:json") }, }, methods: { diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/styleeditor/complicated.js b/testing/talos/talos/tests/devtools/addon/content/tests/styleeditor/complicated.js index 3573f30b4a28..b2d90791a8cf 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/styleeditor/complicated.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/styleeditor/complicated.js @@ -4,12 +4,21 @@ "use strict"; -const { openToolboxAndLog, closeToolboxAndLog, reloadPageAndLog, testSetup, - testTeardown, COMPLICATED_URL } = require("../head"); +const { + openToolboxAndLog, + closeToolboxAndLog, + reloadPageAndLog, + testSetup, + testTeardown, + COMPLICATED_URL, +} = require("../head"); module.exports = async function() { await testSetup(COMPLICATED_URL); - const toolbox = await openToolboxAndLog("complicated.styleeditor", "styleeditor"); + const toolbox = await openToolboxAndLog( + "complicated.styleeditor", + "styleeditor" + ); await reloadPageAndLog("complicated.styleeditor", toolbox); await closeToolboxAndLog("complicated.styleeditor", toolbox); await testTeardown(); diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/styleeditor/simple.js b/testing/talos/talos/tests/devtools/addon/content/tests/styleeditor/simple.js index ae9a124c2b7c..ed30bd87e066 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/styleeditor/simple.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/styleeditor/simple.js @@ -4,8 +4,14 @@ "use strict"; -const { openToolboxAndLog, closeToolboxAndLog, reloadPageAndLog, testSetup, - testTeardown, SIMPLE_URL } = require("../head"); +const { + openToolboxAndLog, + closeToolboxAndLog, + reloadPageAndLog, + testSetup, + testTeardown, + SIMPLE_URL, +} = require("../head"); module.exports = async function() { await testSetup(SIMPLE_URL); diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/toolbox/panels-in-background.js b/testing/talos/talos/tests/devtools/addon/content/tests/toolbox/panels-in-background.js index 64a54aa27571..1bc252031ef2 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/toolbox/panels-in-background.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/toolbox/panels-in-background.js @@ -5,8 +5,14 @@ "use strict"; const { EVENTS } = require("devtools/client/netmonitor/src/constants"); -const { openToolbox, closeToolbox, reloadPageAndLog, testSetup, - testTeardown, PAGES_BASE_URL } = require("../head"); +const { + openToolbox, + closeToolbox, + reloadPageAndLog, + testSetup, + testTeardown, + PAGES_BASE_URL, +} = require("../head"); module.exports = async function() { await testSetup(PAGES_BASE_URL + "custom/panels-in-background/index.html"); diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/autocomplete.js b/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/autocomplete.js index 40b21cead13d..adb401d26957 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/autocomplete.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/autocomplete.js @@ -73,4 +73,3 @@ function setJsTermValueForCompletion(jsterm, value) { jsterm._setValue(value); jsterm.props.autocompleteUpdate(); } - diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/bulklog.js b/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/bulklog.js index 8420db1b2fbf..e0e70894e615 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/bulklog.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/bulklog.js @@ -4,8 +4,15 @@ "use strict"; -const { openToolbox, closeToolbox, getBrowserWindow, runTest, testSetup, - testTeardown, SIMPLE_URL } = require("../head"); +const { + openToolbox, + closeToolbox, + getBrowserWindow, + runTest, + testSetup, + testTeardown, + SIMPLE_URL, +} = require("../head"); module.exports = async function() { let TOTAL_MESSAGES = 10; @@ -30,15 +37,20 @@ module.exports = async function() { // Load a frame script using a data URI so we can do logs // from the page. So this is running in content. - messageManager.loadFrameScript("data:,(" + encodeURIComponent( - `function () { + messageManager.loadFrameScript( + "data:,(" + + encodeURIComponent( + `function () { addMessageListener("do-logs", function () { for (var i = 0; i < ${TOTAL_MESSAGES}; i++) { content.console.log('damp', i+1, content); } }); }` - ) + ")()", true); + ) + + ")()", + true + ); let test = runTest("console.bulklog"); // Kick off the logging diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/cold-open.js b/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/cold-open.js index edc6551b0d70..a6c608c44598 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/cold-open.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/cold-open.js @@ -4,8 +4,13 @@ "use strict"; -const { openToolboxAndLog, closeToolbox, testSetup, - testTeardown, SIMPLE_URL } = require("../head"); +const { + openToolboxAndLog, + closeToolbox, + testSetup, + testTeardown, + SIMPLE_URL, +} = require("../head"); module.exports = async function() { await testSetup(SIMPLE_URL); diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/complicated.js b/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/complicated.js index 7cbb8960983c..74165e200a7c 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/complicated.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/complicated.js @@ -4,8 +4,13 @@ "use strict"; -const { openToolboxAndLog, closeToolboxAndLog, testSetup, - testTeardown, COMPLICATED_URL } = require("../head"); +const { + openToolboxAndLog, + closeToolboxAndLog, + testSetup, + testTeardown, + COMPLICATED_URL, +} = require("../head"); const { reloadConsoleAndLog } = require("./webconsole-helpers"); const EXPECTED_MESSAGES = 7; diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/custom.js b/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/custom.js index 112a106a7aa7..7f81fe39f799 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/custom.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/custom.js @@ -4,13 +4,20 @@ "use strict"; -const { openToolboxAndLog, closeToolboxAndLog, testSetup, - testTeardown, PAGES_BASE_URL } = require("../head"); +const { + openToolboxAndLog, + closeToolboxAndLog, + testSetup, + testTeardown, + PAGES_BASE_URL, +} = require("../head"); const { reloadConsoleAndLog } = require("./webconsole-helpers"); module.exports = async function() { // These numbers controls the number of console api calls we do in the test - let sync = 250, stream = 250, async = 250; + let sync = 250, + stream = 250, + async = 250; let params = `?sync=${sync}&stream=${stream}&async=${async}`; let url = PAGES_BASE_URL + "custom/console/index.html" + params; diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/objectexpand.js b/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/objectexpand.js index 51f0f5958872..506ceea789e9 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/objectexpand.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/objectexpand.js @@ -4,8 +4,15 @@ "use strict"; -const { openToolbox, closeToolboxAndLog, getBrowserWindow, runTest, testSetup, - testTeardown, SIMPLE_URL } = require("../head"); +const { + openToolbox, + closeToolboxAndLog, + getBrowserWindow, + runTest, + testSetup, + testTeardown, + SIMPLE_URL, +} = require("../head"); module.exports = async function() { let tab = await testSetup(SIMPLE_URL); @@ -26,8 +33,10 @@ module.exports = async function() { // Load a frame script using a data URI so we can do logs // from the page. - messageManager.loadFrameScript("data:,(" + encodeURIComponent( - `function () { + messageManager.loadFrameScript( + "data:,(" + + encodeURIComponent( + `function () { addMessageListener("do-dir", function () { content.console.dir(Array.from({length:333}).reduce((res, _, i)=> { res["item_" + i] = "alphanum-indexed-" + i; @@ -37,7 +46,10 @@ module.exports = async function() { }, {})); }); }` - ) + ")()", true); + ) + + ")()", + true + ); let test = runTest("console.objectexpand"); // Kick off the logging @@ -50,7 +62,7 @@ module.exports = async function() { if (tree.querySelectorAll(".node").length === 1) { // If this is the case, we wait for the properties to be fetched and displayed. await new Promise(resolve => { - const observer = new (getBrowserWindow().MutationObserver)(mutations => { + const observer = new (getBrowserWindow()).MutationObserver(mutations => { resolve(mutations); observer.disconnect(); }); @@ -66,5 +78,3 @@ module.exports = async function() { await testTeardown(); }; - - diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/openwithcache.js b/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/openwithcache.js index 5ea88ac3baa4..05eb9b041249 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/openwithcache.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/openwithcache.js @@ -4,8 +4,13 @@ "use strict"; -const { openToolboxAndLog, closeToolbox, testSetup, - testTeardown, SIMPLE_URL } = require("../head"); +const { + openToolboxAndLog, + closeToolbox, + testSetup, + testTeardown, + SIMPLE_URL, +} = require("../head"); const TOTAL_MESSAGES = 100; @@ -14,18 +19,20 @@ module.exports = async function() { // Load a frame script using a data URI so we can do logs // from the page. So this is running in content. - tab.linkedBrowser.messageManager.loadFrameScript("data:,(" + encodeURIComponent(` + tab.linkedBrowser.messageManager.loadFrameScript( + "data:,(" + + encodeURIComponent(` function () { for (var i = 0; i < ${TOTAL_MESSAGES}; i++) { content.console.log('damp', i+1, content); } - }` - ) + ")()", true); + }`) + + ")()", + true + ); await openToolboxAndLog("console.openwithcache", "webconsole"); await closeToolbox(); await testTeardown(); }; - - diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/simple.js b/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/simple.js index 077af885d006..1a521a353301 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/simple.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/simple.js @@ -4,8 +4,13 @@ "use strict"; -const { openToolboxAndLog, closeToolboxAndLog, testSetup, - testTeardown, SIMPLE_URL } = require("../head"); +const { + openToolboxAndLog, + closeToolboxAndLog, + testSetup, + testTeardown, + SIMPLE_URL, +} = require("../head"); const { reloadConsoleAndLog } = require("./webconsole-helpers"); const EXPECTED_MESSAGES = 1; diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/streamlog.js b/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/streamlog.js index f1e1a85959fe..97551f9eaaee 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/streamlog.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/streamlog.js @@ -4,8 +4,14 @@ "use strict"; -const { openToolbox, closeToolbox, logTestResult, testSetup, - testTeardown, SIMPLE_URL } = require("../head"); +const { + openToolbox, + closeToolbox, + logTestResult, + testSetup, + testTeardown, + SIMPLE_URL, +} = require("../head"); // Log a stream of console messages, 1 per rAF. Then record the average // time per rAF. The idea is that the console being slow can slow down @@ -19,8 +25,10 @@ module.exports = async function() { // Load a frame script using a data URI so we can do logs // from the page. So this is running in content. - messageManager.loadFrameScript("data:,(" + encodeURIComponent( - `function () { + messageManager.loadFrameScript( + "data:,(" + + encodeURIComponent( + `function () { let count = 0; let startTime = content.performance.now(); function log() { @@ -40,10 +48,13 @@ module.exports = async function() { } log(); }` - ) + ")()", true); + ) + + ")()", + true + ); let avgTime = await new Promise(resolve => { - messageManager.addMessageListener("done", (e) => { + messageManager.addMessageListener("done", e => { resolve(e.data); }); }); diff --git a/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/typing.js b/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/typing.js index 69907cd18b87..8d3a6b4b5327 100644 --- a/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/typing.js +++ b/testing/talos/talos/tests/devtools/addon/content/tests/webconsole/typing.js @@ -32,8 +32,9 @@ module.exports = async function() { const { jsterm } = hud; // Wait for all the logs to be displayed. - await waitFor(() => - hud.ui.outputNode.querySelectorAll(".message").length >= LOGS_NUMBER); + await waitFor( + () => hud.ui.outputNode.querySelectorAll(".message").length >= LOGS_NUMBER + ); jsterm.focus(); @@ -55,8 +56,9 @@ module.exports = async function() { await onPopupClosed; // Let's clear the output as it looks like not doing it could impact the next tests. - const onMessagesCleared = waitFor(() => - hud.ui.outputNode.querySelectorAll(".message").length === 0); + const onMessagesCleared = waitFor( + () => hud.ui.outputNode.querySelectorAll(".message").length === 0 + ); hud.ui.clearOutput(); await onMessagesCleared; diff --git a/testing/talos/talos/tests/devtools/addon/driver.js b/testing/talos/talos/tests/devtools/addon/driver.js index 0244924021f0..1caa41e2d34a 100644 --- a/testing/talos/talos/tests/devtools/addon/driver.js +++ b/testing/talos/talos/tests/devtools/addon/driver.js @@ -1,6 +1,10 @@ /* eslint-env webextensions */ addEventListener("load", () => { browser.damp.startTest().then(results => { - window.tpRecordTime(results.testResults.join(","), 0, results.testNames.join(",")); + window.tpRecordTime( + results.testResults.join(","), + 0, + results.testNames.join(",") + ); }); }); diff --git a/testing/talos/talos/tests/perf-reftest-singletons/util.js b/testing/talos/talos/tests/perf-reftest-singletons/util.js index 22327ff04681..339f5b13ee3e 100644 --- a/testing/talos/talos/tests/perf-reftest-singletons/util.js +++ b/testing/talos/talos/tests/perf-reftest-singletons/util.js @@ -20,8 +20,9 @@ function build_dom(n, elemName, options) { var leftSize = Math.floor(n / 2); var rightSize = Math.floor((n - 1) / 2); ours.appendChild(build_dom(leftSize, elemNameLeft, options)); - if (rightSize > 0) + if (rightSize > 0) { ours.appendChild(build_dom(rightSize, elemNameRight, options)); + } } return ours; } @@ -29,16 +30,25 @@ function build_dom(n, elemName, options) { function build_rule(selector, selectorRepeat, declaration, ruleRepeat) { ruleRepeat = ruleRepeat || 1; var s = document.createElement("style"); - var rule = Array(selectorRepeat).fill(selector).join(", ") + declaration; - s.textContent = Array(ruleRepeat).fill(rule).join("\n\n"); + var rule = + Array(selectorRepeat) + .fill(selector) + .join(", ") + declaration; + s.textContent = Array(ruleRepeat) + .fill(rule) + .join("\n\n"); return s; } function build_text(word, wordRepeat, paraRepeat) { wordRepeat = wordRepeat || 1; paraRepeat = paraRepeat || 1; - let para = Array(wordRepeat).fill(word).join(" "); - return Array(paraRepeat).fill(para).join("\n"); + let para = Array(wordRepeat) + .fill(word) + .join(" "); + return Array(paraRepeat) + .fill(para) + .join("\n"); } function flush_style(element) { @@ -77,7 +87,10 @@ function perf_finish() { window.tpRecordTime(end - start, start); } else if (window.parent && window.parent.report_perf_reftest_time) { // Running in the perf-reftest runner. - window.parent.report_perf_reftest_time({ type: "time", value: end - start }); + window.parent.report_perf_reftest_time({ + type: "time", + value: end - start, + }); } else { // Running standalone; just alert. console.log(end); diff --git a/testing/talos/talos/tests/perf-reftest/util.js b/testing/talos/talos/tests/perf-reftest/util.js index 22327ff04681..339f5b13ee3e 100644 --- a/testing/talos/talos/tests/perf-reftest/util.js +++ b/testing/talos/talos/tests/perf-reftest/util.js @@ -20,8 +20,9 @@ function build_dom(n, elemName, options) { var leftSize = Math.floor(n / 2); var rightSize = Math.floor((n - 1) / 2); ours.appendChild(build_dom(leftSize, elemNameLeft, options)); - if (rightSize > 0) + if (rightSize > 0) { ours.appendChild(build_dom(rightSize, elemNameRight, options)); + } } return ours; } @@ -29,16 +30,25 @@ function build_dom(n, elemName, options) { function build_rule(selector, selectorRepeat, declaration, ruleRepeat) { ruleRepeat = ruleRepeat || 1; var s = document.createElement("style"); - var rule = Array(selectorRepeat).fill(selector).join(", ") + declaration; - s.textContent = Array(ruleRepeat).fill(rule).join("\n\n"); + var rule = + Array(selectorRepeat) + .fill(selector) + .join(", ") + declaration; + s.textContent = Array(ruleRepeat) + .fill(rule) + .join("\n\n"); return s; } function build_text(word, wordRepeat, paraRepeat) { wordRepeat = wordRepeat || 1; paraRepeat = paraRepeat || 1; - let para = Array(wordRepeat).fill(word).join(" "); - return Array(paraRepeat).fill(para).join("\n"); + let para = Array(wordRepeat) + .fill(word) + .join(" "); + return Array(paraRepeat) + .fill(para) + .join("\n"); } function flush_style(element) { @@ -77,7 +87,10 @@ function perf_finish() { window.tpRecordTime(end - start, start); } else if (window.parent && window.parent.report_perf_reftest_time) { // Running in the perf-reftest runner. - window.parent.report_perf_reftest_time({ type: "time", value: end - start }); + window.parent.report_perf_reftest_time({ + type: "time", + value: end - start, + }); } else { // Running standalone; just alert. console.log(end); diff --git a/testing/talos/talos/tests/tabpaint/api.js b/testing/talos/talos/tests/tabpaint/api.js index 443040f2eee3..3d8fa0a319b8 100644 --- a/testing/talos/talos/tests/tabpaint/api.js +++ b/testing/talos/talos/tests/tabpaint/api.js @@ -20,18 +20,21 @@ * for certain types of links (_blank links for example) to open new tabs. */ -ChromeUtils.defineModuleGetter(this, "Services", - "resource://gre/modules/Services.jsm"); -ChromeUtils.defineModuleGetter(this, "TalosParentProfiler", - "resource://talos-powers/TalosParentProfiler.jsm"); +ChromeUtils.defineModuleGetter( + this, + "Services", + "resource://gre/modules/Services.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "TalosParentProfiler", + "resource://talos-powers/TalosParentProfiler.jsm" +); const ANIMATION_PREF = "toolkit.cosmeticAnimations.enabled"; const MULTI_OPT_OUT_PREF = "dom.ipc.multiOptOut"; -const MESSAGES = [ - "TabPaint:Go", - "TabPaint:Painted", -]; +const MESSAGES = ["TabPaint:Go", "TabPaint:Painted"]; /* globals ExtensionAPI */ this.tabpaint = class extends ExtensionAPI { @@ -50,8 +53,10 @@ this.tabpaint = class extends ExtensionAPI { this.originalAnimate = Services.prefs.getBoolPref(ANIMATION_PREF); Services.prefs.setBoolPref(ANIMATION_PREF, false); - Services.prefs.setIntPref(MULTI_OPT_OUT_PREF, - Services.appinfo.E10S_MULTI_EXPERIMENT); + Services.prefs.setIntPref( + MULTI_OPT_OUT_PREF, + Services.appinfo.E10S_MULTI_EXPERIMENT + ); /** * We'll store a callback here to be fired once the target page @@ -91,7 +96,7 @@ this.tabpaint = class extends ExtensionAPI { let tab = gBrowser.getTabForBrowser(browser); let delta = msg.data.delta; - this.paintCallback({tab, delta}); + this.paintCallback({ tab, delta }); break; } } @@ -131,7 +136,7 @@ this.tabpaint = class extends ExtensionAPI { triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(), }); - let {tab, delta} = await this.whenTabShown(); + let { tab, delta } = await this.whenTabShown(); TalosParentProfiler.pause("tabpaint parent end"); await this.removeTab(tab); return delta; @@ -153,7 +158,7 @@ this.tabpaint = class extends ExtensionAPI { Services.mm.broadcastAsyncMessage("TabPaint:OpenFromContent"); - let {tab, delta} = await this.whenTabShown(); + let { tab, delta } = await this.whenTabShown(); TalosParentProfiler.pause("tabpaint content end"); await this.removeTab(tab); return delta; @@ -166,7 +171,7 @@ this.tabpaint = class extends ExtensionAPI { * @return Promise */ whenTabShown() { - return new Promise((resolve) => { + return new Promise(resolve => { this.paintCallback = resolve; }); } @@ -181,14 +186,18 @@ this.tabpaint = class extends ExtensionAPI { * @return Promise */ removeTab(tab) { - return new Promise((resolve) => { - let {messageManager: mm, frameLoader} = tab.linkedBrowser; - mm.addMessageListener("SessionStore:update", function onMessage(msg) { - if (msg.targetFrameLoader == frameLoader && msg.data.isFinal) { - mm.removeMessageListener("SessionStore:update", onMessage); - resolve(); - } - }, true); + return new Promise(resolve => { + let { messageManager: mm, frameLoader } = tab.linkedBrowser; + mm.addMessageListener( + "SessionStore:update", + function onMessage(msg) { + if (msg.targetFrameLoader == frameLoader && msg.data.isFinal) { + mm.removeMessageListener("SessionStore:update", onMessage); + resolve(); + } + }, + true + ); tab.ownerGlobal.gBrowser.removeTab(tab); }); diff --git a/testing/talos/talos/tests/tabpaint/framescript.js b/testing/talos/talos/tests/tabpaint/framescript.js index 7a84933eb19b..b8ac5c566bd6 100644 --- a/testing/talos/talos/tests/tabpaint/framescript.js +++ b/testing/talos/talos/tests/tabpaint/framescript.js @@ -1,80 +1,100 @@ (function() { - addEventListener("load", loadevt => { - if (!content.location.pathname.endsWith("target.html")) { - return; - } - - /** - * When a page is loaded, we expect a search string to be - * appended with the "starting time" (in ms) of when the tab - * was opened. - * - * Example: target.html?1457063506846 - */ - let opened = parseInt(content.location.search.substring(1), 10); - - addEventListener("MozAfterPaint", function onPaint(e) { - // Bug 1371332 - sometimes, MozAfterPaint events fire - // for "empty" paints, where nothing has actually been - // painted. We can detect that by looking at the rect - // for the region that has painted. - let rect = e.boundingClientRect; - if (!rect.width && !rect.height) { + addEventListener( + "load", + loadevt => { + if (!content.location.pathname.endsWith("target.html")) { return; } - removeEventListener("MozAfterPaint", onPaint); + /** + * When a page is loaded, we expect a search string to be + * appended with the "starting time" (in ms) of when the tab + * was opened. + * + * Example: target.html?1457063506846 + */ + let opened = parseInt(content.location.search.substring(1), 10); - // The MozAfterPaint event comes with a paintTimeStamp - // which tells us when in this content's lifetime the - // paint actually occurred. Note that this is not a - // measurement of when this paint occurred from - // the UNIX epoch. This makes it a little tricky to - // calculate when the paint actually occurred relative - // to the starting time that's been appended to the - // page's URL. - // - // Thankfully, the PerformanceTiming API gives us a - // sense of when this page's lifetime started, relative - // to the UNIX epoch - the "fetchStart". Taking that - // time and adding the paintTimeStamp should give us - // a pretty decent approximation of when since the - // UNIX epoch the paint actually occurred for this - // content. - // - // We can then subtract the starting time to get the - // delta, which should now represent the time it took - // from requesting that the tab be opened, to the - // paint occurring within the tab. - let fetchStart = content.performance.timing.fetchStart; - let presented = fetchStart + e.paintTimeStamp; - let delta = presented - opened; + addEventListener("MozAfterPaint", function onPaint(e) { + // Bug 1371332 - sometimes, MozAfterPaint events fire + // for "empty" paints, where nothing has actually been + // painted. We can detect that by looking at the rect + // for the region that has painted. + let rect = e.boundingClientRect; + if (!rect.width && !rect.height) { + return; + } - sendAsyncMessage("TabPaint:Painted", { delta }); - }); - }, true); + removeEventListener("MozAfterPaint", onPaint); - addEventListener("TabPaint:Ping", e => { - let evt = new content.CustomEvent("TabPaint:Pong", {bubbles: true}); - content.dispatchEvent(evt); - }, false, true); + // The MozAfterPaint event comes with a paintTimeStamp + // which tells us when in this content's lifetime the + // paint actually occurred. Note that this is not a + // measurement of when this paint occurred from + // the UNIX epoch. This makes it a little tricky to + // calculate when the paint actually occurred relative + // to the starting time that's been appended to the + // page's URL. + // + // Thankfully, the PerformanceTiming API gives us a + // sense of when this page's lifetime started, relative + // to the UNIX epoch - the "fetchStart". Taking that + // time and adding the paintTimeStamp should give us + // a pretty decent approximation of when since the + // UNIX epoch the paint actually occurred for this + // content. + // + // We can then subtract the starting time to get the + // delta, which should now represent the time it took + // from requesting that the tab be opened, to the + // paint occurring within the tab. + let fetchStart = content.performance.timing.fetchStart; + let presented = fetchStart + e.paintTimeStamp; + let delta = presented - opened; - addEventListener("TabPaint:Go", e => { - sendAsyncMessage("TabPaint:Go", {target: e.detail.target}); - }, false, true); + sendAsyncMessage("TabPaint:Painted", { delta }); + }); + }, + true + ); + + addEventListener( + "TabPaint:Ping", + e => { + let evt = new content.CustomEvent("TabPaint:Pong", { bubbles: true }); + content.dispatchEvent(evt); + }, + false, + true + ); + + addEventListener( + "TabPaint:Go", + e => { + sendAsyncMessage("TabPaint:Go", { target: e.detail.target }); + }, + false, + true + ); addMessageListener("TabPaint:OpenFromContent", msg => { - let evt = new content.CustomEvent("TabPaint:OpenFromContent", - {bubbles: true}); + let evt = new content.CustomEvent("TabPaint:OpenFromContent", { + bubbles: true, + }); content.dispatchEvent(evt); }); addMessageListener("TabPaint:FinalResults", msg => { - let evt = Cu.cloneInto({ - bubbles: true, - detail: msg.data, - }, content); + let evt = Cu.cloneInto( + { + bubbles: true, + detail: msg.data, + }, + content + ); - content.dispatchEvent(new content.CustomEvent("TabPaint:FinalResults", evt)); + content.dispatchEvent( + new content.CustomEvent("TabPaint:FinalResults", evt) + ); }); })(); diff --git a/testing/talos/talos/tests/tabswitch/api.js b/testing/talos/talos/tests/tabswitch/api.js index e644eedf6761..3ce54879b2ce 100644 --- a/testing/talos/talos/tests/tabswitch/api.js +++ b/testing/talos/talos/tests/tabswitch/api.js @@ -2,8 +2,10 @@ /* globals ExtensionAPI */ -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); -const {RemotePages} = ChromeUtils.import("resource://gre/modules/remotepagemanager/RemotePageManagerParent.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { RemotePages } = ChromeUtils.import( + "resource://gre/modules/remotepagemanager/RemotePageManagerParent.jsm" +); let context = {}; let TalosParentProfiler; @@ -17,7 +19,7 @@ let TalosParentProfiler; * @returns Promise */ function waitForDelayedStartup(win) { - return new Promise((resolve) => { + return new Promise(resolve => { const topic = "browser-delayed-startup-finished"; Services.obs.addObserver(function onStartup(subject) { if (win == subject) { @@ -40,7 +42,7 @@ function waitForDelayedStartup(win) { * Resolves once all tabs have finished loading. */ function loadTabs(gBrowser, urls) { - return new Promise((resolve) => { + return new Promise(resolve => { gBrowser.loadTabs(urls, { inBackground: true, triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(), @@ -49,15 +51,20 @@ function loadTabs(gBrowser, urls) { let waitingToLoad = new Set(urls); let listener = { - QueryInterface: ChromeUtils.generateQI(["nsIWebProgressListener", - "nsISupportsWeakReference"]), + QueryInterface: ChromeUtils.generateQI([ + "nsIWebProgressListener", + "nsISupportsWeakReference", + ]), onStateChange(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { - let loadedState = Ci.nsIWebProgressListener.STATE_STOP | + let loadedState = + Ci.nsIWebProgressListener.STATE_STOP | Ci.nsIWebProgressListener.STATE_IS_NETWORK; - if ((aStateFlags & loadedState) == loadedState && - !aWebProgress.isLoadingDocument && - aWebProgress.isTopLevel && - Components.isSuccessCode(aStatus)) { + if ( + (aStateFlags & loadedState) == loadedState && + !aWebProgress.isLoadingDocument && + aWebProgress.isTopLevel && + Components.isSuccessCode(aStatus) + ) { dump(`Loaded: ${aBrowser.currentURI.spec}\n`); waitingToLoad.delete(aBrowser.currentURI.spec); @@ -111,11 +118,15 @@ async function switchToTab(tab) { * Resolves once the TabSwitchDone event is fired. */ function waitForTabSwitchDone(browser) { - return new Promise((resolve) => { + return new Promise(resolve => { let gBrowser = browser.ownerGlobal.gBrowser; - gBrowser.addEventListener("TabSwitchDone", function onTabSwitchDone() { - resolve(); - }, {once: true}); + gBrowser.addEventListener( + "TabSwitchDone", + function onTabSwitchDone() { + resolve(); + }, + { once: true } + ); }); } @@ -132,12 +143,16 @@ function waitForTabSwitchDone(browser) { * milliseconds since midnight 01 January, 1970 UTC. */ function waitForContentPresented(browser) { - return new Promise((resolve) => { - browser.addEventListener("MozLayerTreeReady", function onLayersReady(event) { - let now = Cu.now(); - TalosParentProfiler.mark("MozLayerTreeReady seen by tabswitch"); - resolve(now); - }, { once: true }); + return new Promise(resolve => { + browser.addEventListener( + "MozLayerTreeReady", + function onLayersReady(event) { + let now = Cu.now(); + TalosParentProfiler.mark("MozLayerTreeReady seen by tabswitch"); + resolve(now); + }, + { once: true } + ); }); } @@ -156,13 +171,18 @@ function forceGC(win, browser) { // TODO: Find a better way of letting Talos force GC in the child. We're // stealing a chunk of pageloader to do this, and we should probably put // something into TalosPowers instead. - browser.messageManager.loadFrameScript("chrome://pageloader/content/talos-content.js", false); + browser.messageManager.loadFrameScript( + "chrome://pageloader/content/talos-content.js", + false + ); win.windowUtils.garbageCollect(); - return new Promise((resolve) => { + return new Promise(resolve => { let mm = browser.messageManager; - mm.addMessageListener("Talos:ForceGC:OK", function onTalosContentForceGC(msg) { + mm.addMessageListener("Talos:ForceGC:OK", function onTalosContentForceGC( + msg + ) { mm.removeMessageListener("Talos:ForceGC:OK", onTalosContentForceGC); resolve(); }); @@ -183,12 +203,17 @@ function forceGC(win, browser) { */ async function test(window) { if (!window.gMultiProcessBrowser) { - dump("** The tabswitch Talos test does not support running in non-e10s mode " + - "anymore! Bailing out!\n"); + dump( + "** The tabswitch Talos test does not support running in non-e10s mode " + + "anymore! Bailing out!\n" + ); return; } - ChromeUtils.import("resource://talos-powers/TalosParentProfiler.jsm", context); + ChromeUtils.import( + "resource://talos-powers/TalosParentProfiler.jsm", + context + ); TalosParentProfiler = context.TalosParentProfiler; let testURLs = []; @@ -199,9 +224,13 @@ async function test(window) { if (prefFile) { testURLs = handleFile(win, prefFile); } - } catch (ex) { /* error condition handled below */ } + } catch (ex) { + /* error condition handled below */ + } if (!testURLs || testURLs.length == 0) { - dump("no tabs to test, 'addon.test.tabswitch.urlfile' pref isn't set to page set path\n"); + dump( + "no tabs to test, 'addon.test.tabswitch.urlfile' pref isn't set to page set path\n" + ); return; } @@ -255,23 +284,27 @@ async function test(window) { await switchToTab(initialTab); } - let output = "" + - '' + - "Tab Switch Results" + - "

Tab switch times

" + - ""; + let output = + "" + + '' + + "Tab Switch Results" + + "

Tab switch times

" + + "
"; let time = 0; for (let i in times) { time += times[i]; - output += ""; + output += + ""; } output += "
" + testURLs[i] + "" + times[i] + "ms
" + testURLs[i] + "" + times[i] + "ms
"; dump("total tab switch time:" + time + "\n"); let resultsTab = win.gBrowser.loadOneTab( - "data:text/html;charset=utf-8," + encodeURIComponent(output), { - triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(), - }); + "data:text/html;charset=utf-8," + encodeURIComponent(output), + { + triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(), + } + ); win.gBrowser.selectedTab = resultsTab; @@ -286,8 +319,7 @@ async function test(window) { } function handleFile(win, file) { - let localFile = Cc["@mozilla.org/file/local;1"] - .createInstance(Ci.nsIFile); + let localFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile); localFile.initWithPath(file); let localURI = Services.io.newFileURI(localFile); let req = new win.XMLHttpRequest(); @@ -298,14 +330,14 @@ function handleFile(win, file) { let server = Services.prefs.getCharPref("addon.test.tabswitch.webserver"); let maxurls = Services.prefs.getIntPref("addon.test.tabswitch.maxurls"); let parent = server + "/tests/"; - let lines = req.responseText.split('
can be hidden while testing manually. in talos always with the button -let aboutNewTabService = Cc["@mozilla.org/browser/aboutnewtab-service;1"] - .getService(Ci.nsIAboutNewTabService); +let aboutNewTabService = Cc[ + "@mozilla.org/browser/aboutnewtab-service;1" +].getService(Ci.nsIAboutNewTabService); /* globals res:true, sequenceArray:true */ -function Tart() { -} +function Tart() {} Tart.prototype = { // Detector methods expect 'this' to be the detector object. @@ -46,7 +46,7 @@ Tart.prototype = { }, measureNow(e) { - return (e.type == "transitionend" && e.propertyName == "max-width"); + return e.type == "transitionend" && e.propertyName == "max-width"; }, cleanup(handler, win) { @@ -60,7 +60,7 @@ Tart.prototype = { }, measureNow(e) { - return (e.type == "customizationready"); + return e.type == "customizationready"; }, cleanup(handler, win) { @@ -94,15 +94,18 @@ Tart.prototype = { }, measureNow(e) { - return (e.type == "customization-transitionend"); + return e.type == "customization-transitionend"; }, keepListening(e) { - return (e.type != "customizationready"); + return e.type != "customizationready"; }, cleanup(handler, win) { - win.gNavToolbox.removeEventListener("customization-transitionend", handler); + win.gNavToolbox.removeEventListener( + "customization-transitionend", + handler + ); win.gNavToolbox.removeEventListener("customizationready", handler); }, }, @@ -113,7 +116,7 @@ Tart.prototype = { }, measureNow(e) { - return (e.type == "aftercustomization"); + return e.type == "aftercustomization"; }, cleanup(handler, win) { @@ -141,7 +144,6 @@ Tart.prototype = { return this._win.gBrowser.selectedTab; }, - clickCloseCurrentTab() { this._endDetection = this.tabDetector; this._win.BrowserCloseTabOrWindow(); @@ -158,10 +160,11 @@ Tart.prototype = { this._win.gBrowser.selectedTab.setAttribute("fadein", "true"); }, - addSomeChromeUriTab() { this._endDetection = this.tabDetector; - this._win.gBrowser.selectedTab = this._win.gBrowser.addTrustedTab("chrome://tart/content/blank.icon.html"); + this._win.gBrowser.selectedTab = this._win.gBrowser.addTrustedTab( + "chrome://tart/content/blank.icon.html" + ); }, triggerCustomizeEnter() { @@ -179,7 +182,6 @@ Tart.prototype = { this._win.gCustomizeMode.exit(); }, - pinTart() { return this._win.gBrowser.pinTab(this._tartTab); }, @@ -189,14 +191,27 @@ Tart.prototype = { }, USE_RECORDING_API: true, // true for Start[/Stop]FrameTimeRecording, otherwise record using rAF - which will also work with OMTC - // but (currently) also records iterations without paint invalidations + // but (currently) also records iterations without paint invalidations _win: undefined, _tartTab: undefined, _results: [], - _config: {subtests: [], repeat: 1, rest: 500, tickle: true, controlProfiler: true}, + _config: { + subtests: [], + repeat: 1, + rest: 500, + tickle: true, + controlProfiler: true, + }, - _animate(preWaitMs, triggerFunc, onDoneCallback, isReportResult, name, referenceDuration) { + _animate( + preWaitMs, + triggerFunc, + onDoneCallback, + isReportResult, + name, + referenceDuration + ) { var self = this; var recordingHandle; var timeoutId = 0; @@ -208,8 +223,9 @@ Tart.prototype = { var startRecordTimestamp; function startRecord() { if (self._config.controlProfiler) { - if (isReportResult) + if (isReportResult) { Profiler.resume(name); + } } else { Profiler.mark("Start: " + (isReportResult ? name : "[warmup]"), true); } @@ -224,7 +240,9 @@ Tart.prototype = { var last = performance.now(); function rec() { // self._win.getComputedStyle(self._win.gBrowser.selectedTab).width; // force draw - not good - too much regression - if (_abortRecording) return; + if (_abortRecording) { + return; + } var now = performance.now(); _recording.push(now - last); @@ -239,23 +257,23 @@ Tart.prototype = { var recordingAbsoluteDuration; function stopRecord() { - recordingAbsoluteDuration = window.performance.now() - startRecordTimestamp; + recordingAbsoluteDuration = + window.performance.now() - startRecordTimestamp; if (self._config.controlProfiler) { - if (isReportResult) + if (isReportResult) { Profiler.pause(name); + } } else { Profiler.mark("End: " + (isReportResult ? name : "[warmup]"), true); } if (self.USE_RECORDING_API) { - return window.windowUtils - .stopFrameTimeRecording(recordingHandle); + return window.windowUtils.stopFrameTimeRecording(recordingHandle); } _abortRecording = true; return _recording.slice(0); // clone } - function addResult(intervals) { // For each animation sequence (intervals) we report 3 values: // 1. Average interval for the last 50% of the reference duration @@ -274,7 +292,7 @@ Tart.prototype = { sumLastHalf += intervals[i]; countLastHalf++; } - if (sumMost < referenceDuration * .85) { + if (sumMost < referenceDuration * 0.85) { sumMost += intervals[i]; } } @@ -282,12 +300,14 @@ Tart.prototype = { var averageLastHalf = countLastHalf ? sumLastHalf / countLastHalf : 0; var averageOverall = intervals.length ? sum / intervals.length : 0; - var durationDiff = Math.abs(recordingAbsoluteDuration - referenceDuration); + var durationDiff = Math.abs( + recordingAbsoluteDuration - referenceDuration + ); - self._results.push({name: name + ".raw.TART", value: intervals}); // Just for display if running manually - Not collected for talos. - self._results.push({name: name + ".half.TART", value: averageLastHalf}); - self._results.push({name: name + ".all.TART", value: averageOverall}); - self._results.push({name: name + ".error.TART", value: durationDiff}); + self._results.push({ name: name + ".raw.TART", value: intervals }); // Just for display if running manually - Not collected for talos. + self._results.push({ name: name + ".half.TART", value: averageLastHalf }); + self._results.push({ name: name + ".all.TART", value: averageOverall }); + self._results.push({ name: name + ".error.TART", value: durationDiff }); } function transEnd(e) { @@ -303,7 +323,9 @@ Tart.prototype = { } // If detector supports keepListening, use it, otherwise - measurement indicates the end. - if (detector.keepListening ? detector.keepListening(e) : !isMeasureNow) { + if ( + detector.keepListening ? detector.keepListening(e) : !isMeasureNow + ) { return; } } else { @@ -319,8 +341,9 @@ Tart.prototype = { } function trigger(f) { - if (!self.USE_RECORDING_API) + if (!self.USE_RECORDING_API) { return rAF(f); + } // When using the recording API, the first interval is to last frame, which could have been a while ago. // To make sure the first interval is counted correctly, we "tickle" a widget @@ -332,8 +355,9 @@ Tart.prototype = { var i = 0; function tickleLoop() { - if (i++ < ((isReportResult && self._config.tickle) ? 17 : 0)) { - self._win.document.getElementById(id).style.opacity = i % 10 / 10 + .05; // just some style modification which will force redraw + if (i++ < (isReportResult && self._config.tickle ? 17 : 0)) { + self._win.document.getElementById(id).style.opacity = + (i % 10) / 10 + 0.05; // just some style modification which will force redraw return rAF(tickleLoop); } @@ -357,7 +381,6 @@ Tart.prototype = { }, preWaitMs); }, - _nextCommandIx: 0, _commands: [], _onSequenceComplete: 0, @@ -379,8 +402,9 @@ Tart.prototype = { }, _log(str) { - if (window.MozillaFileLogger && window.MozillaFileLogger.log) + if (window.MozillaFileLogger && window.MozillaFileLogger.log) { window.MozillaFileLogger.log(str); + } window.dump(str); }, @@ -393,7 +417,12 @@ Tart.prototype = { var out = ""; for (var i in this._results) { res = this._results[i]; - var disp = [].concat(res.value).map(function(a) { return (isNaN(a) ? -1 : a.toFixed(1)); }).join(" "); + var disp = [] + .concat(res.value) + .map(function(a) { + return isNaN(a) ? -1 : a.toFixed(1); + }) + .join(" "); out += res.name + ": " + disp + "\n"; } this._log("\n" + out); @@ -413,9 +442,9 @@ Tart.prototype = { _startTest() { // Save prefs and states which will change during the test, to get restored when done. - var origPreload = Services.prefs.getBoolPref("browser.newtab.preload"); - var origDpi = Services.prefs.getCharPref("layout.css.devPixelsPerPx"); - var origPinned = this._tartTab.pinned; + var origPreload = Services.prefs.getBoolPref("browser.newtab.preload"); + var origDpi = Services.prefs.getCharPref("layout.css.devPixelsPerPx"); + var origPinned = this._tartTab.pinned; var self = this; var animate = this._animate.bind(this); @@ -439,7 +468,13 @@ Tart.prototype = { function getMaxTabTransitionTimeMs(aTab) { let cstyle = window.getComputedStyle(aTab); try { - return 1000 * Math.max.apply(null, cstyle.transitionDuration.split(", ").map(s => parseFloat(s, 10))); + return ( + 1000 * + Math.max.apply( + null, + cstyle.transitionDuration.split(", ").map(s => parseFloat(s, 10)) + ) + ); } catch (e) { return 250; } @@ -455,7 +490,8 @@ Tart.prototype = { var custRefDuration = 0; var subtests = { - init: [ // This is called before each subtest, so it's safe to assume the following prefs: + init: [ + // This is called before each subtest, so it's safe to assume the following prefs: function() { Services.prefs.setBoolPref("browser.newtab.preload", false); self.pinTart(); @@ -468,42 +504,98 @@ Tart.prototype = { function() { Services.prefs.setBoolPref("browser.newtab.preload", origPreload); Services.prefs.setCharPref("layout.css.devPixelsPerPx", origDpi); - if (origPinned) self.pinTart(); else self.unpinTart(); + if (origPinned) { + self.pinTart(); + } else { + self.unpinTart(); + } self.makeNewTabURLChangePromise("about:newtab").then(next); }, ], simple: [ - function() { Services.prefs.setCharPref("layout.css.devPixelsPerPx", "1"); next(); }, - function() { animate(0, addTab, next); }, - function() { animate(0, closeCurrentTab, next); }, + function() { + Services.prefs.setCharPref("layout.css.devPixelsPerPx", "1"); + next(); + }, + function() { + animate(0, addTab, next); + }, + function() { + animate(0, closeCurrentTab, next); + }, - function() { animate(rest, addTab, next, true, "simple-open-DPI1", tabRefDuration); }, - function() { animate(rest, closeCurrentTab, next, true, "simple-close-DPI1", tabRefDuration); }, + function() { + animate(rest, addTab, next, true, "simple-open-DPI1", tabRefDuration); + }, + function() { + animate( + rest, + closeCurrentTab, + next, + true, + "simple-close-DPI1", + tabRefDuration + ); + }, ], iconDpi1: [ function() { Services.prefs.setCharPref("layout.css.devPixelsPerPx", "1"); - self.makeNewTabURLChangePromise("chrome://tart/content/blank.icon.html").then(next); + self + .makeNewTabURLChangePromise("chrome://tart/content/blank.icon.html") + .then(next); + }, + function() { + animate(0, addTab, next); + }, + function() { + animate(0, closeCurrentTab, next); }, - function() { animate(0, addTab, next); }, - function() { animate(0, closeCurrentTab, next); }, - function() { animate(rest, addTab, next, true, "icon-open-DPI1", tabRefDuration); }, - function() { animate(rest, closeCurrentTab, next, true, "icon-close-DPI1", tabRefDuration); }, + function() { + animate(rest, addTab, next, true, "icon-open-DPI1", tabRefDuration); + }, + function() { + animate( + rest, + closeCurrentTab, + next, + true, + "icon-close-DPI1", + tabRefDuration + ); + }, ], iconDpi2: [ function() { Services.prefs.setCharPref("layout.css.devPixelsPerPx", "2"); - self.makeNewTabURLChangePromise("chrome://tart/content/blank.icon.html").then(next); + self + .makeNewTabURLChangePromise("chrome://tart/content/blank.icon.html") + .then(next); + }, + function() { + animate(0, addTab, next); + }, + function() { + animate(0, closeCurrentTab, next); }, - function() { animate(0, addTab, next); }, - function() { animate(0, closeCurrentTab, next); }, - function() { animate(rest, addTab, next, true, "icon-open-DPI2", tabRefDuration); }, - function() { animate(rest, closeCurrentTab, next, true, "icon-close-DPI2", tabRefDuration); }, + function() { + animate(rest, addTab, next, true, "icon-open-DPI2", tabRefDuration); + }, + function() { + animate( + rest, + closeCurrentTab, + next, + true, + "icon-close-DPI2", + tabRefDuration + ); + }, ], newtabNoPreload: [ @@ -512,8 +604,19 @@ Tart.prototype = { Services.prefs.setBoolPref("browser.newtab.preload", false); self.makeNewTabURLChangePromise("about:newtab").then(next); }, - function() { animate(rest, addTab, next, true, "newtab-open-preload-no", tabRefDuration); }, - function() { animate(0, closeCurrentTab, next); }, + function() { + animate( + rest, + addTab, + next, + true, + "newtab-open-preload-no", + tabRefDuration + ); + }, + function() { + animate(0, closeCurrentTab, next); + }, ], newtabYesPreload: [ @@ -522,108 +625,378 @@ Tart.prototype = { Services.prefs.setBoolPref("browser.newtab.preload", true); self.makeNewTabURLChangePromise("about:newtab").then(next); }, - function() { animate(0, addTab, next); }, - function() { animate(0, closeCurrentTab, next); }, + function() { + animate(0, addTab, next); + }, + function() { + animate(0, closeCurrentTab, next); + }, - function() { animate(1000, addTab, next, true, "newtab-open-preload-yes", tabRefDuration); }, - function() { animate(0, closeCurrentTab, next); }, + function() { + animate( + 1000, + addTab, + next, + true, + "newtab-open-preload-yes", + tabRefDuration + ); + }, + function() { + animate(0, closeCurrentTab, next); + }, ], simple3open3closeDpiCurrent: [ - function() { animate(rest, addTab, next, true, "simple3-1-open-DPIcurrent", tabRefDuration); }, - function() { animate(rest, addTab, next, true, "simple3-2-open-DPIcurrent", tabRefDuration); }, - function() { animate(rest, addTab, next, true, "simple3-3-open-DPIcurrent", tabRefDuration); }, + function() { + animate( + rest, + addTab, + next, + true, + "simple3-1-open-DPIcurrent", + tabRefDuration + ); + }, + function() { + animate( + rest, + addTab, + next, + true, + "simple3-2-open-DPIcurrent", + tabRefDuration + ); + }, + function() { + animate( + rest, + addTab, + next, + true, + "simple3-3-open-DPIcurrent", + tabRefDuration + ); + }, - function() { animate(rest, closeCurrentTab, next, true, "simple3-3-close-DPIcurrent", tabRefDuration); }, - function() { animate(rest, closeCurrentTab, next, true, "simple3-2-close-DPIcurrent", tabRefDuration); }, - function() { animate(rest, closeCurrentTab, next, true, "simple3-1-close-DPIcurrent", tabRefDuration); }, + function() { + animate( + rest, + closeCurrentTab, + next, + true, + "simple3-3-close-DPIcurrent", + tabRefDuration + ); + }, + function() { + animate( + rest, + closeCurrentTab, + next, + true, + "simple3-2-close-DPIcurrent", + tabRefDuration + ); + }, + function() { + animate( + rest, + closeCurrentTab, + next, + true, + "simple3-1-close-DPIcurrent", + tabRefDuration + ); + }, ], multi: [ function() { Services.prefs.setCharPref("layout.css.devPixelsPerPx", "1.0"); - self.makeNewTabURLChangePromise("chrome://tart/content/blank.icon.html").then(next); + self + .makeNewTabURLChangePromise("chrome://tart/content/blank.icon.html") + .then(next); }, - function() { animate(0, addTab, next); }, - function() { animate(0, addTab, next); }, - function() { animate(0, addTab, next); }, - function() { animate(0, addTab, next); }, - function() { animate(0, addTab, next); }, - function() { animate(0, addTab, next); }, + function() { + animate(0, addTab, next); + }, + function() { + animate(0, addTab, next); + }, + function() { + animate(0, addTab, next); + }, + function() { + animate(0, addTab, next); + }, + function() { + animate(0, addTab, next); + }, + function() { + animate(0, addTab, next); + }, - function() { animate(rest * 2, addTab, next, true, "multi-open-DPI1", tabRefDuration); }, - function() { animate(rest * 2, closeCurrentTab, next, true, "multi-close-DPI1", tabRefDuration); }, + function() { + animate( + rest * 2, + addTab, + next, + true, + "multi-open-DPI1", + tabRefDuration + ); + }, + function() { + animate( + rest * 2, + closeCurrentTab, + next, + true, + "multi-close-DPI1", + tabRefDuration + ); + }, - function() { Services.prefs.setCharPref("layout.css.devPixelsPerPx", "2"); next(); }, - function() { animate(0, addTab, next); }, - function() { animate(0, closeCurrentTab, next); }, - function() { animate(rest * 2, addTab, next, true, "multi-open-DPI2", tabRefDuration); }, - function() { animate(rest * 2, closeCurrentTab, next, true, "multi-close-DPI2", tabRefDuration); }, + function() { + Services.prefs.setCharPref("layout.css.devPixelsPerPx", "2"); + next(); + }, + function() { + animate(0, addTab, next); + }, + function() { + animate(0, closeCurrentTab, next); + }, + function() { + animate( + rest * 2, + addTab, + next, + true, + "multi-open-DPI2", + tabRefDuration + ); + }, + function() { + animate( + rest * 2, + closeCurrentTab, + next, + true, + "multi-close-DPI2", + tabRefDuration + ); + }, - function() { Services.prefs.setCharPref("layout.css.devPixelsPerPx", "-1"); next(); }, + function() { + Services.prefs.setCharPref("layout.css.devPixelsPerPx", "-1"); + next(); + }, - function() { animate(0, closeCurrentTab, next); }, - function() { animate(0, closeCurrentTab, next); }, - function() { animate(0, closeCurrentTab, next); }, - function() { animate(0, closeCurrentTab, next); }, - function() { animate(0, closeCurrentTab, next); }, - function() { animate(0, closeCurrentTab, next); }, + function() { + animate(0, closeCurrentTab, next); + }, + function() { + animate(0, closeCurrentTab, next); + }, + function() { + animate(0, closeCurrentTab, next); + }, + function() { + animate(0, closeCurrentTab, next); + }, + function() { + animate(0, closeCurrentTab, next); + }, + function() { + animate(0, closeCurrentTab, next); + }, ], simpleFadeDpiCurrent: [ - function() { self.makeNewTabURLChangePromise("about:blank").then(next); }, + function() { + self.makeNewTabURLChangePromise("about:blank").then(next); + }, - function() { animate(0, addTab, next); }, - function() { animate(rest, fadeout, next, true, "simpleFade-close-DPIcurrent", tabRefDuration); }, - function() { animate(rest, fadein, next, true, "simpleFade-open-DPIcurrent", tabRefDuration); }, - function() { animate(0, closeCurrentTab, next); }, + function() { + animate(0, addTab, next); + }, + function() { + animate( + rest, + fadeout, + next, + true, + "simpleFade-close-DPIcurrent", + tabRefDuration + ); + }, + function() { + animate( + rest, + fadein, + next, + true, + "simpleFade-open-DPIcurrent", + tabRefDuration + ); + }, + function() { + animate(0, closeCurrentTab, next); + }, ], iconFadeDpiCurrent: [ - function() { self.makeNewTabURLChangePromise("chrome://tart/content/blank.icon.html").then(next); }, + function() { + self + .makeNewTabURLChangePromise("chrome://tart/content/blank.icon.html") + .then(next); + }, - function() { animate(0, addTab, next); }, - function() { animate(rest, fadeout, next, true, "iconFade-close-DPIcurrent", tabRefDuration); }, - function() { animate(rest, fadein, next, true, "iconFade-open-DPIcurrent", tabRefDuration); }, - function() { animate(0, closeCurrentTab, next); }, + function() { + animate(0, addTab, next); + }, + function() { + animate( + rest, + fadeout, + next, + true, + "iconFade-close-DPIcurrent", + tabRefDuration + ); + }, + function() { + animate( + rest, + fadein, + next, + true, + "iconFade-open-DPIcurrent", + tabRefDuration + ); + }, + function() { + animate(0, closeCurrentTab, next); + }, ], iconFadeDpi2: [ function() { Services.prefs.setCharPref("layout.css.devPixelsPerPx", "2"); - self.makeNewTabURLChangePromise("chrome://tart/content/blank.icon.html").then(next); + self + .makeNewTabURLChangePromise("chrome://tart/content/blank.icon.html") + .then(next); + }, + function() { + animate(0, addTab, next); + }, + function() { + animate( + rest, + fadeout, + next, + true, + "iconFade-close-DPI2", + tabRefDuration + ); + }, + function() { + animate( + rest, + fadein, + next, + true, + "iconFade-open-DPI2", + tabRefDuration + ); + }, + function() { + animate(0, closeCurrentTab, next); }, - function() { animate(0, addTab, next); }, - function() { animate(rest, fadeout, next, true, "iconFade-close-DPI2", tabRefDuration); }, - function() { animate(rest, fadein, next, true, "iconFade-open-DPI2", tabRefDuration); }, - function() { animate(0, closeCurrentTab, next); }, ], lastTabFadeDpiCurrent: [ function() { - self._win.gBrowser.selectedTab = self._win.gBrowser.tabs[gBrowser.tabs.length - 1]; - next(); -}, - function() { animate(rest, fadeout, next, true, "lastTabFade-close-DPIcurrent", tabRefDuration); }, - function() { animate(rest, fadein, next, true, "lastTabFade-open-DPIcurrent", tabRefDuration); }, + self._win.gBrowser.selectedTab = + self._win.gBrowser.tabs[gBrowser.tabs.length - 1]; + next(); + }, + function() { + animate( + rest, + fadeout, + next, + true, + "lastTabFade-close-DPIcurrent", + tabRefDuration + ); + }, + function() { + animate( + rest, + fadein, + next, + true, + "lastTabFade-open-DPIcurrent", + tabRefDuration + ); + }, ], customize: [ // Test australis customize mode animation with default DPI. - function() { Services.prefs.setCharPref("layout.css.devPixelsPerPx", "-1"); next(); }, + function() { + Services.prefs.setCharPref("layout.css.devPixelsPerPx", "-1"); + next(); + }, // Adding a non-newtab since the behavior of exiting customize mode which was entered on newtab may change. See bug 957202. - function() { animate(0, addSomeTab, next); }, + function() { + animate(0, addSomeTab, next); + }, // The prefixes 1- and 2- were added because talos cuts common prefixes on all "pages", which ends up as "customize-e" prefix. - function() { animate(rest, customizeEnter, next, true, "1-customize-enter", custRefDuration); }, - function() { animate(rest, customizeExit, next, true, "2-customize-exit", custRefDuration); }, + function() { + animate( + rest, + customizeEnter, + next, + true, + "1-customize-enter", + custRefDuration + ); + }, + function() { + animate( + rest, + customizeExit, + next, + true, + "2-customize-exit", + custRefDuration + ); + }, // Measures the CSS-animation-only part of entering into customize mode - function() { animate(rest, customizeEnterCss, next, true, "3-customize-enter-css", custRefDuration); }, - function() { animate(0, customizeExit, next); }, + function() { + animate( + rest, + customizeEnterCss, + next, + true, + "3-customize-enter-css", + custRefDuration + ); + }, + function() { + animate(0, customizeExit, next); + }, - function() { animate(0, closeCurrentTab, next); }, + function() { + animate(0, closeCurrentTab, next); + }, ], }; @@ -633,7 +1006,9 @@ Tart.prototype = { for (var i in this._config.subtests) { for (var r = 0; r < this._config.repeat; r++) { sequenceArray = sequenceArray.concat(subtests.init); - sequenceArray = sequenceArray.concat(subtests[this._config.subtests[i]]); + sequenceArray = sequenceArray.concat( + subtests[this._config.subtests[i]] + ); } } sequenceArray = sequenceArray.concat(subtests.restore); diff --git a/testing/talos/talos/tests/tresize/addon/api.js b/testing/talos/talos/tests/tresize/addon/api.js index f5c26588cf06..2f718012d173 100644 --- a/testing/talos/talos/tests/tresize/addon/api.js +++ b/testing/talos/talos/tests/tresize/addon/api.js @@ -1,14 +1,19 @@ "use strict"; -const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); XPCOMUtils.defineLazyModuleGetters(this, { Services: "resource://gre/modules/Services.jsm", }); -XPCOMUtils.defineLazyServiceGetter(this, "aomStartup", - "@mozilla.org/addons/addon-manager-startup;1", - "amIAddonManagerStartup"); +XPCOMUtils.defineLazyServiceGetter( + this, + "aomStartup", + "@mozilla.org/addons/addon-manager-startup;1", + "amIAddonManagerStartup" +); /* globals ExtensionAPI */ @@ -16,25 +21,41 @@ const PREFIX = "tresize@mozilla.org"; this.tresize = class extends ExtensionAPI { onStartup() { - const manifestURI = Services.io.newURI("manifest.json", null, this.extension.rootURI); + const manifestURI = Services.io.newURI( + "manifest.json", + null, + this.extension.rootURI + ); this.chromeHandle = aomStartup.registerChrome(manifestURI, [ ["content", "tresize", "chrome/"], ]); - let {baseURI} = this.extension; + let { baseURI } = this.extension; - this.listener = function listener({target, data}) { + this.listener = function listener({ target, data }) { let win = target.ownerGlobal; - Services.scriptloader.loadSubScript(baseURI.resolve("/content/Profiler.js"), win); - Services.scriptloader.loadSubScript(baseURI.resolve("/content/tresize.js"), win); + Services.scriptloader.loadSubScript( + baseURI.resolve("/content/Profiler.js"), + win + ); + Services.scriptloader.loadSubScript( + baseURI.resolve("/content/tresize.js"), + win + ); function sendResult(result) { - target.messageManager.sendAsyncMessage(`${PREFIX}:chrome-run-reply`, {id: data.id, result}); + target.messageManager.sendAsyncMessage(`${PREFIX}:chrome-run-reply`, { + id: data.id, + result, + }); } win.runTest(sendResult, data.locationSearch); }; - Services.mm.addMessageListener(`${PREFIX}:chrome-run-message`, this.listener); + Services.mm.addMessageListener( + `${PREFIX}:chrome-run-message`, + this.listener + ); this.framescriptURL = baseURI.resolve("/content/framescript.js"); Services.mm.loadFrameScript(this.framescriptURL, true); @@ -42,7 +63,10 @@ this.tresize = class extends ExtensionAPI { onShutdown() { Services.mm.removeDelayedFrameScript(this.framescriptURL); - Services.mm.removeMessageListener(`${PREFIX}:chrome-run-message`, this.listener); + Services.mm.removeMessageListener( + `${PREFIX}:chrome-run-message`, + this.listener + ); this.chromeHandle.destruct(); } }; diff --git a/testing/talos/talos/tests/tresize/addon/content/Profiler.js b/testing/talos/talos/tests/tresize/addon/content/Profiler.js index 68412f2807f1..2eb6fcc7b652 100644 --- a/testing/talos/talos/tests/tresize/addon/content/Profiler.js +++ b/testing/talos/talos/tests/tresize/addon/content/Profiler.js @@ -45,7 +45,9 @@ var Profiler; try { // eslint-disable-next-line mozilla/use-services _profiler = Cc["@mozilla.org/tools/profiler;1"].getService(Ci.nsIProfiler); - } catch (ex) { (typeof(dumpLog) == "undefined" ? dump : dumpLog)(ex + "\n"); } + } catch (ex) { + (typeof dumpLog == "undefined" ? dump : dumpLog)(ex + "\n"); + } // Parses an url query string into a JS object. function searchToObject(locationSearch) { @@ -72,11 +74,17 @@ var Profiler; * - gecko_profile_dir */ initFromObject: function Profiler__initFromObject(obj) { - if (obj && - ("gecko_profile_dir" in obj) && typeof obj.gecko_profile_dir == "string" && - ("gecko_profile_interval" in obj) && Number.isFinite(obj.gecko_profile_interval * 1) && - ("gecko_profile_entries" in obj) && Number.isFinite(obj.gecko_profile_entries * 1) && - ("gecko_profile_threads" in obj) && typeof obj.gecko_profile_threads == "string") { + if ( + obj && + "gecko_profile_dir" in obj && + typeof obj.gecko_profile_dir == "string" && + "gecko_profile_interval" in obj && + Number.isFinite(obj.gecko_profile_interval * 1) && + "gecko_profile_entries" in obj && + Number.isFinite(obj.gecko_profile_entries * 1) && + "gecko_profile_threads" in obj && + typeof obj.gecko_profile_threads == "string" + ) { profiler_interval = obj.gecko_profile_interval; profiler_entries = obj.gecko_profile_entries; profiler_threadsArray = obj.gecko_profile_threads.split(","); @@ -84,15 +92,20 @@ var Profiler; enabled = true; } }, - initFromURLQueryParams: function Profiler__initFromURLQueryParams(locationSearch) { + initFromURLQueryParams: function Profiler__initFromURLQueryParams( + locationSearch + ) { this.initFromObject(searchToObject(locationSearch)); }, beginTest: function Profiler__beginTest(testName) { currentTest = testName; if (_profiler && enabled) { - _profiler.StartProfiler(profiler_entries, profiler_interval, - ["js", "leaf", "stackwalk", "threads"], - profiler_threadsArray); + _profiler.StartProfiler( + profiler_entries, + profiler_interval, + ["js", "leaf", "stackwalk", "threads"], + profiler_threadsArray + ); if (_profiler.PauseSampling) { _profiler.PauseSampling(); } @@ -100,7 +113,9 @@ var Profiler; }, finishTest: function Profiler__finishTest() { if (_profiler && enabled) { - _profiler.dumpProfileToFile(profiler_dir + "/" + currentTest + ".profile"); + _profiler.dumpProfileToFile( + profiler_dir + "/" + currentTest + ".profile" + ); _profiler.StopProfiler(); } }, @@ -115,7 +130,9 @@ var Profiler; if (_profiler.ResumeSampling) { _profiler.ResumeSampling(); } - _profiler.AddMarker(explicit ? name : 'Start of test "' + (name || test_name) + '"'); + _profiler.AddMarker( + explicit ? name : 'Start of test "' + (name || test_name) + '"' + ); } }, pause: function Profiler__pause(name, explicit) { @@ -123,12 +140,16 @@ var Profiler; if (_profiler.PauseSampling) { _profiler.PauseSampling(); } - _profiler.AddMarker(explicit ? name : 'End of test "' + (name || test_name) + '"'); + _profiler.AddMarker( + explicit ? name : 'End of test "' + (name || test_name) + '"' + ); } }, mark: function Profiler__mark(marker, explicit) { if (_profiler) { - _profiler.AddMarker(explicit ? marker : 'Profiler: "' + (marker || test_name) + '"'); + _profiler.AddMarker( + explicit ? marker : 'Profiler: "' + (marker || test_name) + '"' + ); } }, }; diff --git a/testing/talos/talos/tests/tresize/addon/content/framescript.js b/testing/talos/talos/tests/tresize/addon/content/framescript.js index 74a60eee6d8e..a4995ae47256 100644 --- a/testing/talos/talos/tests/tresize/addon/content/framescript.js +++ b/testing/talos/talos/tests/tresize/addon/content/framescript.js @@ -1,20 +1,30 @@ (function() { const TRESIZE_PREFIX = "tresize@mozilla.org:"; - addEventListener(TRESIZE_PREFIX + "chrome-run-event", function(e) { - // eslint-disable-next-line mozilla/avoid-Date-timing - var uniqueMessageId = TRESIZE_PREFIX + content.document.documentURI + Date.now() + Math.random(); + addEventListener( + TRESIZE_PREFIX + "chrome-run-event", + function(e) { + // eslint-disable-next-line mozilla/avoid-Date-timing + var uniqueMessageId = + TRESIZE_PREFIX + + content.document.documentURI + + Date.now() + + Math.random(); - addMessageListener(TRESIZE_PREFIX + "chrome-run-reply", function done(reply) { - if (reply.data.id == uniqueMessageId) { - removeMessageListener(TRESIZE_PREFIX + "chrome-run-reply", done); - content.wrappedJSObject.logResults(reply.data.result); - } - }); + addMessageListener(TRESIZE_PREFIX + "chrome-run-reply", function done( + reply + ) { + if (reply.data.id == uniqueMessageId) { + removeMessageListener(TRESIZE_PREFIX + "chrome-run-reply", done); + content.wrappedJSObject.logResults(reply.data.result); + } + }); - sendAsyncMessage(TRESIZE_PREFIX + "chrome-run-message", { - id: uniqueMessageId, - locationSearch: e.detail.locationSearch, - }); - }, false); + sendAsyncMessage(TRESIZE_PREFIX + "chrome-run-message", { + id: uniqueMessageId, + locationSearch: e.detail.locationSearch, + }); + }, + false + ); })(); diff --git a/testing/talos/talos/tests/tresize/addon/content/tresize.js b/testing/talos/talos/tests/tresize/addon/content/tresize.js index ec0afa6bd878..b957ae29b171 100644 --- a/testing/talos/talos/tests/tresize/addon/content/tresize.js +++ b/testing/talos/talos/tests/tresize/addon/content/tresize.js @@ -63,5 +63,5 @@ async function runTest(callback, locationSearch) { let total = times.reduce((a, b) => a + b); let average = total / times.length; - callback({average}); + callback({ average }); } diff --git a/testing/talos/talos/tests/twinopen/api.js b/testing/talos/talos/tests/twinopen/api.js index 9df62f1618ae..f8949e66f732 100644 --- a/testing/talos/talos/tests/twinopen/api.js +++ b/testing/talos/talos/tests/twinopen/api.js @@ -1,31 +1,49 @@ "use strict"; -ChromeUtils.defineModuleGetter(this, "Services", - "resource://gre/modules/Services.jsm"); -ChromeUtils.defineModuleGetter(this, "TalosParentProfiler", - "resource://talos-powers/TalosParentProfiler.jsm"); -ChromeUtils.defineModuleGetter(this, "AppConstants", - "resource://gre/modules/AppConstants.jsm"); +ChromeUtils.defineModuleGetter( + this, + "Services", + "resource://gre/modules/Services.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "TalosParentProfiler", + "resource://talos-powers/TalosParentProfiler.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "AppConstants", + "resource://gre/modules/AppConstants.jsm" +); var OPENER_DELAY = 1000; // ms delay between tests async function openDelay(win) { - return new Promise((resolve) => { + return new Promise(resolve => { win.setTimeout(resolve, OPENER_DELAY); }); } function waitForBrowserPaint() { - return new Promise((resolve) => { + return new Promise(resolve => { let observer = { observe(doc) { - if (!doc.location || doc.location.href != AppConstants.BROWSER_CHROME_URL) { + if ( + !doc.location || + doc.location.href != AppConstants.BROWSER_CHROME_URL + ) { return; } Services.obs.removeObserver(observer, "document-element-inserted"); - doc.ownerGlobal.addEventListener("MozAfterPaint", (evt) => { - resolve(doc.ownerGlobal.performance.timing.fetchStart + evt.paintTimeStamp); - }, {once: true}); + doc.ownerGlobal.addEventListener( + "MozAfterPaint", + evt => { + resolve( + doc.ownerGlobal.performance.timing.fetchStart + evt.paintTimeStamp + ); + }, + { once: true } + ); }, }; Services.obs.addObserver(observer, "document-element-inserted"); diff --git a/testing/talos/talos/webextensions/dummy/background.js b/testing/talos/talos/webextensions/dummy/background.js index 955ce2874b00..34d0f67a97b2 100644 --- a/testing/talos/talos/webextensions/dummy/background.js +++ b/testing/talos/talos/webextensions/dummy/background.js @@ -21,54 +21,55 @@ browser.webRequest.onBeforeRequest.addListener( filter.ondata = event => { filter.write(event.data); }; - }, { + }, + { urls: [""], }, - ["blocking"]); + ["blocking"] +); browser.webRequest.onBeforeSendHeaders.addListener( details => { - return {requestHeaders: details.requestHeaders}; + return { requestHeaders: details.requestHeaders }; }, - {urls: ["https://*/*", "http://*/*"]}, - ["blocking", "requestHeaders"]); + { urls: ["https://*/*", "http://*/*"] }, + ["blocking", "requestHeaders"] +); browser.webRequest.onHeadersReceived.addListener( details => { - return {responseHeaders: details.responseHeaders}; + return { responseHeaders: details.responseHeaders }; }, - {urls: ["https://*/*", "http://*/*"]}, - ["blocking", "responseHeaders"]); + { urls: ["https://*/*", "http://*/*"] }, + ["blocking", "responseHeaders"] +); -browser.webRequest.onErrorOccurred.addListener( - details => { - }, - {urls: ["https://*/*", "http://*/*"]}); - - -browser.runtime.onMessage.addListener(msg => { - return Promise.resolve({code: "10-4", msg}); +browser.webRequest.onErrorOccurred.addListener(details => {}, { + urls: ["https://*/*", "http://*/*"], }); +browser.runtime.onMessage.addListener(msg => { + return Promise.resolve({ code: "10-4", msg }); +}); browser.tabs.onUpdated.addListener((tabId, changed, tab) => { if (changed.url) { browser.pageAction.show(tabId); } if (changed.title) { - browser.pageAction.setTitle({tabId, title: `title: ${tab.title}`}); - browser.pageAction.setIcon({tabId, path: {16: "/icon.png"}}); + browser.pageAction.setTitle({ tabId, title: `title: ${tab.title}` }); + browser.pageAction.setIcon({ tabId, path: { 16: "/icon.png" } }); - browser.browserAction.setTitle({tabId, title: `title: ${tab.title}`}); - browser.browserAction.setIcon({path: {16: "/icon.png"}}); + browser.browserAction.setTitle({ tabId, title: `title: ${tab.title}` }); + browser.browserAction.setIcon({ path: { 16: "/icon.png" } }); } - browser.tabs.sendMessage(tabId, {changed, tab}).catch(() => { + browser.tabs.sendMessage(tabId, { changed, tab }).catch(() => { // Ignore tabs that don't have a listener yet. }); }); -browser.tabs.onActivated.addListener(({tabId, windowId}) => { +browser.tabs.onActivated.addListener(({ tabId, windowId }) => { browser.pageAction.show(tabId); }); @@ -76,11 +77,8 @@ browser.tabs.onCreated.addListener(tab => { browser.pageAction.show(tab.id); }); -browser.tabs.onRemoved.addListener((tabId, removeInfo) => { -}); +browser.tabs.onRemoved.addListener((tabId, removeInfo) => {}); -browser.tabs.onAttached.addListener((tabId, attachInfo) => { -}); +browser.tabs.onAttached.addListener((tabId, attachInfo) => {}); -browser.tabs.onDetached.addListener((tabId, detachInfo) => { -}); +browser.tabs.onDetached.addListener((tabId, detachInfo) => {}); diff --git a/testing/talos/talos/webextensions/dummy/content.js b/testing/talos/talos/webextensions/dummy/content.js index a0490656a077..57bf2912a51f 100644 --- a/testing/talos/talos/webextensions/dummy/content.js +++ b/testing/talos/talos/webextensions/dummy/content.js @@ -8,5 +8,5 @@ browser.runtime.sendMessage({ }); browser.runtime.onMessage.addListener(msg => { - return Promise.resolve({code: "10-4", msg}); + return Promise.resolve({ code: "10-4", msg }); }); diff --git a/testing/xpcshell/dbg-actors.js b/testing/xpcshell/dbg-actors.js index bd9114248d17..54d1e17a87ae 100644 --- a/testing/xpcshell/dbg-actors.js +++ b/testing/xpcshell/dbg-actors.js @@ -10,7 +10,9 @@ const { DebuggerServer } = require("devtools/server/main"); const { RootActor } = require("devtools/server/actors/root"); const { BrowserTabList } = require("devtools/server/actors/webbrowser"); const Services = require("Services"); -const { ActorRegistry } = require("devtools/server/actors/utils/actor-registry"); +const { + ActorRegistry, +} = require("devtools/server/actors/utils/actor-registry"); /** * xpcshell-test (XPCST) specific actors. diff --git a/testing/xpcshell/example/unit/check_profile.js b/testing/xpcshell/example/unit/check_profile.js index 3359ec2fcddd..0529fd9832e4 100644 --- a/testing/xpcshell/example/unit/check_profile.js +++ b/testing/xpcshell/example/unit/check_profile.js @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); function check_profile_dir(profd) { Assert.ok(profd.exists()); @@ -21,7 +21,7 @@ function check_do_get_profile(fireProfileAfterChange) { ]); const expectedTopics = new Map(observedTopics); - for (let [topic ] of observedTopics) { + for (let [topic] of observedTopics) { Services.obs.addObserver(() => { let val = observedTopics.get(topic) + 1; observedTopics.set(topic, val); diff --git a/testing/xpcshell/example/unit/import_module.jsm b/testing/xpcshell/example/unit/import_module.jsm index fa176a7544ea..947e41ee1d33 100644 --- a/testing/xpcshell/example/unit/import_module.jsm +++ b/testing/xpcshell/example/unit/import_module.jsm @@ -6,7 +6,7 @@ // Module used by test_import_module.js -const EXPORTED_SYMBOLS = [ "MODULE_IMPORTED", "MODULE_URI" ]; +const EXPORTED_SYMBOLS = ["MODULE_IMPORTED", "MODULE_URI"]; const MODULE_IMPORTED = true; const MODULE_URI = __URI__; diff --git a/testing/xpcshell/example/unit/test_check_nsIException.js b/testing/xpcshell/example/unit/test_check_nsIException.js index 7ec5e2f1fa5e..d6bf7c37fbf1 100644 --- a/testing/xpcshell/example/unit/test_check_nsIException.js +++ b/testing/xpcshell/example/unit/test_check_nsIException.js @@ -4,10 +4,10 @@ /* import-globals-from ../../head.js */ function run_test() { - let env = Cc["@mozilla.org/process/environment;1"] - .getService(Ci.nsIEnvironment); + let env = Cc["@mozilla.org/process/environment;1"].getService( + Ci.nsIEnvironment + ); do_check_throws_nsIException(function() { env.QueryInterface(Ci.nsIFile); }, "NS_NOINTERFACE"); } - diff --git a/testing/xpcshell/example/unit/test_check_nsIException_failing.js b/testing/xpcshell/example/unit/test_check_nsIException_failing.js index f96a92b8eab4..5f559247d92a 100644 --- a/testing/xpcshell/example/unit/test_check_nsIException_failing.js +++ b/testing/xpcshell/example/unit/test_check_nsIException_failing.js @@ -8,4 +8,3 @@ function run_test() { throw Error("I find your relaxed dishabille unpalatable"); }, "NS_NOINTERFACE"); } - diff --git a/testing/xpcshell/example/unit/test_do_check_matches.js b/testing/xpcshell/example/unit/test_do_check_matches.js index 2eee88ffd48f..44ef0096fc98 100644 --- a/testing/xpcshell/example/unit/test_do_check_matches.js +++ b/testing/xpcshell/example/unit/test_do_check_matches.js @@ -2,13 +2,13 @@ * http://creativecommons.org/publicdomain/zero/1.0/ */ function run_test() { - Assert.deepEqual({x: 1}, {x: 1}); + Assert.deepEqual({ x: 1 }, { x: 1 }); // Property order is irrelevant. - Assert.deepEqual({x: "foo", y: "bar"}, {y: "bar", x: "foo"});// pass + Assert.deepEqual({ x: "foo", y: "bar" }, { y: "bar", x: "foo" }); // pass // Patterns nest. - Assert.deepEqual({a: 1, b: {c: 2, d: 3}}, {a: 1, b: {c: 2, d: 3}}); + Assert.deepEqual({ a: 1, b: { c: 2, d: 3 } }, { a: 1, b: { c: 2, d: 3 } }); Assert.deepEqual([3, 4, 5], [3, 4, 5]); } diff --git a/testing/xpcshell/example/unit/test_do_check_matches_failing.js b/testing/xpcshell/example/unit/test_do_check_matches_failing.js index bbb035d6b882..c45ec3469b7b 100644 --- a/testing/xpcshell/example/unit/test_do_check_matches_failing.js +++ b/testing/xpcshell/example/unit/test_do_check_matches_failing.js @@ -2,11 +2,11 @@ * http://creativecommons.org/publicdomain/zero/1.0/ */ function run_test() { - Assert.deepEqual({x: 1}, {}); // fail: all pattern props required - Assert.deepEqual({x: 1}, {x: 2}); // fail: values must match - Assert.deepEqual({x: undefined}, {}); + Assert.deepEqual({ x: 1 }, {}); // fail: all pattern props required + Assert.deepEqual({ x: 1 }, { x: 2 }); // fail: values must match + Assert.deepEqual({ x: undefined }, {}); // 'length' property counts, even if non-enumerable. Assert.deepEqual([3, 4, 5], [3, 5, 5]); // fail; value doesn't match - Assert.deepEqual([3, 4, 5], [3, 4, 5, 6]);// fail; length doesn't match + Assert.deepEqual([3, 4, 5], [3, 4, 5, 6]); // fail; length doesn't match } diff --git a/testing/xpcshell/example/unit/test_get_idle.js b/testing/xpcshell/example/unit/test_get_idle.js index 5ebdd85930c0..0d9eff9b223b 100644 --- a/testing/xpcshell/example/unit/test_get_idle.js +++ b/testing/xpcshell/example/unit/test_get_idle.js @@ -4,8 +4,9 @@ function run_test() { print("Init the fake idle service and check its identity."); - let fakeIdleService = Cc["@mozilla.org/widget/idleservice;1"]. - getService(Ci.nsIIdleService); + let fakeIdleService = Cc["@mozilla.org/widget/idleservice;1"].getService( + Ci.nsIIdleService + ); try { fakeIdleService.QueryInterface(Ci.nsIFactory); } catch (ex) { diff --git a/testing/xpcshell/example/unit/test_import_module.js b/testing/xpcshell/example/unit/test_import_module.js index ced08ad1f233..f832c41ee0f9 100644 --- a/testing/xpcshell/example/unit/test_import_module.js +++ b/testing/xpcshell/example/unit/test_import_module.js @@ -12,8 +12,8 @@ */ function run_test() { - Assert.ok(typeof(this.MODULE_IMPORTED) == "undefined"); - Assert.ok(typeof(this.MODULE_URI) == "undefined"); + Assert.ok(typeof this.MODULE_IMPORTED == "undefined"); + Assert.ok(typeof this.MODULE_URI == "undefined"); let uri = "resource://test/import_module.jsm"; let exports = ChromeUtils.import(uri); Assert.ok(exports.MODULE_URI == uri); diff --git a/testing/xpcshell/example/unit/test_load_httpd_js.js b/testing/xpcshell/example/unit/test_load_httpd_js.js index 47805d58c2ae..03a993730dd3 100644 --- a/testing/xpcshell/example/unit/test_load_httpd_js.js +++ b/testing/xpcshell/example/unit/test_load_httpd_js.js @@ -4,7 +4,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const {HttpServer} = ChromeUtils.import("resource://testing-common/httpd.js"); +const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js"); function run_test() { var httpserver = new HttpServer(); diff --git a/testing/xpcshell/head.js b/testing/xpcshell/head.js index 542bd2b5447d..102c3c23b11f 100644 --- a/testing/xpcshell/head.js +++ b/testing/xpcshell/head.js @@ -39,18 +39,27 @@ var _XPCSHELL_PROCESS; // Register the testing-common resource protocol early, to have access to its // modules. -var _Services = ChromeUtils.import("resource://gre/modules/Services.jsm", null).Services; +var _Services = ChromeUtils.import("resource://gre/modules/Services.jsm", null) + .Services; _register_modules_protocol_handler(); -var _PromiseTestUtils = ChromeUtils.import("resource://testing-common/PromiseTestUtils.jsm", null).PromiseTestUtils; +var _PromiseTestUtils = ChromeUtils.import( + "resource://testing-common/PromiseTestUtils.jsm", + null +).PromiseTestUtils; var _Task = ChromeUtils.import("resource://testing-common/Task.jsm", null).Task; -let _NetUtil = ChromeUtils.import("resource://gre/modules/NetUtil.jsm", null).NetUtil; +let _NetUtil = ChromeUtils.import("resource://gre/modules/NetUtil.jsm", null) + .NetUtil; -let _XPCOMUtils = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm", null).XPCOMUtils; +let _XPCOMUtils = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm", + null +).XPCOMUtils; // Support a common assertion library, Assert.jsm. -var AssertCls = ChromeUtils.import("resource://testing-common/Assert.jsm", null).Assert; +var AssertCls = ChromeUtils.import("resource://testing-common/Assert.jsm", null) + .Assert; // Pass a custom report function for xpcshell-test style reporting. var Assert = new AssertCls(function(err, message, stack) { if (err) { @@ -76,7 +85,10 @@ var _dumpLog = function(raw_msg) { dump("\n" + JSON.stringify(raw_msg) + "\n"); }; -var _LoggerClass = ChromeUtils.import("resource://testing-common/StructuredLog.jsm", null).StructuredLogger; +var _LoggerClass = ChromeUtils.import( + "resource://testing-common/StructuredLog.jsm", + null +).StructuredLogger; var _testLogger = new _LoggerClass("xpcshell/head.js", _dumpLog, [_add_params]); // Disable automatic network detection, so tests work correctly when @@ -90,14 +102,13 @@ try { // Don't use Services.appinfo here as it disables replacing appinfo with stubs // for test usage. // eslint-disable-next-line mozilla/use-services - runningInParent = Cc["@mozilla.org/xre/runtime;1"]. - getService(Ci.nsIXULRuntime).processType - == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT; -} catch (e) { } + runningInParent = + Cc["@mozilla.org/xre/runtime;1"].getService(Ci.nsIXULRuntime).processType == + Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT; +} catch (e) {} // Only if building of places is enabled. -if (runningInParent && - "mozIAsyncHistory" in Ci) { +if (runningInParent && "mozIAsyncHistory" in Ci) { // Ensure places history is enabled for xpcshell-tests as some non-FF // apps disable it. _Services.prefs.setBoolPref("places.history.enabled", true); @@ -114,7 +125,7 @@ try { _Services.prefs.setCharPref("network.dns.ipv4OnlyDomains", "localhost"); } } -} catch (e) { } +} catch (e) {} // Configure crash reporting, if possible // We rely on the Python harness to set MOZ_CRASHREPORTER, @@ -122,15 +133,14 @@ try { // Note that if we're in a child process, we don't want to init the // crashreporter component. try { - if (runningInParent && - "@mozilla.org/toolkit/crash-reporter;1" in Cc) { - let crashReporter = - Cc["@mozilla.org/toolkit/crash-reporter;1"] - .getService(Ci.nsICrashReporter); + if (runningInParent && "@mozilla.org/toolkit/crash-reporter;1" in Cc) { + let crashReporter = Cc["@mozilla.org/toolkit/crash-reporter;1"].getService( + Ci.nsICrashReporter + ); crashReporter.UpdateCrashEventsDir(); crashReporter.minidumpPath = do_get_minidumpdir(); } -} catch (e) { } +} catch (e) {} if (runningInParent) { _Services.prefs.setBoolPref("dom.push.connection.enabled", false); @@ -147,8 +157,14 @@ try { let listener = { QueryInterface: ChromeUtils.generateQI(["nsIConsoleListener"]), observe(msg) { - if (typeof info === "function") - info("CONSOLE_MESSAGE: (" + levelNames[msg.logLevel] + ") " + msg.toString()); + if (typeof info === "function") { + info( + "CONSOLE_MESSAGE: (" + + levelNames[msg.logLevel] + + ") " + + msg.toString() + ); + } }, }; // Don't use _Services.console here as it causes one of the devtools tests @@ -168,18 +184,19 @@ const _timerFuzz = 15; function _Timer(func, delay) { delay = Number(delay); - if (delay < 0) + if (delay < 0) { do_throw("do_timeout() delay must be nonnegative"); + } - if (typeof func !== "function") + if (typeof func !== "function") { do_throw("string callbacks no longer accepted; use a function!"); + } this._func = func; this._start = Date.now(); this._delay = delay; - var timer = Cc["@mozilla.org/timer;1"] - .createInstance(Ci.nsITimer); + var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); timer.initWithCallback(this, delay + _timerFuzz, timer.TYPE_ONE_SHOT); // Keep timer alive until it fires @@ -217,8 +234,9 @@ function _isGenerator(val) { } function _do_main() { - if (_quit) + if (_quit) { return; + } _testLogger.info("running event loop"); @@ -252,8 +270,9 @@ void Cc["@mozilla.org/widget/transferable;1"].createInstance(); var _fakeIdleService = { get registrar() { delete this.registrar; - return this.registrar = - Components.manager.QueryInterface(Ci.nsIComponentRegistrar); + return (this.registrar = Components.manager.QueryInterface( + Ci.nsIComponentRegistrar + )); }, contractID: "@mozilla.org/widget/idleservice;1", CID: Components.ID("{9163a4ae-70c2-446c-9ac1-bbe4ab93004e}"), @@ -262,8 +281,11 @@ var _fakeIdleService = { if (!this.originalCID) { this.originalCID = this.registrar.contractIDToCID(this.contractID); // Replace with the mock. - this.registrar.registerFactory(this.CID, "Fake Idle Service", - this.contractID, this.factory + this.registrar.registerFactory( + this.CID, + "Fake Idle Service", + this.contractID, + this.factory ); } }, @@ -273,8 +295,12 @@ var _fakeIdleService = { // Unregister the mock. this.registrar.unregisterFactory(this.CID, this.factory); // Restore original factory. - this.registrar.registerFactory(this.originalCID, "Idle Service", - this.contractID, null); + this.registrar.registerFactory( + this.originalCID, + "Idle Service", + this.contractID, + null + ); delete this.originalCID; } }, @@ -306,8 +332,7 @@ var _fakeIdleService = { if (aIID.equals(Ci.nsIFactory)) { return this.factory; } - if (aIID.equals(Ci.nsIIdleService) || - aIID.equals(Ci.nsISupports)) { + if (aIID.equals(Ci.nsIIdleService) || aIID.equals(Ci.nsISupports)) { return this; } throw Components.Exception("", Cr.NS_ERROR_NO_INTERFACE); @@ -320,16 +345,15 @@ var _fakeIdleService = { */ function do_get_idle() { _fakeIdleService.deactivate(); - return Cc[_fakeIdleService.contractID] - .getService(Ci.nsIIdleService); + return Cc[_fakeIdleService.contractID].getService(Ci.nsIIdleService); } // Map resource://test/ to current working directory and // resource://testing-common/ to the shared test modules directory. function _register_protocol_handlers() { - let protocolHandler = - _Services.io.getProtocolHandler("resource") - .QueryInterface(Ci.nsIResProtocolHandler); + let protocolHandler = _Services.io + .getProtocolHandler("resource") + .QueryInterface(Ci.nsIResProtocolHandler); let curDirURI = _Services.io.newFileURI(do_get_cwd()); protocolHandler.setSubstitution("test", curDirURI); @@ -339,27 +363,30 @@ function _register_protocol_handlers() { function _register_modules_protocol_handler() { if (!_TESTING_MODULES_DIR) { - throw new Error("Please define a path where the testing modules can be " + - "found in a variable called '_TESTING_MODULES_DIR' before " + - "head.js is included."); + throw new Error( + "Please define a path where the testing modules can be " + + "found in a variable called '_TESTING_MODULES_DIR' before " + + "head.js is included." + ); } - let protocolHandler = - _Services.io.getProtocolHandler("resource") - .QueryInterface(Ci.nsIResProtocolHandler); + let protocolHandler = _Services.io + .getProtocolHandler("resource") + .QueryInterface(Ci.nsIResProtocolHandler); - let modulesFile = Cc["@mozilla.org/file/local;1"]. - createInstance(Ci.nsIFile); + let modulesFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile); modulesFile.initWithPath(_TESTING_MODULES_DIR); if (!modulesFile.exists()) { - throw new Error("Specified modules directory does not exist: " + - _TESTING_MODULES_DIR); + throw new Error( + "Specified modules directory does not exist: " + _TESTING_MODULES_DIR + ); } if (!modulesFile.isDirectory()) { - throw new Error("Specified modules directory is not a directory: " + - _TESTING_MODULES_DIR); + throw new Error( + "Specified modules directory is not a directory: " + _TESTING_MODULES_DIR + ); } let modulesURI = _Services.io.newFileURI(modulesFile); @@ -374,8 +401,9 @@ function _setupDebuggerServer(breakpointFiles, callback) { _Services.prefs.setBoolPref("devtools.debugger.remote-enabled", true); // for debugging-the-debugging, let an env var cause log spew. - let env = Cc["@mozilla.org/process/environment;1"] - .getService(Ci.nsIEnvironment); + let env = Cc["@mozilla.org/process/environment;1"].getService( + Ci.nsIEnvironment + ); if (env.get("DEVTOOLS_DEBUGGER_LOG")) { _Services.prefs.setBoolPref("devtools.debugger.log", true); } @@ -387,15 +415,17 @@ function _setupDebuggerServer(breakpointFiles, callback) { try { ({ require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm")); } catch (e) { - throw new Error("resource://devtools appears to be inaccessible from the " + - "xpcshell environment.\n" + - "This can usually be resolved by adding:\n" + - " firefox-appdir = browser\n" + - "to the xpcshell.ini manifest.\n" + - "It is possible for this to alter test behevior by " + - "triggering additional browser code to run, so check " + - "test behavior after making this change.\n" + - "See also https://bugzil.la/1215378."); + throw new Error( + "resource://devtools appears to be inaccessible from the " + + "xpcshell environment.\n" + + "This can usually be resolved by adding:\n" + + " firefox-appdir = browser\n" + + "to the xpcshell.ini manifest.\n" + + "It is possible for this to alter test behevior by " + + "triggering additional browser code to run, so check " + + "test behavior after making this change.\n" + + "See also https://bugzil.la/1215378." + ); } let { DebuggerServer } = require("devtools/server/main"); DebuggerServer.init(); @@ -406,7 +436,11 @@ function _setupDebuggerServer(breakpointFiles, callback) { // An observer notification that tells us when we can "resume" script // execution. - const TOPICS = ["devtools-thread-instantiated", "devtools-thread-resumed", "xpcshell-test-devtools-shutdown"]; + const TOPICS = [ + "devtools-thread-instantiated", + "devtools-thread-resumed", + "xpcshell-test-devtools-shutdown", + ]; let observe = function(subject, topic, data) { if (topic === "devtools-thread-instantiated") { const threadActor = subject.wrappedJSObject; @@ -431,8 +465,12 @@ function _setupDebuggerServer(breakpointFiles, callback) { function _initDebugging(port) { let initialized = false; - const { DebuggerServer, SocketListener } = - _setupDebuggerServer(_TEST_FILE, () => { initialized = true; }); + const { DebuggerServer, SocketListener } = _setupDebuggerServer( + _TEST_FILE, + () => { + initialized = true; + } + ); info(""); info("*******************************************************************"); @@ -493,7 +531,10 @@ function _execute_test() { let coverageCollector = null; if (typeof _JSCOV_DIR === "string") { - let _CoverageCollector = ChromeUtils.import("resource://testing-common/CoverageUtils.jsm", {}).CoverageCollector; + let _CoverageCollector = ChromeUtils.import( + "resource://testing-common/CoverageUtils.jsm", + {} + ).CoverageCollector; coverageCollector = new _CoverageCollector(_JSCOV_DIR); } @@ -508,7 +549,9 @@ function _execute_test() { this[func] = Assert[func].bind(Assert); } - const {PerTestCoverageUtils} = ChromeUtils.import("resource://testing-common/PerTestCoverageUtils.jsm"); + const { PerTestCoverageUtils } = ChromeUtils.import( + "resource://testing-common/PerTestCoverageUtils.jsm" + ); if (runningInParent) { PerTestCoverageUtils.beforeTestSync(); @@ -579,11 +622,10 @@ function _execute_test() { } else if (ex.fileName) { filename = ex.fileName; } - _testLogger.error(_exception_message(ex), - { - stack: _format_stack(stack), - source_file: filename, - }); + _testLogger.error(_exception_message(ex), { + stack: _format_stack(stack), + source_file: filename, + }); }; let complete = _cleanupFunctions.length == 0; @@ -599,7 +641,9 @@ function _execute_test() { } } _cleanupFunctions = []; - })().catch(reportCleanupError).then(() => complete = true); + })() + .catch(reportCleanupError) + .then(() => (complete = true)); _Services.tm.spinEventLoopUntil(() => complete); // Restore idle service to avoid leaks. @@ -679,7 +723,7 @@ function do_timeout(delay, func) { } function executeSoon(callback, aName) { - let funcName = (aName ? aName : callback.name); + let funcName = aName ? aName : callback.name; do_test_pending(funcName); _Services.tm.dispatchToMainThread({ @@ -694,12 +738,14 @@ function executeSoon(callback, aName) { // do_check failure though. if (!_quit || e.result != Cr.NS_ERROR_ABORT) { let stack = e.stack ? _format_stack(e.stack) : null; - _testLogger.testStatus(_TEST_NAME, - funcName, - "FAIL", - "PASS", - _exception_message(e), - stack); + _testLogger.testStatus( + _TEST_NAME, + funcName, + "FAIL", + "PASS", + _exception_message(e), + stack + ); _do_quit(); } } finally { @@ -722,16 +768,16 @@ function do_throw(error, stack) { // otherwise get it from our call context stack = stack || error.stack || Components.stack.caller; - if (stack instanceof Ci.nsIStackFrame) + if (stack instanceof Ci.nsIStackFrame) { filename = stack.filename; - else if (error.fileName) + } else if (error.fileName) { filename = error.fileName; + } - _testLogger.error(_exception_message(error), - { - source_file: filename, - stack: _format_stack(stack), - }); + _testLogger.error(_exception_message(error), { + source_file: filename, + stack: _format_stack(stack), + }); _abort_failed_test(); } @@ -767,9 +813,9 @@ function _exception_message(ex) { message += ex.message; } if (ex.fileName) { - message += (" at " + ex.fileName); + message += " at " + ex.fileName; if (ex.lineNumber) { - message += (":" + ex.lineNumber); + message += ":" + ex.lineNumber; } } if (message !== "") { @@ -784,22 +830,20 @@ function do_report_unexpected_exception(ex, text) { text = text ? text + " - " : ""; _passed = false; - _testLogger.error(text + "Unexpected exception " + _exception_message(ex), - { - source_file: filename, - stack: _format_stack(ex.stack), - }); + _testLogger.error(text + "Unexpected exception " + _exception_message(ex), { + source_file: filename, + stack: _format_stack(ex.stack), + }); _do_quit(); throw Components.Exception("", Cr.NS_ERROR_ABORT); } function do_note_exception(ex, text) { let filename = Components.stack.caller.filename; - _testLogger.info(text + "Swallowed exception " + _exception_message(ex), - { - source_file: filename, - stack: _format_stack(ex.stack), - }); + _testLogger.info(text + "Swallowed exception " + _exception_message(ex), { + source_file: filename, + stack: _format_stack(ex.stack), + }); } function do_report_result(passed, text, stack, todo) { @@ -812,70 +856,72 @@ function do_report_result(passed, text, stack, todo) { let name = _gRunningTest ? _gRunningTest.name : stack.name; let message; if (name) { - message = "[" + name + " : " + stack.lineNumber + "] " + text; + message = "[" + name + " : " + stack.lineNumber + "] " + text; } else { message = text; } if (passed) { if (todo) { - _testLogger.testStatus(_TEST_NAME, - name, - "PASS", - "FAIL", - message, - _format_stack(stack)); + _testLogger.testStatus( + _TEST_NAME, + name, + "PASS", + "FAIL", + message, + _format_stack(stack) + ); _abort_failed_test(); } else { - _testLogger.testStatus(_TEST_NAME, - name, - "PASS", - "PASS", - message); + _testLogger.testStatus(_TEST_NAME, name, "PASS", "PASS", message); } } else if (todo) { - _testLogger.testStatus(_TEST_NAME, - name, - "FAIL", - "FAIL", - message); + _testLogger.testStatus(_TEST_NAME, name, "FAIL", "FAIL", message); } else { - _testLogger.testStatus(_TEST_NAME, - name, - "FAIL", - "PASS", - message, - _format_stack(stack)); + _testLogger.testStatus( + _TEST_NAME, + name, + "FAIL", + "PASS", + message, + _format_stack(stack) + ); _abort_failed_test(); } } function _do_check_eq(left, right, stack, todo) { - if (!stack) + if (!stack) { stack = Components.stack.caller; + } - var text = _wrap_with_quotes_if_necessary(left) + " == " + - _wrap_with_quotes_if_necessary(right); + var text = + _wrap_with_quotes_if_necessary(left) + + " == " + + _wrap_with_quotes_if_necessary(right); do_report_result(left == right, text, stack, todo); } function todo_check_eq(left, right, stack) { - if (!stack) - stack = Components.stack.caller; + if (!stack) { + stack = Components.stack.caller; + } _do_check_eq(left, right, stack, true); } function todo_check_true(condition, stack) { - if (!stack) + if (!stack) { stack = Components.stack.caller; + } todo_check_eq(condition, true, stack); } function todo_check_false(condition, stack) { - if (!stack) + if (!stack) { stack = Components.stack.caller; + } todo_check_eq(condition, false, stack); } @@ -886,25 +932,37 @@ function todo_check_null(condition, stack = Components.stack.caller) { // Check that |func| throws an nsIException that has // |Components.results[resultName]| as the value of its 'result' property. -function do_check_throws_nsIException(func, resultName, - stack = Components.stack.caller, todo = false) { +function do_check_throws_nsIException( + func, + resultName, + stack = Components.stack.caller, + todo = false +) { let expected = Cr[resultName]; if (typeof expected !== "number") { - do_throw("do_check_throws_nsIException requires a Components.results" + - " property name, not " + uneval(resultName), stack); + do_throw( + "do_check_throws_nsIException requires a Components.results" + + " property name, not " + + uneval(resultName), + stack + ); } - let msg = ("do_check_throws_nsIException: func should throw" + - " an nsIException whose 'result' is Components.results." + - resultName); + let msg = + "do_check_throws_nsIException: func should throw" + + " an nsIException whose 'result' is Components.results." + + resultName; try { func(); } catch (ex) { - if (!(ex instanceof Ci.nsIException) || - ex.result !== expected) { - do_report_result(false, msg + ", threw " + legible_exception(ex) + - " instead", stack, todo); + if (!(ex instanceof Ci.nsIException) || ex.result !== expected) { + do_report_result( + false, + msg + ", threw " + legible_exception(ex) + " instead", + stack, + todo + ); } do_report_result(true, msg, stack, todo); @@ -921,50 +979,69 @@ function do_check_throws_nsIException(func, resultName, function legible_exception(exception) { switch (typeof exception) { case "object": - if (exception instanceof Ci.nsIException) { - return "nsIException instance: " + uneval(exception.toString()); - } - return exception.toString(); + if (exception instanceof Ci.nsIException) { + return "nsIException instance: " + uneval(exception.toString()); + } + return exception.toString(); case "number": - for (let name in Cr) { - if (exception === Cr[name]) { - return "Components.results." + name; + for (let name in Cr) { + if (exception === Cr[name]) { + return "Components.results." + name; + } } - } // Fall through. default: - return uneval(exception); + return uneval(exception); } } -function do_check_instanceof(value, constructor, - stack = Components.stack.caller, todo = false) { - do_report_result(value instanceof constructor, - "value should be an instance of " + constructor.name, - stack, todo); +function do_check_instanceof( + value, + constructor, + stack = Components.stack.caller, + todo = false +) { + do_report_result( + value instanceof constructor, + "value should be an instance of " + constructor.name, + stack, + todo + ); } -function todo_check_instanceof(value, constructor, - stack = Components.stack.caller) { +function todo_check_instanceof( + value, + constructor, + stack = Components.stack.caller +) { do_check_instanceof(value, constructor, stack, true); } function do_test_pending(aName) { ++_tests_pending; - _testLogger.info("(xpcshell/head.js) | test" + - (aName ? " " + aName : "") + - " pending (" + _tests_pending + ")"); + _testLogger.info( + "(xpcshell/head.js) | test" + + (aName ? " " + aName : "") + + " pending (" + + _tests_pending + + ")" + ); } function do_test_finished(aName) { - _testLogger.info("(xpcshell/head.js) | test" + - (aName ? " " + aName : "") + - " finished (" + _tests_pending + ")"); - if (--_tests_pending == 0) + _testLogger.info( + "(xpcshell/head.js) | test" + + (aName ? " " + aName : "") + + " finished (" + + _tests_pending + + ")" + ); + if (--_tests_pending == 0) { _do_quit(); + } } function do_get_file(path, allowNonexistent) { @@ -974,10 +1051,11 @@ function do_get_file(path, allowNonexistent) { let bits = path.split("/"); for (let i = 0; i < bits.length; i++) { if (bits[i]) { - if (bits[i] == "..") + if (bits[i] == "..") { lf = lf.parent; - else + } else { lf.append(bits[i]); + } } } @@ -985,8 +1063,15 @@ function do_get_file(path, allowNonexistent) { // Not using do_throw(): caller will continue. _passed = false; var stack = Components.stack.caller; - _testLogger.error("[" + stack.name + " : " + stack.lineNumber + "] " + - lf.path + " does not exist"); + _testLogger.error( + "[" + + stack.name + + " : " + + stack.lineNumber + + "] " + + lf.path + + " does not exist" + ); } return lf; @@ -1026,9 +1111,13 @@ function do_parse_document(aPath, aType) { break; default: - do_throw("type: expected application/xhtml+xml, application/xml or text/xml," + - " got '" + aType + "'", - Components.stack.caller); + do_throw( + "type: expected application/xhtml+xml, application/xml or text/xml," + + " got '" + + aType + + "'", + Components.stack.caller + ); } let file = do_get_file(aPath); @@ -1064,12 +1153,12 @@ function registerCleanupFunction(aFunction) { * @return nsIFile of the temporary directory */ function do_get_tempdir() { - let env = Cc["@mozilla.org/process/environment;1"] - .getService(Ci.nsIEnvironment); + let env = Cc["@mozilla.org/process/environment;1"].getService( + Ci.nsIEnvironment + ); // the python harness sets this in the environment for us let path = env.get("XPCSHELL_TEST_TEMP_DIR"); - let file = Cc["@mozilla.org/file/local;1"] - .createInstance(Ci.nsIFile); + let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile); file.initWithPath(path); return file; } @@ -1080,13 +1169,13 @@ function do_get_tempdir() { * @return nsIFile of the minidump directory */ function do_get_minidumpdir() { - let env = Cc["@mozilla.org/process/environment;1"] - .getService(Ci.nsIEnvironment); + let env = Cc["@mozilla.org/process/environment;1"].getService( + Ci.nsIEnvironment + ); // the python harness may set this in the environment for us let path = env.get("XPCSHELL_MINIDUMP_DIR"); if (path) { - let file = Cc["@mozilla.org/file/local;1"] - .createInstance(Ci.nsIFile); + let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile); file.initWithPath(path); return file; } @@ -1106,27 +1195,33 @@ function do_get_profile(notifyProfileAfterChange = false) { return null; } - let env = Cc["@mozilla.org/process/environment;1"] - .getService(Ci.nsIEnvironment); + let env = Cc["@mozilla.org/process/environment;1"].getService( + Ci.nsIEnvironment + ); // the python harness sets this in the environment for us let profd = env.get("XPCSHELL_TEST_PROFILE_DIR"); - let file = Cc["@mozilla.org/file/local;1"] - .createInstance(Ci.nsIFile); + let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile); file.initWithPath(profd); let provider = { getFile(prop, persistent) { persistent.value = true; - if (prop == "ProfD" || prop == "ProfLD" || prop == "ProfDS" || - prop == "ProfLDS" || prop == "TmpD") { + if ( + prop == "ProfD" || + prop == "ProfLD" || + prop == "ProfDS" || + prop == "ProfLDS" || + prop == "TmpD" + ) { return file.clone(); } return null; }, QueryInterface: ChromeUtils.generateQI(["nsIDirectoryServiceProvider"]), }; - _Services.dirsvc.QueryInterface(Ci.nsIDirectoryService) - .registerProvider(provider); + _Services.dirsvc + .QueryInterface(Ci.nsIDirectoryService) + .registerProvider(provider); try { _Services.dirsvc.undefine("TmpD"); @@ -1139,19 +1234,26 @@ function do_get_profile(notifyProfileAfterChange = false) { } // We need to update the crash events directory when the profile changes. - if (runningInParent && - "@mozilla.org/toolkit/crash-reporter;1" in Cc) { - let crashReporter = - Cc["@mozilla.org/toolkit/crash-reporter;1"] - .getService(Ci.nsICrashReporter); + if (runningInParent && "@mozilla.org/toolkit/crash-reporter;1" in Cc) { + let crashReporter = Cc["@mozilla.org/toolkit/crash-reporter;1"].getService( + Ci.nsICrashReporter + ); crashReporter.UpdateCrashEventsDir(); } if (!_profileInitialized) { - _Services.obs.notifyObservers(null, "profile-do-change", "xpcshell-do-get-profile"); + _Services.obs.notifyObservers( + null, + "profile-do-change", + "xpcshell-do-get-profile" + ); _profileInitialized = true; if (notifyProfileAfterChange) { - _Services.obs.notifyObservers(null, "profile-after-change", "xpcshell-do-get-profile"); + _Services.obs.notifyObservers( + null, + "profile-after-change", + "xpcshell-do-get-profile" + ); } } @@ -1178,27 +1280,37 @@ function do_load_child_test_harness() { } // Allow to be called multiple times, but only run once - if (typeof do_load_child_test_harness.alreadyRun != "undefined") + if (typeof do_load_child_test_harness.alreadyRun != "undefined") { return; + } do_load_child_test_harness.alreadyRun = 1; _XPCSHELL_PROCESS = "parent"; let command = - "const _HEAD_JS_PATH=" + uneval(_HEAD_JS_PATH) + "; " - + "const _HEAD_FILES=" + uneval(_HEAD_FILES) + "; " - + "const _MOZINFO_JS_PATH=" + uneval(_MOZINFO_JS_PATH) + "; " - + "const _TEST_NAME=" + uneval(_TEST_NAME) + "; " - // We'll need more magic to get the debugger working in the child - + "const _JSDEBUGGER_PORT=0; " - + "_XPCSHELL_PROCESS='child';"; + "const _HEAD_JS_PATH=" + + uneval(_HEAD_JS_PATH) + + "; " + + "const _HEAD_FILES=" + + uneval(_HEAD_FILES) + + "; " + + "const _MOZINFO_JS_PATH=" + + uneval(_MOZINFO_JS_PATH) + + "; " + + "const _TEST_NAME=" + + uneval(_TEST_NAME) + + "; " + + // We'll need more magic to get the debugger working in the child + "const _JSDEBUGGER_PORT=0; " + + "_XPCSHELL_PROCESS='child';"; if (typeof _JSCOV_DIR === "string") { command += " const _JSCOV_DIR=" + uneval(_JSCOV_DIR) + ";"; } if (_TESTING_MODULES_DIR) { - command += " const _TESTING_MODULES_DIR=" + uneval(_TESTING_MODULES_DIR) + ";"; + command += + " const _TESTING_MODULES_DIR=" + uneval(_TESTING_MODULES_DIR) + ";"; } command += " load(_HEAD_JS_PATH);"; @@ -1219,7 +1331,7 @@ function do_load_child_test_harness() { * @return Promise Resolved when the test in the child is complete. */ function run_test_in_child(testFile, optionalCallback) { - return new Promise((resolve) => { + return new Promise(resolve => { var callback = () => { resolve(); if (typeof optionalCallback == "undefined") { @@ -1233,11 +1345,15 @@ function run_test_in_child(testFile, optionalCallback) { var testPath = do_get_file(testFile).path.replace(/\\/g, "/"); do_test_pending("run in child"); - sendCommand("_testLogger.info('CHILD-TEST-STARTED'); " - + "const _TEST_FILE=['" + testPath + "']; " - + "_execute_test(); " - + "_testLogger.info('CHILD-TEST-COMPLETED');", - callback); + sendCommand( + "_testLogger.info('CHILD-TEST-STARTED'); " + + "const _TEST_FILE=['" + + testPath + + "']; " + + "_execute_test(); " + + "_testLogger.info('CHILD-TEST-COMPLETED');", + callback + ); }); } @@ -1251,7 +1367,7 @@ function run_test_in_child(testFile, optionalCallback) { * @return Promise Promise that is resolved when the message is received. */ function do_await_remote_message(name, optionalCallback) { - return new Promise((resolve) => { + return new Promise(resolve => { var listener = { receiveMessage(message) { if (message.name == name) { @@ -1325,8 +1441,8 @@ function add_test(properties, func = properties, isTask = false) { } else { do_throw("add_test() should take a function or an object and a function"); } - func.skip = () => properties.skip_if = () => true; - func.only = () => _gRunOnlyThisTest = func; + func.skip = () => (properties.skip_if = () => true); + func.only = () => (_gRunOnlyThisTest = func); return func; } @@ -1397,9 +1513,11 @@ var _gTestIndex = 0; // The index of the currently running test. var _gTaskRunning = false; function run_next_test() { if (_gTaskRunning) { - throw new Error("run_next_test() called from an add_task() test function. " + - "run_next_test() should not be called from inside add_task() " + - "under any circumstances!"); + throw new Error( + "run_next_test() called from an add_task() test function. " + + "run_next_test() should not be called from inside add_task() " + + "under any circumstances!" + ); } function _run_next_test() { @@ -1407,48 +1525,60 @@ function run_next_test() { // Check for uncaught rejections as early and often as possible. _PromiseTestUtils.assertNoUncaughtRejections(); let _properties; - [_properties, _gRunningTest ] = _gTests[_gTestIndex++]; + [_properties, _gRunningTest] = _gTests[_gTestIndex++]; // Must set to pending before we check for skip, so that we keep the // running counts correct. _testLogger.info(_TEST_NAME + " | Starting " + _gRunningTest.name); do_test_pending(_gRunningTest.name); - if ((typeof(_properties.skip_if) == "function" && _properties.skip_if()) || - (_gRunOnlyThisTest && _gRunningTest != _gRunOnlyThisTest)) { - let _condition = _gRunOnlyThisTest ? "only one task may run." : - _properties.skip_if.toSource().replace(/\(\)\s*=>\s*/, ""); - if (_condition == "true") + if ( + (typeof _properties.skip_if == "function" && _properties.skip_if()) || + (_gRunOnlyThisTest && _gRunningTest != _gRunOnlyThisTest) + ) { + let _condition = _gRunOnlyThisTest + ? "only one task may run." + : _properties.skip_if.toSource().replace(/\(\)\s*=>\s*/, ""); + if (_condition == "true") { _condition = "explicitly skipped."; - let _message = _gRunningTest.name - + " skipped because the following conditions were" - + " met: (" + _condition + ")"; - _testLogger.testStatus(_TEST_NAME, - _gRunningTest.name, - "SKIP", - "SKIP", - _message); + } + let _message = + _gRunningTest.name + + " skipped because the following conditions were" + + " met: (" + + _condition + + ")"; + _testLogger.testStatus( + _TEST_NAME, + _gRunningTest.name, + "SKIP", + "SKIP", + _message + ); executeSoon(run_next_test); return; } if (_properties.isTask) { _gTaskRunning = true; - (async () => _gRunningTest())().then(result => { - _gTaskRunning = false; - if (_isGenerator(result)) { - Assert.ok(false, "Task returned a generator"); + (async () => _gRunningTest())().then( + result => { + _gTaskRunning = false; + if (_isGenerator(result)) { + Assert.ok(false, "Task returned a generator"); + } + run_next_test(); + }, + ex => { + _gTaskRunning = false; + try { + do_report_unexpected_exception(ex); + } catch (error) { + // The above throws NS_ERROR_ABORT and we don't want this to show up + // as an unhandled rejection later. + } } - run_next_test(); - }, ex => { - _gTaskRunning = false; - try { - do_report_unexpected_exception(ex); - } catch (error) { - // The above throws NS_ERROR_ABORT and we don't want this to show up - // as an unhandled rejection later. - } - }); + ); } else { // Exceptions do not kill asynchronous tests, so they'll time out. try { @@ -1475,8 +1605,7 @@ function run_next_test() { try { // Set global preferences if (runningInParent) { - let prefsFile = Cc["@mozilla.org/file/local;1"] - .createInstance(Ci.nsIFile); + let prefsFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile); prefsFile.initWithPath(_PREFS_FILE); _Services.prefs.readUserPrefsFromFile(prefsFile); } @@ -1485,14 +1614,14 @@ try { } function _load_mozinfo() { - let mozinfoFile = Cc["@mozilla.org/file/local;1"] - .createInstance(Ci.nsIFile); + let mozinfoFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile); mozinfoFile.initWithPath(_MOZINFO_JS_PATH); - let stream = Cc["@mozilla.org/network/file-input-stream;1"] - .createInstance(Ci.nsIFileInputStream); + let stream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance( + Ci.nsIFileInputStream + ); stream.init(mozinfoFile, -1, 0, 0); let bytes = _NetUtil.readInputStream(stream, stream.available()); - let decoded = JSON.parse((new TextDecoder()).decode(bytes)); + let decoded = JSON.parse(new TextDecoder().decode(bytes)); stream.close(); return decoded; }