Bug 1432894 - Provide shorthands for Marionette prefs. r=whimboo
☠☠ backed out by 48a09f9f6fd9 ☠ ☠
authorAndreas Tolfsen <ato@sny.no>
Sat, 14 Apr 2018 17:25:26 +0100
changeset 468514 531f8f2af57d283809a8cf553dd14c51a2e3c887
parent 468513 8e9f1887bc89a5dbd861aed29c8870fb0203a6df
child 468515 fb56c3c325d3c7a79dc11b2dec1c2fc0924f3d3f
push id9165
push userasasaki@mozilla.com
push dateThu, 26 Apr 2018 21:04:54 +0000
treeherdermozilla-beta@064c3804de2e [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewerswhimboo
bugs1432894
milestone61.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1432894 - Provide shorthands for Marionette prefs. r=whimboo This introduces a new testing/marionette/prefs.js module with shorthands for all of Marionette's preferences. Getters are provided for all preferences, but setters are only offered for preference we expect to mutate at runtime. The new module additionally provides a preference abstraction on top of nsIPrefService instead of Preferences.jsm. We cannot use Preferences.jsm during startup in Marionette because Marionette gets loaded unconditionally. Finally an EnvironmentPrefs class is provided for reading and iterating over preferences stored in JSON Objects in environment variables. MozReview-Commit-ID: FbgdBEkf5A
testing/marionette/jar.mn
testing/marionette/prefs.js
testing/marionette/test/unit/test_prefs.js
testing/marionette/test/unit/xpcshell.ini
--- a/testing/marionette/jar.mn
+++ b/testing/marionette/jar.mn
@@ -31,16 +31,17 @@ marionette.jar:
   content/session.js (session.js)
   content/transport.js (transport.js)
   content/packets.js (packets.js)
   content/stream-utils.js (stream-utils.js)
   content/reftest.js (reftest.js)
   content/reftest.xul (reftest.xul)
   content/dom.js (dom.js)
   content/format.js (format.js)
+  content/prefs.js (prefs.js)
 #ifdef ENABLE_TESTS
   content/test.xul (chrome/test.xul)
   content/test2.xul (chrome/test2.xul)
   content/test_dialog.dtd (chrome/test_dialog.dtd)
   content/test_dialog.properties (chrome/test_dialog.properties)
   content/test_dialog.xul (chrome/test_dialog.xul)
   content/test_nested_iframe.xul (chrome/test_nested_iframe.xul)
   content/test_anonymous_content.xul (chrome/test_anonymous_content.xul)
new file mode 100644
--- /dev/null
+++ b/testing/marionette/prefs.js
@@ -0,0 +1,257 @@
+/* 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/. */
+
+"use strict";
+
+ChromeUtils.import("resource://gre/modules/Log.jsm");
+ChromeUtils.import("resource://gre/modules/Services.jsm");
+ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
+
+XPCOMUtils.defineLazyServiceGetter(this, "env",
+    "@mozilla.org/process/environment;1",
+    "nsIEnvironment");
+
+const {
+  PREF_BOOL,
+  PREF_COMPLEX,
+  PREF_INT,
+  PREF_INVALID,
+  PREF_STRING,
+} = Ci.nsIPrefBranch;
+
+this.EXPORTED_SYMBOLS = [
+  "Branch",
+  "MarionettePrefs",
+];
+
+class Branch {
+  /**
+   * @param {string=} branch
+   *     Preference subtree.  Uses root tree given `null`.
+   */
+  constructor(branch) {
+    this._branch = Services.prefs.getBranch(branch);
+  }
+
+  /**
+   * Gets value of `pref` in its known type.
+   *
+   * @param {string} pref
+   *     Preference name.
+   * @param {?=} fallback
+   *     Fallback value to return if `pref` does not exist.
+   *
+   * @return {(string|boolean|number)}
+   *     Value of `pref`, or the `fallback` value if `pref` does
+   *     not exist.
+   *
+   * @throws {TypeError}
+   *     If `pref` is not a recognised preference and no `fallback`
+   *     value has been provided.
+   */
+  get(pref, fallback = null) {
+    switch (this._branch.getPrefType(pref)) {
+      case PREF_STRING:
+        return this._branch.getStringPref(pref);
+
+      case PREF_BOOL:
+        return this._branch.getBoolPref(pref);
+
+      case PREF_INT:
+        return this._branch.getIntPref(pref);
+
+      case PREF_COMPLEX:
+        throw new TypeError(`Unsupported complex preference: ${pref}`);
+
+      case PREF_INVALID:
+      default:
+        if (fallback != null) {
+          return fallback;
+        }
+        throw new TypeError(`Unrecognised preference: ${pref}`);
+    }
+  }
+
+  /**
+   * Sets the value of `pref`.
+   *
+   * @param {string} pref
+   *     Preference name.
+   * @param {(string|boolean|number)} value
+   *     `pref`'s new value.
+   *
+   * @throws {TypeError}
+   *     If `value` is not the correct type for `pref`.
+   */
+  set(pref, value) {
+    let typ;
+    if (typeof value != "undefined" && value != null) {
+      typ = value.constructor.name;
+    }
+
+    switch (typ) {
+      case "String":
+        // Unicode compliant
+        return this._branch.setStringPref(pref, value);
+
+      case "Boolean":
+        return this._branch.setBoolPref(pref, value);
+
+      case "Number":
+        return this._branch.setIntPref(pref, value);
+
+      default:
+        throw new TypeError(`Illegal preference type value: ${typ}`);
+    }
+  }
+}
+
+/**
+ * Provides shortcuts for lazily getting and setting typed Marionette
+ * preferences.
+ *
+ * Some of Marionette's preferences are stored using primitive values
+ * that internally are represented by complex types.  One such example
+ * is `marionette.log.level` which stores a string such as `info` or
+ * `DEBUG`, and which is represented as `Log.Level`.
+ *
+ * Because we cannot trust the input of many of these preferences,
+ * this class provides abstraction that lets us safely deal with
+ * potentially malformed input.  In the `marionette.log.level` example,
+ * `DEBUG`, `Debug`, and `dEbUg` are considered valid inputs and the
+ * `LogBranch` specialisation deserialises the string value to the
+ * correct `Log.Level` by sanitising the input data first.
+ *
+ * A further complication is that we cannot rely on `Preferences.jsm`
+ * in Marionette.  See https://bugzilla.mozilla.org/show_bug.cgi?id=1357517
+ * for further details.
+ *
+ * Usage::
+ *
+ *     ChromeUtils.import("resource://gre/modules/Log.jsm");
+ *     const {MarionettePrefs} = ChromeUtils.import("chrome://marionette/content/prefs.js", {});
+ *
+ *     const log = Log.repository.getLogger("Marionette");
+ *     log.level = MarionettePrefs.log.level;
+ */
+class MarionetteBranch extends Branch {
+  constructor(branch = "marionette.") {
+    super(branch);
+  }
+
+  /**
+   * Gets the `marionette.enabled` preference.  When it returns true,
+   * this signifies that the Marionette server is running.
+   *
+   * @return {boolean}
+   */
+  get enabled() {
+    return this.get("enabled", false);
+  }
+
+  /**
+   * Sets the `marionette.enabled` preference.  Note that setting
+   * this to true will start the Marionette server.
+   *
+   * @param {boolean} isEnabled
+   */
+  set enabled(isEnabled) {
+    this.set("enabled", isEnabled);
+  }
+
+  /**
+   * Gets the `marionette.port` preference, detailing which port
+   * the TCP server should listen on.
+   *
+   * @return {number}
+   */
+  get port() {
+    return this.get("port", 2828);
+  }
+
+  /**
+   * Sets the `marionette.port` preference to `newPort`.  Setting this
+   * whilst the server is running will have no effect.
+   *
+   * @param {number} newPort
+   */
+  set port(newPort) {
+    this.set("port", newPort);
+  }
+
+  /**
+   * Fail-safe return of the current log level from preference
+   * `marionette.log.level`.
+   *
+   * @return {Log.Level}
+   */
+  get logLevel() {
+    switch (this.get("log.level", "info").toLowerCase()) {
+      case "fatal":
+        return Log.Level.Fatal;
+      case "error":
+        return Log.Level.Error;
+      case "warn":
+        return Log.Level.Warn;
+      case "config":
+        return Log.Level.Config;
+      case "debug":
+        return Log.Level.Debug;
+      case "trace":
+        return Log.Level.Trace;
+      case "info":
+      default:
+        return Log.Level.Info;
+    }
+  }
+
+  /**
+   * Gets the `marionette.prefs.recommended` preference, signifying
+   * whether recommended automation preferences will be set when
+   * Marionette is started.
+   *
+   * @return {boolean}
+   */
+  get recommendedPrefs() {
+    return this.get("prefs.recommended", true);
+  }
+}
+
+/** Reads a JSON serialised blob stored in the environment. */
+class EnvironmentPrefs {
+  /**
+   * Reads the environment variable `key` and tries to parse it as
+   * JSON Object, then provides an iterator over its keys and values.
+   *
+   * If the environment variable is not set, this function returns empty.
+   *
+   * @param {string} key
+   *     Environment variable.
+   *
+   * @return {Iterable.<string, (string|boolean|number)>
+   */
+  static* from(key) {
+    if (!env.exists(key)) {
+      return;
+    }
+
+    let prefs;
+    try {
+      prefs = JSON.parse(env.get(key));
+    } catch (e) {
+      throw new TypeError(`Unable to parse prefs from ${key}`, e);
+    }
+
+    for (let prefName of Object.keys(prefs)) {
+      yield [prefName, prefs[prefName]];
+    }
+  }
+}
+
+this.Branch = Branch;
+this.EnvironmentPrefs = EnvironmentPrefs;
+
+// There is a future potential of exposing this as Marionette.prefs.port
+// if we introduce a Marionette.jsm module.
+this.MarionettePrefs = new MarionetteBranch();
new file mode 100644
--- /dev/null
+++ b/testing/marionette/test/unit/test_prefs.js
@@ -0,0 +1,125 @@
+/* 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/. */
+
+"use strict";
+
+ChromeUtils.import("resource://gre/modules/Log.jsm");
+ChromeUtils.import("resource://gre/modules/Services.jsm");
+ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
+
+XPCOMUtils.defineLazyServiceGetter(
+    this, "env", "@mozilla.org/process/environment;1", "nsIEnvironment");
+
+const {
+  Branch,
+  EnvironmentPrefs,
+  MarionettePrefs,
+} = ChromeUtils.import("chrome://marionette/content/prefs.js", {});
+
+function reset() {
+  Services.prefs.setBoolPref("test.bool", false);
+  Services.prefs.setStringPref("test.string", "foo");
+  Services.prefs.setIntPref("test.int", 777);
+}
+
+// Give us something to work with:
+reset();
+
+add_test(function test_Branch_get_root() {
+  let root = new Branch(null);
+  equal(false, root.get("test.bool"));
+  equal("foo", root.get("test.string"));
+  equal(777, root.get("test.int"));
+  Assert.throws(() => root.get("doesnotexist"), /TypeError/);
+
+  run_next_test();
+});
+
+add_test(function test_Branch_get_branch() {
+  let test = new Branch("test.");
+  equal(false, test.get("bool"));
+  equal("foo", test.get("string"));
+  equal(777, test.get("int"));
+  Assert.throws(() => test.get("doesnotexist"), /TypeError/);
+
+  run_next_test();
+});
+
+add_test(function test_Branch_set_root() {
+  let root = new Branch(null);
+
+  try {
+    root.set("test.string", "bar");
+    root.set("test.in", 777);
+    root.set("test.bool", true);
+
+    equal("bar", Services.prefs.getStringPref("test.string"));
+    equal(777, Services.prefs.getIntPref("test.int"));
+    equal(true, Services.prefs.getBoolPref("test.bool"));
+  } finally {
+    reset();
+  }
+
+  run_next_test();
+});
+
+add_test(function test_Branch_set_branch() {
+  let test = new Branch("test.");
+
+  try {
+    test.set("string", "bar");
+    test.set("int", 888);
+    test.set("bool", true);
+
+    equal("bar", Services.prefs.getStringPref("test.string"));
+    equal(888, Services.prefs.getIntPref("test.int"));
+    equal(true, Services.prefs.getBoolPref("test.bool"));
+  } finally {
+    reset();
+  }
+
+  run_next_test();
+});
+
+add_test(function test_EnvironmentPrefs_from() {
+  let prefsTable = {
+    "test.bool": true,
+    "test.int": 888,
+    "test.string": "bar",
+  };
+  env.set("FOO", JSON.stringify(prefsTable));
+
+  try {
+    for (let [key, value] of EnvironmentPrefs.from("FOO")) {
+      equal(prefsTable[key], value);
+    }
+  } finally {
+    env.set("FOO", null);
+  }
+
+  run_next_test();
+});
+
+add_test(function test_MarionettePrefs_getters() {
+  equal(false, MarionettePrefs.enabled);
+  equal(2828, MarionettePrefs.port);
+  equal(Log.Level.Info, MarionettePrefs.logLevel);
+  equal(true, MarionettePrefs.recommendedPrefs);
+
+  run_next_test();
+});
+
+add_test(function test_MarionettePrefs_setters() {
+  try {
+    MarionettePrefs.enabled = true;
+    MarionettePrefs.port = 777;
+    equal(true, MarionettePrefs.enabled);
+    equal(777, MarionettePrefs.port);
+  } finally {
+    Services.prefs.clearUserPref("marionette.enabled");
+    Services.prefs.clearUserPref("marionette.port");
+  }
+
+  run_next_test();
+});
--- a/testing/marionette/test/unit/xpcshell.ini
+++ b/testing/marionette/test/unit/xpcshell.ini
@@ -1,22 +1,21 @@
 # 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/.
 
-# xpcshell unit tests for Marionette
-
 [DEFAULT]
 skip-if = appname == "thunderbird"
 
 [test_action.js]
 [test_assert.js]
 [test_browser.js]
 [test_cookie.js]
 [test_dom.js]
 [test_element.js]
 [test_error.js]
 [test_evaluate.js]
 [test_format.js]
 [test_message.js]
 [test_navigate.js]
+[test_prefs.js]
 [test_session.js]
 [test_sync.js]