Bug 1240576 - Use Preferences.jsm throughout Marionette; r?automatedtester draft
authorAndreas Tolfsen <ato@mozilla.com>
Mon, 18 Jan 2016 22:05:30 +0000
changeset 323905 e6b8c80a15062972b4bbbe544cb0ad93d1f88613
parent 323893 977d78a8dd78afbc0153d37fd9887c3a200dce6a
child 513288 6b0a0a215ce11aeec8f8b904032a984f066bef97
push id9801
push useratolfsen@mozilla.com
push dateThu, 21 Jan 2016 13:27:41 +0000
reviewersautomatedtester
bugs1240576
milestone46.0a1
Bug 1240576 - Use Preferences.jsm throughout Marionette; r?automatedtester A distinct advantage is that try...catch statements are no longer used to control the flow of code.
testing/marionette/actions.js
testing/marionette/client/marionette/marionette_test.py
testing/marionette/client/marionette/runner/mixins/browsermob.py
testing/marionette/client/marionette/tests/unit/test_getactiveframe_oop.py
testing/marionette/client/marionette/tests/unit/test_proxy.py
testing/marionette/client/marionette/tests/unit/test_switch_remote_frame.py
testing/marionette/components/marionettecomponent.js
testing/marionette/dispatcher.js
testing/marionette/driver.js
testing/marionette/driver/marionette_driver/marionette.py
testing/marionette/server.js
--- a/testing/marionette/actions.js
+++ b/testing/marionette/actions.js
@@ -1,30 +1,36 @@
 /* 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 {classes: Cc, interfaces: Ci, utils: Cu} = Components;
+
+Cu.import("resource://gre/modules/Preferences.jsm");
+
+var CONTEXT_MENU_DELAY_PREF = "ui.click_hold_context_menus.delay";
+var DEFAULT_CONTEXT_MENU_DELAY = 750;  // ms
+
 this.EXPORTED_SYMBOLS = ["ActionChain"];
 
 /**
  * Functionality for (single finger) action chains.
  */
 this.ActionChain = function(utils, checkForInterrupted) {
   // for assigning unique ids to all touches
   this.nextTouchId = 1000;
   // keep track of active Touches
   this.touchIds = {};
   // last touch for each fingerId
   this.lastCoordinates = null;
   this.isTap = false;
   this.scrolling = false;
   // whether to send mouse event
   this.mouseEventsOnly = false;
-  this.checkTimer = Components.classes["@mozilla.org/timer;1"]
-      .createInstance(Components.interfaces.nsITimer);
+  this.checkTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
 
   // callbacks for command completion
   this.onSuccess = null;
   this.onError = null;
   if (typeof checkForInterrupted == "function") {
     this.checkForInterrupted = checkForInterrupted;
   } else {
     this.checkForInterrupted = () => {};
@@ -253,20 +259,19 @@ ActionChain.prototype.actions = function
       this.actions(chain, touchId, i, keyModifiers);
       break;
 
     case "wait":
       if (pack[1] != null) {
         let time = pack[1] * 1000;
 
         // standard waiting time to fire contextmenu
-        let standard = 750;
-        try {
-          standard = Services.prefs.getIntPref("ui.click_hold_context_menus.delay");
-        } catch (e) {}
+        let standard = Preferences.get(
+            CONTEXT_MENU_DELAY_PREF,
+            DEFAULT_CONTEXT_MENU_DELAY);
 
         if (time >= standard && this.isTap) {
           chain.splice(i, 0, ["longPress"], ["wait", (time - standard) / 1000]);
           time = standard;
         }
         this.checkTimer.initWithCallback(
             () => this.actions(chain, touchId, i, keyModifiers),
             time, Components.interfaces.nsITimer.TYPE_ONE_SHOT);
@@ -292,17 +297,16 @@ ActionChain.prototype.actions = function
           "contextmenu",
           this.lastCoordinates[0],
           this.lastCoordinates[1],
           touchId,
           null,
           keyModifiers);
       this.actions(chain, touchId, i, keyModifiers);
       break;
-
   }
 };
 
 /**
  * This function generates a pair of coordinates relative to the viewport given a
  * target element and coordinates relative to that element's top-left corner.
  *
  * @param {DOMElement} target
--- a/testing/marionette/client/marionette/marionette_test.py
+++ b/testing/marionette/client/marionette/marionette_test.py
@@ -547,18 +547,18 @@ setReq.onerror = function() {
             'css selector',
             'iframe[src*="app://test-container.gaiamobile.org/index.html"]'
         ))
 
     def setup_SpecialPowers_observer(self):
         self.marionette.set_context("chrome")
         self.marionette.execute_script("""
             let SECURITY_PREF = "security.turn_off_all_security_so_that_viruses_can_take_over_this_computer";
-            Components.utils.import("resource://gre/modules/Services.jsm");
-            Services.prefs.setBoolPref(SECURITY_PREF, true);
+            Components.utils.import("resource://gre/modules/Preferences.jsm");
+            Preferences.set(SECURITY_PREF, true);
 
             if (!testUtils.hasOwnProperty("specialPowersObserver")) {
               let loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
                 .getService(Components.interfaces.mozIJSSubScriptLoader);
               loader.loadSubScript("chrome://specialpowers/content/SpecialPowersObserver.jsm",
                 testUtils);
               testUtils.specialPowersObserver = new testUtils.SpecialPowersObserver();
               testUtils.specialPowersObserver.init();
--- a/testing/marionette/client/marionette/runner/mixins/browsermob.py
+++ b/testing/marionette/client/marionette/runner/mixins/browsermob.py
@@ -43,21 +43,22 @@ class BrowserMobProxyTestCaseMixin(objec
         self.browsermob_server = Server(
             self.browsermob_script, options=options)
         self.browsermob_server.start()
 
     def create_browsermob_proxy(self):
         client = self.browsermob_server.create_proxy()
         with self.marionette.using_context('chrome'):
             self.marionette.execute_script("""
-                Services.prefs.setIntPref('network.proxy.type', 1);
-                Services.prefs.setCharPref('network.proxy.http', 'localhost');
-                Services.prefs.setIntPref('network.proxy.http_port', %(port)s);
-                Services.prefs.setCharPref('network.proxy.ssl', 'localhost');
-                Services.prefs.setIntPref('network.proxy.ssl_port', %(port)s);
+                Components.utils.import("resource://gre/modules/Preferences.jsm");
+                Preferences.set("network.proxy.type", 1);
+                Preferences.set("network.proxy.http", "localhost");
+                Preferences.set("network.proxy.http_port", %(port)s);
+                Preferences.set("network.proxy.ssl", "localhost");
+                Preferences.set("network.proxy.ssl_port", %(port)s);
             """ % {"port": client.port})
         return client
 
     def tearDown(self):
         if self.browsermob_server:
             self.browsermob_server.stop()
             self.browsermob_server = None
 
--- a/testing/marionette/client/marionette/tests/unit/test_getactiveframe_oop.py
+++ b/testing/marionette/client/marionette/tests/unit/test_getactiveframe_oop.py
@@ -1,38 +1,40 @@
 # 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/.
 
 from marionette import MarionetteTestCase
 from marionette_driver.by import By
 
 
+OOP_BY_DEFAULT = "dom.ipc.browser_frames.oop_by_default"
+BROWSER_FRAMES_ENABLED = "dom.mozBrowserFramesEnabeld"
+
+
 class TestGetActiveFrameOOP(MarionetteTestCase):
     def setUp(self):
         super(TestGetActiveFrameOOP, self).setUp()
-        with self.marionette.using_context('chrome'):
-            self.oop_by_default = self.marionette.execute_script("""
-                try {
-                  return Services.prefs.getBoolPref('dom.ipc.browser_frames.oop_by_default');
-                }
-                catch(e) {}
-                """)
-            self.mozBrowserFramesEnabled = self.marionette.execute_script("""
-                try {
-                  return Services.prefs.getBoolPref('dom.mozBrowserFramesEnabled');
-                }
-                catch(e) {}
-                """)
-            self.marionette.execute_script("""
-                Services.prefs.setBoolPref('dom.ipc.browser_frames.oop_by_default', true);
-                """)
-            self.marionette.execute_script("""
-                Services.prefs.setBoolPref('dom.mozBrowserFramesEnabled', true);
-                """)
+        with self.marionette.using_context("chrome"):
+            self.oop_by_default = self.marionette.get_pref(OOP_BY_DEFAULT)
+            self.mozBrowserFramesEnabled = self.marionette.get_pref(BROWSER_FRAMES_ENABLED)
+            self.marionette.set_pref(OOP_BY_DEFAULT, True)
+            self.marionette.set_pref(BROWSER_FRAMES_ENABLED, True)
+
+    def tearDown(self):
+        with self.marionette.using_context("chrome"):
+            if self.oop_by_default is None:
+                self.marionette.clear_pref(OOP_BY_DEFAULT)
+            else:
+                self.marionette.set_pref(OOP_BY_DEFAULT, self.oop_by_default)
+
+            if self.mozBrowserFramesEnabled is None:
+                self.marionette.clear_pref(BROWSER_FRAMES_ENABLED)
+            else:
+                self.marionette.set_pref(BROWSER_FRAMES_ENABLED, self.mozBrowserFramesEnabled)
 
     def test_active_frame_oop(self):
         self.marionette.navigate(self.marionette.absolute_url("test.html"))
         self.marionette.push_permission('browser', True)
 
         # Create first OOP frame
         self.marionette.execute_script("""
             let iframe1 = document.createElement("iframe");
@@ -89,27 +91,8 @@ class TestGetActiveFrameOOP(MarionetteTe
         self.marionette.switch_to_frame(active_frame2)
         self.assertTrue("test_oop_2.html" in self.marionette.execute_script("return document.wrappedJSObject.location.href"))
 
         # NOTE: For some reason the emulator, the contents of the OOP iframes are not
         # actually rendered, even though the page_source is correct. When this test runs
         # on a b2g device, the contents do appear
         # print self.marionette.get_url()
         # print self.marionette.page_source
-
-    def tearDown(self):
-        with self.marionette.using_context('chrome'):
-            if self.oop_by_default is None:
-                self.marionette.execute_script("""
-                    Services.prefs.clearUserPref('dom.ipc.browser_frames.oop_by_default');
-                    """)
-            else:
-                self.marionette.execute_script("""
-                    Services.prefs.setBoolPref('dom.ipc.browser_frames.oop_by_default', %s);
-                    """ % 'true' if self.oop_by_default else 'false')
-            if self.mozBrowserFramesEnabled is None:
-                self.marionette.execute_script("""
-                    Services.prefs.clearUserPref('dom.mozBrowserFramesEnabled');
-                    """)
-            else:
-                self.marionette.execute_script("""
-                    Services.prefs.setBoolPref('dom.mozBrowserFramesEnabled', %s);
-                    """ % 'true' if self.mozBrowserFramesEnabled else 'false')
--- a/testing/marionette/client/marionette/tests/unit/test_proxy.py
+++ b/testing/marionette/client/marionette/tests/unit/test_proxy.py
@@ -220,17 +220,17 @@ class TestProxy(MarionetteTestCase):
                                     {
                                     "proxy":"I really should be a dictionary"
                                     }
                             }
         try:
             self.marionette.start_session(capabilities)
             self.fail("We should have started a session because proxy should be a dict")
         except InvalidArgumentException as e:
-            assert e.msg == "the value of 'proxy' should be an object"
+            assert e.msg == "Value of 'proxy' should be an object"
 
     def test_proxy_is_passed_in_with_no_proxy_doesnt_set_it(self):
         capabilities = {"requiredCapabilities":
             {
                 "proxy": {"proxyType": "NOPROXY"},
             }
         }
         self.marionette.start_session(capabilities)
--- a/testing/marionette/client/marionette/tests/unit/test_switch_remote_frame.py
+++ b/testing/marionette/client/marionette/tests/unit/test_switch_remote_frame.py
@@ -1,66 +1,71 @@
 # 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/.
 
 from marionette import MarionetteTestCase
 
 
+OOP_BY_DEFAULT = "dom.ipc.browser_frames.oop_by_default"
+BROWSER_FRAMES_ENABLED = "dom.mozBrowserFramesEnabled"
+
+
 class TestSwitchRemoteFrame(MarionetteTestCase):
     def setUp(self):
         super(TestSwitchRemoteFrame, self).setUp()
         with self.marionette.using_context('chrome'):
-            self.oop_by_default = self.marionette.execute_script("""
-                try {
-                  return Services.prefs.getBoolPref('dom.ipc.browser_frames.oop_by_default');
-                }
-                catch(e) {}
-                """)
-            self.mozBrowserFramesEnabled = self.marionette.execute_script("""
-                try {
-                  return Services.prefs.getBoolPref('dom.mozBrowserFramesEnabled');
-                }
-                catch(e) {}
-                """)
-            self.marionette.execute_script("""
-                Services.prefs.setBoolPref("dom.ipc.browser_frames.oop_by_default", true);
-                Services.prefs.setBoolPref("dom.mozBrowserFramesEnabled", true);
-                """)
+            self.oop_by_default = self.marionette.get_pref(OOP_BY_DEFAULT)
+            self.mozBrowserFramesEnabled = self.marionette.get_pref(BROWSER_FRAMES_ENABLED)
+            self.marionette.set_pref(OOP_BY_DEFAULT, True)
+            self.marionette.set_pref(BROWSER_FRAMES_ENABLED, True)
 
             self.multi_process_browser = self.marionette.execute_script("""
                 try {
                   return Services.appinfo.browserTabsRemoteAutostart;
                 } catch (e) {
                   return false;
                 }""")
 
+    def tearDown(self):
+        with self.marionette.using_context("chrome"):
+            if self.oop_by_default is None:
+                self.marionette.clear_pref(OOP_BY_DEFAULT)
+            else:
+                self.marionette.set_pref(OOP_BY_DEFAULT, self.oop_by_default)
+
+            if self.mozBrowserFramesEnabled is None:
+                self.marionette.clear_pref(BROWSER_FRAMES_ENABLED)
+            else:
+                self.marionette.set_pref(BROWSER_FRAMES_ENABLED, self.mozBrowserFramesEnabled)
+
+    @property
     def is_main_process(self):
         return self.marionette.execute_script("""
             return Components.classes["@mozilla.org/xre/app-info;1"].
                 getService(Components.interfaces.nsIXULRuntime).
                 processType == Components.interfaces.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
-        """, sandbox='system')
+        """, sandbox="system")
 
     def test_remote_frame(self):
         self.marionette.navigate(self.marionette.absolute_url("test.html"))
         self.marionette.push_permission('browser', True)
         self.marionette.execute_script("""
             let iframe = document.createElement("iframe");
             iframe.setAttribute('mozbrowser', true);
             iframe.setAttribute('remote', true);
             iframe.id = "remote_iframe";
             iframe.style.height = "100px";
             iframe.style.width = "100%%";
             iframe.src = "%s";
             document.body.appendChild(iframe);
             """ % self.marionette.absolute_url("test.html"))
         remote_iframe = self.marionette.find_element("id", "remote_iframe")
         self.marionette.switch_to_frame(remote_iframe)
-        main_process = self.is_main_process()
+        main_process = self.is_main_process
         self.assertFalse(main_process)
 
     def test_remote_frame_revisit(self):
         # test if we can revisit a remote frame (this takes a different codepath)
         self.marionette.navigate(self.marionette.absolute_url("test.html"))
         self.marionette.push_permission('browser', True)
         self.marionette.execute_script("""
             let iframe = document.createElement("iframe");
@@ -69,25 +74,25 @@ class TestSwitchRemoteFrame(MarionetteTe
             iframe.id = "remote_iframe";
             iframe.style.height = "100px";
             iframe.style.width = "100%%";
             iframe.src = "%s";
             document.body.appendChild(iframe);
             """ % self.marionette.absolute_url("test.html"))
         self.marionette.switch_to_frame(self.marionette.find_element("id",
                                                                      "remote_iframe"))
-        main_process = self.is_main_process()
+        main_process = self.is_main_process
         self.assertFalse(main_process)
         self.marionette.switch_to_frame()
-        main_process = self.is_main_process()
+        main_process = self.is_main_process
         should_be_main_process = not self.multi_process_browser
         self.assertEqual(main_process, should_be_main_process)
         self.marionette.switch_to_frame(self.marionette.find_element("id",
                                                                      "remote_iframe"))
-        main_process = self.is_main_process()
+        main_process = self.is_main_process
         self.assertFalse(main_process)
 
     def test_we_can_switch_to_a_remote_frame_by_index(self):
         # test if we can revisit a remote frame (this takes a different codepath)
         self.marionette.navigate(self.marionette.absolute_url("test.html"))
         self.marionette.push_permission('browser', True)
         self.marionette.execute_script("""
             let iframe = document.createElement("iframe");
@@ -95,36 +100,17 @@ class TestSwitchRemoteFrame(MarionetteTe
             iframe.setAttribute('remote', true);
             iframe.id = "remote_iframe";
             iframe.style.height = "100px";
             iframe.style.width = "100%%";
             iframe.src = "%s";
             document.body.appendChild(iframe);
             """ % self.marionette.absolute_url("test.html"))
         self.marionette.switch_to_frame(0)
-        main_process = self.is_main_process()
+        main_process = self.is_main_process
         self.assertFalse(main_process)
         self.marionette.switch_to_frame()
-        main_process = self.is_main_process()
+        main_process = self.is_main_process
         should_be_main_process = not self.multi_process_browser
         self.assertEqual(main_process, should_be_main_process)
         self.marionette.switch_to_frame(0)
-        main_process = self.is_main_process()
+        main_process = self.is_main_process
         self.assertFalse(main_process)
-
-    def tearDown(self):
-        with self.marionette.using_context('chrome'):
-            if self.oop_by_default is None:
-                self.marionette.execute_script("""
-                    Services.prefs.clearUserPref('dom.ipc.browser_frames.oop_by_default');
-                    """)
-            else:
-                self.marionette.execute_async_script(
-                    "Services.prefs.setBoolPref('dom.ipc.browser_frames.oop_by_default', %s);" %
-                    ('true' if self.oop_by_default else 'false'))
-            if self.mozBrowserFramesEnabled is None:
-                self.marionette.execute_script("""
-                    Services.prefs.clearUserPref('dom.mozBrowserFramesEnabled');
-                    """)
-            else:
-                self.marionette.execute_async_script(
-                    "Services.prefs.setBoolPref('dom.mozBrowserFramesEnabled', %s);" %
-                    ('true' if self.mozBrowserFramesEnabled else 'false'))
--- a/testing/marionette/components/marionettecomponent.js
+++ b/testing/marionette/components/marionettecomponent.js
@@ -105,19 +105,17 @@ MarionetteComponent.prototype.handle = f
 
 MarionetteComponent.prototype.observe = function(subj, topic, data) {
   switch (topic) {
     case "profile-after-change":
       // Using final-ui-startup as the xpcom category doesn't seem to work,
       // so we wait for that by adding an observer here.
       this.observerService.addObserver(this, "final-ui-startup", false);
 #ifdef ENABLE_MARIONETTE
-      try {
-        this.enabled = Services.prefs.getBoolPref(ENABLED_PREF);
-      } catch(e) {}
+      this.enabled = Preferences.get(ENABLED_PREF, false);
       if (this.enabled) {
         this.logger.debug("Marionette enabled via build flag and pref");
 
         // We want to suppress the modal dialog that's shown
         // when starting up in safe-mode to enable testing.
         if (Services.appinfo.inSafeMode) {
           this.observerService.addObserver(this, "domwindowopened", false);
         }
@@ -160,37 +158,32 @@ MarionetteComponent.prototype.suppressSa
 
 MarionetteComponent.prototype.init = function() {
   if (this.loaded_ || !this.enabled || !this.finalUiStartup) {
     return;
   }
 
   this.loaded_ = true;
 
-  let forceLocal = Services.appinfo.name == "B2G" ? false : true;
-  try {
-    forceLocal = Services.prefs.getBoolPref(FORCELOCAL_PREF);
-  } catch (e) {}
-  Services.prefs.setBoolPref(FORCELOCAL_PREF, forceLocal);
+  let forceLocal = Preferences.get(FORCELOCAL_PREF,
+      Services.appinfo.name == "B2G" ? false : true);
+  Preferences.set(FORCELOCAL_PREF, forceLocal);
 
   if (!forceLocal) {
     // See bug 800138.  Because the first socket that opens with
     // force-local=false fails, we open a dummy socket that will fail.
     // keepWhenOffline=true so that it still work when offline (local).
     // This allows the following attempt by Marionette to open a socket
     // to succeed.
     let insaneSacrificialGoat =
         new ServerSocket(666, Ci.nsIServerSocket.KeepWhenOffline, 4);
     insaneSacrificialGoat.asyncListen(this);
   }
 
-  let port = DEFAULT_PORT;
-  try {
-    port = Services.prefs.getIntPref(PORT_PREF);
-  } catch (e) {}
+  let port = Preferences.get(PORT_PREF, DEFAULT_PORT);
 
   let s;
   try {
     Cu.import("chrome://marionette/content/server.js");
     s = new MarionetteServer(port, forceLocal);
     s.start();
     this.logger.info(`Listening on port ${s.port}`);
   } catch (e) {
--- a/testing/marionette/dispatcher.js
+++ b/testing/marionette/dispatcher.js
@@ -2,16 +2,17 @@
  * 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";
 
 const {interfaces: Ci, utils: Cu} = Components;
 
 Cu.import("resource://gre/modules/Log.jsm");
+Cu.import("resource://gre/modules/Preferences.jsm");
 Cu.import("resource://gre/modules/Task.jsm");
 
 Cu.import("chrome://marionette/content/driver.js");
 Cu.import("chrome://marionette/content/emulator.js");
 Cu.import("chrome://marionette/content/error.js");
 Cu.import("chrome://marionette/content/message.js");
 
 this.EXPORTED_SYMBOLS = ["Dispatcher"];
--- a/testing/marionette/driver.js
+++ b/testing/marionette/driver.js
@@ -7,16 +7,17 @@
 var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
 
 var loader = Cc["@mozilla.org/moz/jssubscript-loader;1"]
     .getService(Ci.mozIJSSubScriptLoader);
 
 Cu.import("resource://gre/modules/FileUtils.jsm");
 Cu.import("resource://gre/modules/Log.jsm");
 Cu.import("resource://gre/modules/NetUtil.jsm");
+Cu.import("resource://gre/modules/Preferences.jsm");
 Cu.import("resource://gre/modules/Services.jsm");
 Cu.import("resource://gre/modules/Task.jsm");
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 
 var {devtools} = Cu.import("resource://devtools/shared/Loader.jsm", {});
 this.DevToolsUtils = devtools.require("devtools/shared/DevToolsUtils");
 
 XPCOMUtils.defineLazyServiceGetter(
@@ -360,19 +361,19 @@ GeckoDriver.prototype.whenBrowserStarted
       // with no children, we don't have a hope of coming back from this call,
       // so send the ack here. Otherwise, make a note of how many child scripts
       // will be loaded so we known when it's safe to return.
       if (mm.childCount !== 0) {
         this.curBrowser.frameRegsPending = mm.childCount;
       }
     }
 
-    if (!Services.prefs.getBoolPref("marionette.contentListener") || !isNewSession) {
+    if (!Preferences.get(CONTENT_LISTENER_PREF) || !isNewSession) {
       mm.loadFrameScript(FRAME_SCRIPT, true, true);
-      Services.prefs.setBoolPref("marionette.contentListener", true);
+      Preferences.set(CONTENT_LISTENER_PREF, true);
     }
   } catch (e) {
     // there may not always be a content process
     logger.error(
         `Could not load listener into content for page ${win.location.href}: ${e}`);
   }
 };
 
@@ -538,31 +539,28 @@ GeckoDriver.prototype.newSession = funct
         if (ev.target != win.document) {
           return;
         }
         win.removeEventListener("load", listener);
         waitForWindow.call(this);
       };
       win.addEventListener("load", listener, true);
     } else {
-      let clickToStart;
-      try {
-        clickToStart = Services.prefs.getBoolPref(CLICK_TO_START_PREF);
-      } catch (e) {}
+      let clickToStart = Preferences.get(CLICK_TO_START_PREF);
       if (clickToStart && (this.appName != "B2G")) {
         let pService = Cc["@mozilla.org/embedcomp/prompt-service;1"]
             .getService(Ci.nsIPromptService);
         pService.alert(win, "", "Click to start execution of marionette tests");
       }
       this.startBrowser(win, true);
     }
   };
 
   let runSessionStart = function() {
-    if (!Services.prefs.getBoolPref(CONTENT_LISTENER_PREF)) {
+    if (!Preferences.get(CONTENT_LISTENER_PREF)) {
       waitForWindow.call(this);
     } else if (this.appName != "Firefox" && this.curBrowser === null) {
       // if there is a content listener, then we just wake it up
       this.addBrowser(this.getCurrentWindow());
       this.curBrowser.startSession(this.whenBrowserStarted.bind(this));
       this.mm.broadcastAsyncMessage("Marionette:restart", {});
     } else {
       throw new WebDriverError("Session already running");
@@ -667,55 +665,59 @@ GeckoDriver.prototype.setSessionCapabili
   // clone, overwrite, and set
   let caps = copy(this.sessionCapabilities);
   caps = copy(newCaps, caps);
   logger.config("Changing capabilities: " + JSON.stringify(caps));
   this.sessionCapabilities = caps;
 };
 
 GeckoDriver.prototype.setUpProxy = function(proxy) {
-  logger.debug("User-provided proxy settings: " + JSON.stringify(proxy));
+  logger.config("User-provided proxy settings: " + JSON.stringify(proxy));
 
   if (typeof proxy == "object" && proxy.hasOwnProperty("proxyType")) {
     switch (proxy.proxyType.toUpperCase()) {
       case "MANUAL":
-        Services.prefs.setIntPref("network.proxy.type", 1);
+        Preferences.set("network.proxy.type", 1);
         if (proxy.httpProxy && proxy.httpProxyPort){
-          Services.prefs.setCharPref("network.proxy.http", proxy.httpProxy);
-          Services.prefs.setIntPref("network.proxy.http_port", proxy.httpProxyPort);
+          Preferences.set("network.proxy.http", proxy.httpProxy);
+          Preferences.set("network.proxy.http_port", proxy.httpProxyPort);
         }
         if (proxy.sslProxy && proxy.sslProxyPort){
-          Services.prefs.setCharPref("network.proxy.ssl", proxy.sslProxy);
-          Services.prefs.setIntPref("network.proxy.ssl_port", proxy.sslProxyPort);
+          Preferences.set("network.proxy.ssl", proxy.sslProxy);
+          Preferences.set("network.proxy.ssl_port", proxy.sslProxyPort);
         }
         if (proxy.ftpProxy && proxy.ftpProxyPort) {
-          Services.prefs.setCharPref("network.proxy.ftp", proxy.ftpProxy);
-          Services.prefs.setIntPref("network.proxy.ftp_port", proxy.ftpProxyPort);
+          Preferences.set("network.proxy.ftp", proxy.ftpProxy);
+          Preferences.set("network.proxy.ftp_port", proxy.ftpProxyPort);
         }
         if (proxy.socksProxy) {
-          Services.prefs.setCharPref("network.proxy.socks", proxy.socksProxy);
-          Services.prefs.setIntPref("network.proxy.socks_port", proxy.socksProxyPort);
+          Preferences.set("network.proxy.socks", proxy.socksProxy);
+          Preferences.set("network.proxy.socks_port", proxy.socksProxyPort);
           if (proxy.socksVersion) {
-            Services.prefs.setIntPref("network.proxy.socks_version", proxy.socksVersion);
+            Preferences.set("network.proxy.socks_version", proxy.socksVersion);
           }
         }
         break;
+
       case "PAC":
-        Services.prefs.setIntPref("network.proxy.type", 2);
-        Services.prefs.setCharPref("network.proxy.autoconfig_url", proxy.pacUrl);
+        Preferences.set("network.proxy.type", 2);
+        Preferences.set("network.proxy.autoconfig_url", proxy.pacUrl);
         break;
+
       case "AUTODETECT":
-        Services.prefs.setIntPref("network.proxy.type", 4);
+        Preferences.set("network.proxy.type", 4);
         break;
+
       case "SYSTEM":
-        Services.prefs.setIntPref("network.proxy.type", 5);
+        Preferences.set("network.proxy.type", 5);
         break;
+
       case "NOPROXY":
       default:
-        Services.prefs.setIntPref("network.proxy.type", 0);
+        Preferences.set("network.proxy.type", 0);
     }
   } else {
     throw new InvalidArgumentError("Value of 'proxy' should be an object");
   }
 };
 
 /**
  * Log message.  Accepts user defined log-level.
@@ -2445,17 +2447,17 @@ GeckoDriver.prototype.sessionTearDown = 
   if (this.curBrowser !== null) {
     if (this.appName == "B2G") {
       globalMessageManager.broadcastAsyncMessage(
           "Marionette:sleepSession" + this.curBrowser.mainContentId, {});
       this.curBrowser.knownFrames.splice(
           this.curBrowser.knownFrames.indexOf(this.curBrowser.mainContentId), 1);
     } else {
       // don't set this pref for B2G since the framescript can be safely reused
-      Services.prefs.setBoolPref("marionette.contentListener", false);
+      Preferences.set(CONTENT_LISTENER_PREF, false);
     }
 
     // delete session in each frame in each browser
     for (let win in this.browsers) {
       let browser = this.browsers[win];
       for (let i in browser.knownFrames) {
         globalMessageManager.broadcastAsyncMessage(
             "Marionette:deleteSession" + browser.knownFrames[i], {});
--- a/testing/marionette/driver/marionette_driver/marionette.py
+++ b/testing/marionette/driver/marionette_driver/marionette.py
@@ -962,73 +962,48 @@ class Marionette(object):
 
         try:
             yield
         finally:
             for perm in original_perms:
                 self.push_permission(perm, original_perms[perm])
 
     def get_pref(self, pref):
-        '''Gets the preference value.
+        """Gets the preference value.
 
         :param pref: Name of the preference.
 
         Usage example::
 
-          marionette.get_pref('browser.tabs.warnOnClose')
-
-        '''
+            marionette.get_pref("browser.tabs.warnOnClose")
+        """
         with self.using_context(self.CONTEXT_CONTENT):
             pref_value = self.execute_script("""
-                Components.utils.import("resource://gre/modules/Services.jsm");
-                let pref = arguments[0];
-                let type = Services.prefs.getPrefType(pref);
-                switch (type) {
-                    case Services.prefs.PREF_STRING:
-                        return Services.prefs.getCharPref(pref);
-                    case Services.prefs.PREF_INT:
-                        return Services.prefs.getIntPref(pref);
-                    case Services.prefs.PREF_BOOL:
-                        return Services.prefs.getBoolPref(pref);
-                    case Services.prefs.PREF_INVALID:
-                        return null;
-                }
-                """, script_args=[pref], sandbox='system')
+                Components.utils.import("resource://gre/modules/Preferences.jsm");
+                return Preferences.get(arguments[0], null);
+                """, script_args=[pref], sandbox="system")
             return pref_value
 
     def clear_pref(self, pref):
         with self.using_context(self.CONTEXT_CHROME):
             self.execute_script("""
-               Components.utils.import("resource://gre/modules/Services.jsm");
-               let pref = arguments[0];
-               Services.prefs.clearUserPref(pref);
+               Components.utils.import("resource://gre/modules/Preferences.jsm");
+               Preferences.reset(arguments[0]);
                """, script_args=[pref])
 
     def set_pref(self, pref, value):
         with self.using_context(self.CONTEXT_CHROME):
             if value is None:
                 self.clear_pref(pref)
                 return
 
-            if isinstance(value, bool):
-                func = 'setBoolPref'
-            elif isinstance(value, (int, long)):
-                func = 'setIntPref'
-            elif isinstance(value, basestring):
-                func = 'setCharPref'
-            else:
-                raise errors.MarionetteException(
-                    "Unsupported preference type: %s" % type(value))
-
             self.execute_script("""
-                Components.utils.import("resource://gre/modules/Services.jsm");
-                let pref = arguments[0];
-                let value = arguments[1];
-                Services.prefs.%s(pref, value);
-                """ % func, script_args=[pref, value])
+                Components.utils.import("resource://gre/modules/Preferences.jsm");
+                Preferences.set(arguments[0], arguments[1]);
+                """, script_args=[pref, value])
 
     def set_prefs(self, prefs):
         '''Sets preferences.
 
         If the value of the preference to be set is None, reset the preference
         to its default value. If no default value exists, the preference will
         cease to exist.
 
--- a/testing/marionette/server.js
+++ b/testing/marionette/server.js
@@ -5,16 +5,17 @@
 "use strict";
 
 var {Constructor: CC, classes: Cc, interfaces: Ci, utils: Cu} = Components;
 
 var loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader);
 const ServerSocket = CC("@mozilla.org/network/server-socket;1", "nsIServerSocket", "initSpecialConnection");
 
 Cu.import("resource://gre/modules/Log.jsm");
+Cu.import("resource://gre/modules/Preferences.jsm");
 Cu.import("resource://gre/modules/Services.jsm");
 
 Cu.import("chrome://marionette/content/dispatcher.js");
 Cu.import("chrome://marionette/content/driver.js");
 Cu.import("chrome://marionette/content/elements.js");
 Cu.import("chrome://marionette/content/simpletest.js");
 
 // Bug 1083711: Load transport.js as an SDK module instead of subscript
@@ -24,17 +25,19 @@ loader.loadSubScript("resource://devtool
 var events = {};
 loader.loadSubScript("chrome://marionette/content/EventUtils.js", events);
 loader.loadSubScript("chrome://marionette/content/ChromeUtils.js", events);
 loader.loadSubScript("chrome://marionette/content/frame-manager.js");
 
 const logger = Log.repository.getLogger("Marionette");
 
 this.EXPORTED_SYMBOLS = ["MarionetteServer"];
+
 const CONTENT_LISTENER_PREF = "marionette.contentListener";
+const MANAGE_OFFLINE_STATUS_PREF = "network.gonk.manage-offline-status";
 
 /**
  * Bootstraps Marionette and handles incoming client connections.
  *
  * Once started, it opens a TCP socket sporting the debugger transport
  * protocol on the provided port.  For every new client a Dispatcher is
  * created.
  *
@@ -79,21 +82,21 @@ MarionetteServer.prototype.driverFactory
 
   if (qemu == "1") {
     device = "qemu";
   }
   if (!device) {
     device = "desktop";
   }
 
-  Services.prefs.setBoolPref(CONTENT_LISTENER_PREF, false);
+  Preferences.set(CONTENT_LISTENER_PREF, false);
 
   if (bypassOffline) {
     logger.debug("Bypassing offline status");
-    Services.prefs.setBoolPref("network.gonk.manage-offline-status", false);
+    Preferences.set(MANAGE_OFFLINE_STATUS_PREF, false);
     Services.io.manageOfflineStatus = false;
     Services.io.offline = false;
   }
 
   let stopSignal = () => this.stop();
   return new GeckoDriver(appName, device, stopSignal, emulator);
 };
 
@@ -141,14 +144,10 @@ MarionetteServer.prototype.onSocketAccep
 
 MarionetteServer.prototype.onConnectionClosed = function(conn) {
   let id = conn.connId;
   delete this.conns[id];
   logger.debug(`Closed connection ${id}`);
 };
 
 function isMulet() {
-  try {
-    return Services.prefs.getBoolPref("b2g.is_mulet");
-  } catch (e) {
-    return false;
-  }
+  return Preferences.get("b2g.is_mulet", false);
 }