Bug 1056851 - Change existing callers of SpecialPowers.setBoolPref/setIntPref/setCharPref to SpecialPowers.pushPrefEnv. r=jmaher
☠☠ backed out by 3a255cd7dadf ☠ ☠
authorAnish <anishchandran94@gmail.com>
Thu, 19 Feb 2015 07:26:41 -0500
changeset 258653 6885e993936a17fd0c9d0b59984630825f2f1e16
parent 258652 0638262755e796055e5f3198cc412ec59a01a976
child 258654 18fbec59acaaa22ef3a062ab5b76d8ce5b12127a
push id721
push userjlund@mozilla.com
push dateTue, 21 Apr 2015 23:03:33 +0000
treeherdermozilla-release@d27c9211ebb3 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersjmaher
bugs1056851
milestone38.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 1056851 - Change existing callers of SpecialPowers.setBoolPref/setIntPref/setCharPref to SpecialPowers.pushPrefEnv. r=jmaher
accessible/tests/mochitest/elm/test_canvas.html
accessible/tests/mochitest/hittest/test_canvas_hitregion.html
docshell/test/navigation/test_bug430723.html
dom/apps/tests/test_app_update.html
dom/base/test/test_EventSource_redirects.html
dom/base/test/test_bug666604.html
dom/base/test/test_bug715041.xul
dom/base/test/test_bug715041_removal.xul
dom/base/test/test_child_process_shutdown_message.html
dom/base/test/test_messagemanager_assertpermission.html
dom/base/test/test_websocket_permessage_deflate.html
dom/browser-element/mochitest/priority/test_Preallocated.html
dom/canvas/test/test_2d_composite_canvaspattern_setTransform.html
dom/canvas/test/test_canvas_path.html
dom/canvas/test/test_hitregion_canvas.html
dom/datastore/tests/test_app_install.html
dom/datastore/tests/test_arrays.html
dom/datastore/tests/test_basic.html
dom/datastore/tests/test_basic_worker.html
dom/datastore/tests/test_bug1008044.html
dom/datastore/tests/test_bug1058108.html
dom/datastore/tests/test_bug924104.html
dom/datastore/tests/test_bug957086.html
dom/datastore/tests/test_bug976311.html
dom/datastore/tests/test_certifiedApp.html
dom/datastore/tests/test_duplicate.html
dom/datastore/tests/test_keys.html
dom/datastore/tests/test_oop.html
dom/datastore/tests/test_oop_events.html
dom/datastore/tests/test_readonly.html
dom/datastore/tests/test_sync.html
dom/datastore/tests/test_sync_worker.html
dom/datastore/tests/test_transactions.html
dom/datastore/tests/test_worker_close.html
dom/events/test/test_bug422132.html
dom/events/test/test_bug563329.html
dom/events/test/test_bug574663.html
dom/events/test/test_bug607464.html
dom/events/test/test_bug822898.html
dom/html/test/file_fullscreen-api.html
dom/html/test/file_fullscreen-denied.html
dom/html/test/file_fullscreen-esc-context-menu.html
dom/html/test/forms/test_input_number_key_events.html
dom/html/test/forms/test_input_radio_radiogroup.html
dom/html/test/forms/test_input_range_key_events.html
dom/html/test/forms/test_input_range_rounding.html
dom/html/test/forms/test_radio_in_label.html
dom/html/test/forms/test_valueAsDate_pref.html
dom/html/test/test_bug369370.html
dom/html/test/test_bug633058.html
dom/html/test/test_bug674558.html
dom/html/test/test_fullscreen-api.html
dom/network/tests/test_networkstats_enabled_no_perm.html
dom/network/tests/test_tcpsocket_enabled_no_perm.html
dom/network/tests/test_tcpsocket_enabled_with_perm.html
dom/requestsync/tests/test_basic_app.html
dom/tests/mochitest/bugs/test_bug265203.html
dom/tests/mochitest/chrome/test_MozEnteredDomFullscreen_event.xul
dom/tests/mochitest/chrome/test_clipboard_events_chrome.html
dom/tests/mochitest/general/test_clipboard_events.html
dom/tests/mochitest/general/test_vibrator.html
dom/tests/mochitest/localstorage/test_appIsolation.html
dom/tv/test/mochitest/test_tv_non_permitted_app.html
dom/xul/test/test_bug757137.xul
editor/libeditor/tests/test_bug549262.html
editor/libeditor/tests/test_bug578771.html
editor/libeditor/tests/test_bug640321.html
editor/libeditor/tests/test_bug645914.html
editor/libeditor/tests/test_bug674770-1.html
editor/libeditor/tests/test_bug674770-2.html
editor/libeditor/tests/test_bug795785.html
extensions/cookie/test/test_permissionmanager_app_isolation.html
image/test/crashtests/ownerdiscard.html
testing/mochitest/tests/Harness_sanity/test_SpecialPowersExtension.html
toolkit/components/passwordmgr/test/test_basic_form_2.html
toolkit/components/passwordmgr/test/test_basic_form_observer_autofillForms.html
toolkit/components/url-classifier/tests/mochitest/test_allowlisted_annotations.html
toolkit/content/tests/chrome/test_preferences_beforeaccept.xul
widget/tests/test_assign_event_data.html
widget/tests/test_imestate.html
--- a/accessible/tests/mochitest/elm/test_canvas.html
+++ b/accessible/tests/mochitest/elm/test_canvas.html
@@ -13,42 +13,41 @@
   <script type="application/javascript"
           src="../common.js"></script>
   <script type="application/javascript"
           src="../role.js"></script>
   <script type="application/javascript"
           src="../layout.js"></script>
 
   <script type="application/javascript">
-  SpecialPowers.setBoolPref("canvas.hitregions.enabled", true);
-
     function doTest()
     {
       var canv = document.getElementById("c");
       var context = canv.getContext('2d');
       var element = document.getElementById("showA");
       context.beginPath();
       context.rect(10, 10, 150, 100);
       context.addHitRegion({control: element});
       var input = getAccessible("showA");
       var input = getAccessible("showA");
       var [cnvX, cnvY, cnvWidth, cnvHeight] = getBoundsForDOMElm(canv);
       var [accX, accY, accWidth, accHeight] = getBounds(input);
       is(accX, cnvX + 10, "accX should be 10 and not " + accX);
       is(accY, cnvY + 10, "accY should be 10 and not " + accY);
       is(accWidth, 150, "accWidth should be 150 and not " + accWidth);
       is(accHeight, 100, "accHeight should be 100 and not " + accHeight);
-
-      SpecialPowers.setBoolPref("canvas.hitregions.enabled", false);
       SimpleTest.finish();
     }
 
     SimpleTest.waitForExplicitFinish();
-    addA11yLoadEvent(doTest);
-  </script>
+    addA11yLoadEvent(function() {
+      SpecialPowers.pushPrefEnv({"set": [['canvas.hitregions.enabled', true]]}, doTest);
+    });
+
+    </script>
 </head>
 <body>
 
   <canvas id="c">
     <input id="showA" type="checkbox"><label for="showA"> Show As </label>
   </canvas>
 
 </body>
--- a/accessible/tests/mochitest/hittest/test_canvas_hitregion.html
+++ b/accessible/tests/mochitest/hittest/test_canvas_hitregion.html
@@ -8,18 +8,16 @@
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
 
   <script type="application/javascript"
           src="../common.js"></script>
   <script type="application/javascript"
           src="../layout.js"></script>
 
   <script type="application/javascript">
-    SpecialPowers.setBoolPref("canvas.hitregions.enabled", true);
-
     function redrawCheckbox(context, element, x, y)
     {
       context.save();
       context.font = '10px sans-serif';
       context.textAlign = 'left';
       context.textBaseline = 'middle';
       var metrics = context.measureText(element.parentNode.textContent);
       context.beginPath();
@@ -62,23 +60,23 @@
                           ". Found: " + prettyName(hitAcc));
 
       tgtY = hitY+75;
       hitAcc = docAcc.getDeepestChildAtPoint(tgtX, tgtY);
       // test that we don't hit the region associated with the shadow dom checkbox
       is(hitAcc, hitcanvas, "Hit match at " + tgtX + "," + tgtY +
                           ". Found: " + prettyName(hitAcc));
 
-      SpecialPowers.setBoolPref("canvas.hitregions.enabled", false);
       SimpleTest.finish();
     }
-
     SimpleTest.waitForExplicitFinish();
-    addA11yLoadEvent(doTest);
-  </script>
+    addA11yLoadEvent(function() {
+      SpecialPowers.pushPrefEnv({"set": [['canvas.hitregions.enabled', true]]}, doTest);
+    });
+ </script>
 </head>
 <body>
 
   <a target="_blank"
      href="https://bugzilla.mozilla.org/show_bug.cgi?id=966591"
      title="nsIAccessible::childAtPoint() for canvas hit regions from browser tests">Mozilla Bug 966591</a>
 
   <canvas id="hitcanvas">
--- a/docshell/test/navigation/test_bug430723.html
+++ b/docshell/test/navigation/test_bug430723.html
@@ -32,26 +32,26 @@ var gTallRedBoxURI = "data:text/html;cha
 var gTallBlueBoxURI = "data:text/html;charset=utf-8;base64,PGh0bWw%2BPGhlYWQ%2BPHNjcmlwdD53aW5kb3cuYWRkRXZlbnRMaXN0ZW5lcigncGFnZXNob3cnLCBmdW5jdGlvbigpe29wZW5lci5uZXh0VGVzdCgpO30sIGZhbHNlKTs8L3NjcmlwdD48L2hlYWQ%2BPGJvZHk%2BPGRpdiBzdHlsZT0icG9zaXRpb246YWJzb2x1dGU7IGxlZnQ6MHB4OyB0b3A6MHB4OyB3aWR0aDo1MCU7IGhlaWdodDoxNTAlOyBiYWNrZ3JvdW5kLWNvbG9yOmJsdWUiPjxwPlRoaXMgaXMgYSB2ZXJ5IHRhbGwgYmx1ZSBib3guPC9wPjwvZGl2PjwvYm9keT48L2h0bWw%2B";
 // <html><head>
 // < script > window.addEventListener("pageshow", function(){opener.nextTest();}, false); < /script > 
 // </head><body>
 // <div style="position:absolute; left:0px; top:0px; width:50%; height:150%; background-color:blue">
 // <p>This is a very tall blue box.</p>
 // </div></body></html>
 
-
 window.onload = runTest;
 
 var testWindow;
 var testNum = 0;
 
 var smoothScrollPref = "general.smoothScroll";
 function runTest() {
-  SpecialPowers.setBoolPref(smoothScrollPref, false);
-  testWindow = window.open(gTallRedBoxURI, "testWindow", "width=300,height=300,location=yes,scrollbars=yes");
+  SpecialPowers.pushPrefEnv({"set":[[smoothScrollPref, false]]}, function(){
+    testWindow = window.open(gTallRedBoxURI, "testWindow", "width=300,height=300,location=yes,scrollbars=yes");
+  });
 }
 
 var nextTest =function() {
   testNum++;
   switch (testNum) {
     case 1: setTimeout(step1, 0); break;
     case 2: setTimeout(step2, 0); break;
     case 3: setTimeout(step3, 0); break;
@@ -119,22 +119,20 @@ var step3 =function() {
      "Page1Again: Ensure scroll pane at top before we scroll.");  
   testWindow.addEventListener("scroll", function () {
     testWindow.removeEventListener("scroll", arguments.callee, true);
 
     isnot(testWindow.document.body.scrollTop, 0,
           "Page2Again: Ensure we can still scroll.");  
 
     testWindow.close();
-    SpecialPowers.clearUserPref(smoothScrollPref);
     window.SimpleTest.finish();
   }, true);
   sendKey('DOWN', testWindow);
 }
 
 SimpleTest.waitForExplicitFinish();
 
 //]]>
 </script>
 </pre>
 </body>
 </html>
-
--- a/dom/apps/tests/test_app_update.html
+++ b/dom/apps/tests/test_app_update.html
@@ -13,25 +13,23 @@ https://bugzilla.mozilla.org/show_bug.cg
   /** Test for Bug 826058 **/
 
   SimpleTest.waitForExplicitFinish();
 
   var gBaseURL = 'http://test/tests/dom/apps/tests/';
   var gHostedManifestURL = gBaseURL + 'file_app.sjs?apptype=hosted&getmanifest=true';
   var gCachedManifestURL = gBaseURL + 'file_app.sjs?apptype=cached&getmanifest=true';
   var gTrustedManifestURL = gBaseURL + 'file_app.sjs?apptype=trusted&getmanifest=true';
-  var gGenerator = runTest();
-
+  var gGenerator;
   // We need to set the trusted hosted app csp pref since it's only in
   // b2g.js for now.
   function setCSPPrefs() {
-    SpecialPowers.pushPrefEnv({'set':
-      [["security.apps.trusted.CSP.default",
-        "default-src *; object-src 'none'"]]},
-      function() {  gGenerator.next(); });
+    SpecialPowers.pushPrefEnv({'set':[["security.apps.trusted.CSP.default",
+"default-src *; object-src 'none'"], ["dom.mozBrowserFramesEnabled",true]]},
+      function() {  gGenerator = runTest(); gGenerator.next(); });
   }
 
   function go() {
     SpecialPowers.pushPermissions(
       [{ "type": "browser", "allow": 1, "context": document },
        { "type": "embed-apps", "allow": 1, "context": document },
        { "type": "webapps-manage", "allow": 1, "context": document }],
       setCSPPrefs);
@@ -59,20 +57,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 
   function xhrAbort(url) {
     ok(false, "XHR abort loading " + url);
     finish();
   }
 
   function runTest() {
     // Set up.
-
     SpecialPowers.setAllAppsLaunchable(true);
-    SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-
     // Test Bug 927699 - navigator.mozApps.install(url) lets NS_ERROR_FAILURE
     //                   onto the web
     var request = navigator.mozApps.install("");
     request.onerror = function() {
       ok(request.error.name == "INVALID_URL", "Got expected INVALID_URL");
       continueTest();
     };
     request.onsuccess = mozAppsError;
@@ -319,17 +314,16 @@ https://bugzilla.mozilla.org/show_bug.cg
   // or the base sjs file if app is null.
   function getAppURL(app) {
     if (!app)
       return gBaseURL + "file_app.sjs?apptype=hosted";
     return app.origin + app.manifest.launch_path;
   }
 
   function finish() {
-    SpecialPowers.clearUserPref("dom.mozBrowserFramesEnabled");
     SimpleTest.finish();
   }
 
   function doReload() {
     window.location.reload(true);
   }
 
   </script>
--- a/dom/base/test/test_EventSource_redirects.html
+++ b/dom/base/test/test_EventSource_redirects.html
@@ -17,18 +17,16 @@ https://bugzilla.mozilla.org/show_bug.cg
 <div id="content" style="display: none">
 
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
   function doTest(test_id) {
     oldPrefVal = SpecialPowers.getBoolPref("dom.server-events.enabled");
-    SpecialPowers.setBoolPref("dom.server-events.enabled", true);
-
     ok(true, "here we go");
 
     source = new EventSource("eventsource_redirect.resource");
     ok(source.url == "http://mochi.test:8888/tests/dom/base/test/eventsource_redirect.resource", "Test failed.");
     ok(source.readyState == 0 || source.readyState == 1, "Test failed.");
 
     source.onopen = function (event) {
       ok(true, "opened");
@@ -44,16 +42,17 @@ https://bugzilla.mozilla.org/show_bug.cg
       ok(false, "received onError: " + event);
       source.close();
       SimpleTest.finish();
     };
 
   }
 
   SimpleTest.waitForExplicitFinish();
-  addLoadEvent(doTest);
-
+  addLoadEvent(function() {
+    SpecialPowers.pushPrefEnv({"set": [['dom.server-events.enabled', true]]}, doTest);
+  });
 </script>
 </pre>
 
 </body>
 </html>
 
--- a/dom/base/test/test_bug666604.html
+++ b/dom/base/test/test_bug666604.html
@@ -103,52 +103,40 @@ function test5() {
     }
   testlink.click();
 }
 
 function test6() {
   activationListener =
     function() {
       ok(true, "Untrusted DOMActivate should activate a link");
-      test7();
+      SpecialPowers.pushPrefEnv({"set":[["dom.disable_open_during_load", false]]}, test7);
     }
   dispatchDOMActivate(testlink);
 }
 
-var oldPref;
 function test7() {
-  oldPref = SpecialPowers.getBoolPref("dom.disable_open_during_load");
-  SpecialPowers.setBoolPref("dom.disable_open_during_load", false);
   testlink.href = "javascript:opener.activationListener(); window.close();";
   testlink.target = "_blank";
   activationListener =
     function() {
       ok(true, "Click() should activate a link");
-      setTimeout(test8, 0);
+      SpecialPowers.pushPrefEnv({"set":[["dom.disable_open_during_load", true]]}, test8);
     }
   testlink.click();
 }
 
 function test8() {
-  SpecialPowers.setBoolPref("dom.disable_open_during_load", true);
   testlink.href = "javascript:opener.activationListener(); window.close();";
   testlink.target = "_blank";
   activationListener =
     function() {
       ok(false, "Click() should not activate a link");
-      setTimeout(test9, 0);
     }
-  testlink.click();  
-  hitEventLoop(10, test9);
-} 
-
-
-function test9() {
-  SpecialPowers.setBoolPref("dom.disable_open_during_load", oldPref);
-  SimpleTest.finish();
+  testlink.click();
+  SimpleTest.executeSoon(SimpleTest.finish);
 }
-
 addLoadEvent(test1);
 
 </script>
 </pre>
 </body>
 </html>
--- a/dom/base/test/test_bug715041.xul
+++ b/dom/base/test/test_bug715041.xul
@@ -14,18 +14,16 @@ xmlns="http://www.mozilla.org/keymaster/
 target="_blank">Mozilla Bug 715041</a>
     </body>
 
     <!-- test code goes here -->
     <script type="application/javascript">
     <![CDATA[
 
   /** Mock Idle Service Test for Bug 715041 **/
-  SpecialPowers.setBoolPref("dom.idle-observers-api.fuzz_time.disabled", true);
-
   //class mock javascript idle service
   var idleServiceObj = {
     observers: [],
     windowObservers: [],
     idleTimeInMS: 5000,   //in milli seconds
 
     // takes note of the idle observers added as the minimum idle observer
     // with the idle service
@@ -805,14 +803,13 @@ target="_blank">Mozilla Bug 715041</a>
 
   AddOutOfOrderActiveEnabled = true;
   AddOutOfOrderIdleEnabled = true;
   AddNewLocalWhileAllIdleEnabled = true;
   TestActiveToActiveNotificationEnabled = true;
   AddShiftLocalEnabled = true;
   AddIdleObserverWithInvalidTimeEnabled = false;
   
-  caseZero();  
-  
+  SpecialPowers.pushPrefEnv({"set":[['dom.idle-observers-api.fuzz_time.disabled', true]]}, caseZero);
     ]]>
     </script>
     </window>
 
--- a/dom/base/test/test_bug715041_removal.xul
+++ b/dom/base/test/test_bug715041_removal.xul
@@ -14,18 +14,16 @@ xmlns="http://www.mozilla.org/keymaster/
 target="_blank">Mozilla Bug 715041</a>
     </body>
 
     <!-- test code goes here -->
     <script type="application/javascript">
     <![CDATA[
 
   /** Mock Idle Service Test for Bug 715041 **/
-  SpecialPowers.setBoolPref("dom.idle-observers-api.fuzz_time.disabled", true);
-
   try {
     var idleServiceCID = Components.ID("6f95d965-4322-4829-8a3c-5dc8a4587f4d");
     var idleServiceContractID = "@mozilla.org/widget/idleservice;1";
     var oldIdleService = Components.classes[idleServiceContractID].getService(Components.interfaces.nsIIdleService);
   }
   catch (ex) {
     dump("test_bug715041_removal.xul: failed to get old idle service 1.");
   }
@@ -831,15 +829,13 @@ target="_blank">Mozilla Bug 715041</a>
   //test case enabled
   var RemoveLocalIdleObserverWhileIdleEnabled = true;
   var RemoveHeadIdleObserverEnabled = true;
   var RemoveLocalIdleTimerWhileIdleEnabled = true;
   var RemoveLocalIdleTimerLastElementEnabled = true;
   var RemoveHeadAfterLastLocalFiredEnabled = true;
   var RemoveHeadIdleObserverWhileIdleCase1Enabled = true;
   var RemoveLastAddLastEnabled = true;
-
-  RemoveHeadIdleObserverWhileActive();
-
+  SpecialPowers.pushPrefEnv({"set":[['dom.idle-observers-api.fuzz_time.disabled', true]]}, RemoveHeadIdleObserverWhileActive);
 ]]>
     </script>
     </window>
 
--- a/dom/base/test/test_child_process_shutdown_message.html
+++ b/dom/base/test/test_child_process_shutdown_message.html
@@ -112,25 +112,23 @@ function expectFrameProcessShutdown(ifra
       ok(true, "Received 'message-manager-disconnect' notification with " +
                "frame message manager");
       countMessage();
     }
   }, "message-manager-disconnect", false);
 }
 
 function setUp() {
-  SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-  SpecialPowers.setBoolPref("dom.ipc.browser_frames.oop_by_default", true);
   SpecialPowers.addPermission("browser", true, window.document);
   SpecialPowers.addPermission("embed-apps", true, window.document);
-
-  // TODO: remove in bug 820712
-  SpecialPowers.setBoolPref("network.disable.ipc.security", true);
-
-  runNextTest();
+  // TODO: remove network.disable.ipc.security in bug 820712
+  SpecialPowers.pushPrefEnv({
+    "set": [['dom.mozBrowserFramesEnabled', true],
+            ['dom.ipc.browser_frames.oop_by_default', true],
+            ['network.disable.ipc.security', true]]}, runNextTest);
 }
 
 function makeKillTest(isApp) function testKill() {
   loadBrowser(isApp, function (iframe) {
     // We want to make sure we get notified on both the frame and
     // process message managers.
     let frameMM = SpecialPowers.getBrowserFrameMessageManager(iframe);
     prepareProcess(frameMM, function (processMM) {
@@ -142,22 +140,16 @@ function makeKillTest(isApp) function te
         iframe.parentNode.removeChild(iframe);
         runNextTest();
       });
     });
   });
 }
 
 function tearDown() {
-  SpecialPowers.clearUserPref("dom.mozBrowserFramesEnabled");
-  SpecialPowers.clearUserPref("dom.ipc.browser_frames.oop_by_default");
-
-  // TODO: remove in bug 820712
-  SpecialPowers.clearUserPref("network.disable.ipc.security");
-
   SimpleTest.finish();
 }
 
 let _tests = [
   setUp,
   makeKillTest(false),
   makeKillTest(true),
   tearDown
--- a/dom/base/test/test_messagemanager_assertpermission.html
+++ b/dom/base/test/test_messagemanager_assertpermission.html
@@ -22,26 +22,25 @@ const CHILD_PROCESS_SHUTDOWN_MESSAGE = "
 let ppmm = SpecialPowers.Cc["@mozilla.org/parentprocessmessagemanager;1"]
                         .getService(SpecialPowers.Ci.nsIMessageBroadcaster);
 let cpmm = SpecialPowers.Cc["@mozilla.org/childprocessmessagemanager;1"]
                         .getService(SpecialPowers.Ci.nsISyncMessageSender);
 let gAppsService = SpecialPowers.Cc["@mozilla.org/AppsService;1"]
                      .getService(SpecialPowers.Ci.nsIAppsService);
 
 function setUp() {
-  SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-  SpecialPowers.setBoolPref("dom.ipc.browser_frames.oop_by_default", true);
   SpecialPowers.addPermission("browser", true, window.document);
   SpecialPowers.addPermission("embed-apps", true, window.document);
 
   let appId = gAppsService.getAppLocalIdByManifestURL(APP_MANIFEST);
   SpecialPowers.addPermission("foobar", true, { url: APP_URL,
                                                 appId: appId,
                                                 isInBrowserElement: false });
-  runNextTest();
+  SpecialPowers.pushPrefEnv({"set":[['dom.mozBrowserFramesEnabled', true],
+                                    ['dom.ipc.browser_frames.oop_by_default', true]]}, runNextTest);
 }
 
 /**
  * Load the example.org app in an <iframe mozbrowser mozapp>
  */
 function loadApp(callback) {
   let iframe = document.createElement("iframe");
   iframe.setAttribute("mozapp", APP_MANIFEST);
@@ -163,18 +162,16 @@ function testChildProcessMessageManager(
         iframe.parentNode.removeChild(iframe);
         runNextTest();
       });
     });
   });
 }
 
 function tearDown() {
-  SpecialPowers.clearUserPref("dom.mozBrowserFramesEnabled");
-  SpecialPowers.clearUserPref("dom.ipc.browser_frames.oop_by_default");
   SimpleTest.finish();
 }
 
 let _tests = [
   setUp,
   testSameProcess,
   testFrameMessageManager,
   testChildProcessMessageManager,
--- a/dom/base/test/test_websocket_permessage_deflate.html
+++ b/dom/base/test/test_websocket_permessage_deflate.html
@@ -1,16 +1,16 @@
 <!DOCTYPE HTML>
 <html>
 <head>
   <title>Basic test of permessage compression websocket extension</title>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
-<body onload="testDeflate()">
+<body onload="loadDeflate()">
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=792831">Mozilla Bug </a>
 <p id="display"></p>
 <div id="content" style="display: none">
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 var ws;
@@ -45,18 +45,16 @@ function sendMessage() {
     ws.send(textMessage);
   } else {
     ws.binaryType = "arraybuffer";
     ws.send(str2ab(binaryMessage));
   }
 }
 
 function testDeflate() {
-  SpecialPowers.setBoolPref("network.websocket.extensions.permessage-deflate", tests[testIdx][0]);
-
   ws = new WebSocket(tests[testIdx][2]);
 
   ws.onopen = function(e) {
     if (tests[testIdx][1]) {
       is(ws.extensions, "permessage-deflate", "permessage-deflate not negotiated!");
     } else {
       is(ws.extensions, "", "permessage-deflate should not be negotiated!");
     }
@@ -84,22 +82,26 @@ function testDeflate() {
     } else {
       ok(e.data instanceof ArrayBuffer, "Should receive an arraybuffer!");
       is(ab2str(e.data), binaryMessage, "Binary message not received successfully!");
       ws.close();
 
       sendText = true;
       testIdx++;
       if (testIdx < tests.length) {
-        testDeflate();
+        loadDeflate();
       } else {
         SimpleTest.finish();
       }
     }
   }
 }
 
+function loadDeflate() {
+  SpecialPowers.pushPrefEnv({"set":[['network.websocket.extensions.permessage-deflate', tests[testIdx][0]]]}, testDeflate);
+}
+
 SimpleTest.waitForExplicitFinish();
 
 </script>
 </pre>
 </body>
 </html>
--- a/dom/browser-element/mochitest/priority/test_Preallocated.html
+++ b/dom/browser-element/mochitest/priority/test_Preallocated.html
@@ -31,23 +31,16 @@ var childID = null;
 var cleanedUp = false;
 function cleanUp()
 {
   if (cleanedUp) {
     return;
   }
 
   cleanedUp = true;
-
-  if (preallocationEnabledPref === null) {
-    SpecialPowers.clearUserPref('dom.ipc.processPrelaunch.enabled');
-  } else {
-    SpecialPowers.setBoolPref('dom.ipc.processPrelaunch.enabled',
-                              preallocationEnabledPref);
-  }
 }
 
 // Even if this test times out, we still want to run cleanUp so as to set the
 // pref back.
 addEventListener('unload', cleanUp);
 
 function runTest()
 {
@@ -63,17 +56,16 @@ function runTest()
   expectProcessCreated('PREALLOC', 'CPU_LOW').then(function() {
     // We need to set the pref asynchoronously or the preallocated process won't
     // be shut down.
     SimpleTest.executeSoon(function(){
       cleanUp();
       SimpleTest.finish();
     });
   });
-
-  // Setting this pref to true should cause us to prelaunch a process.
-  SpecialPowers.setBoolPref('dom.ipc.processPrelaunch.enabled', true);
 }
-
-addEventListener('testready', runTest);
+// Setting this pref to true should cause us to prelaunch a process.
+addEventListener('testready', function() {
+  SpecialPowers.pushPrefEnv({'set':[["dom.ipc.processPrelaunch.enabled",true]]},runTest);
+});
 </script>
 </body>
 </html>
--- a/dom/canvas/test/test_2d_composite_canvaspattern_setTransform.html
+++ b/dom/canvas/test/test_2d_composite_canvaspattern_setTransform.html
@@ -3,17 +3,16 @@
 <script src="/tests/SimpleTest/SimpleTest.js"></script>
 <link rel="stylesheet" href="/tests/SimpleTest/test.css">
 <body>
 <script>
 
 SimpleTest.waitForExplicitFinish();
 const Cc = SpecialPowers.Cc;
 const Cr = SpecialPowers.Cr;
-SpecialPowers.setBoolPref("canvas.path.enabled", true);
 
 function isPixel(ctx, x,y, r,g,b,a, d) {
 	var pos = x + "," + y;
 	var colour = r + "," + g + "," + b + "," + a;
     var pixel = ctx.getImageData(x, y, 1, 1);
     var pr = pixel.data[0],
         pg = pixel.data[1],
         pb = pixel.data[2],
@@ -62,16 +61,18 @@ function runTests() {
   test_2d_canvaspattern_setTransform();
  } catch(e) {
   throw e;
   ok(false, "unexpected exception thrown in: test_2d_canvaspattern_setTransform");
  }
  SimpleTest.finish();
 }
 
-addLoadEvent(runTests);
+addLoadEvent(function() {
+  SpecialPowers.pushPrefEnv({"set":[["canvas.path.enabled", true]]}, runTests)
+});
 
 // Don't leak the world via the Path2D reference to its window.
 document.all;
 window.p = new Path2D();
 
 </script>
 
--- a/dom/canvas/test/test_canvas_path.html
+++ b/dom/canvas/test/test_canvas_path.html
@@ -3,17 +3,16 @@
 <script src="/tests/SimpleTest/SimpleTest.js"></script>
 <link rel="stylesheet" href="/tests/SimpleTest/test.css">
 <body>
 <script>
 
 SimpleTest.waitForExplicitFinish();
 const Cc = SpecialPowers.Cc;
 const Cr = SpecialPowers.Cr;
-SpecialPowers.setBoolPref("canvas.path.enabled", true);
 
 function isPixel(ctx, x,y, c, d) {
   var pos = x + "," + y;
   var color = c[0] + "," + c[1] + "," + c[2] + "," + c[3];
     var pixel = ctx.getImageData(x, y, 1, 1);
     var pr = pixel.data[0],
         pg = pixel.data[1],
         pb = pixel.data[2],
@@ -429,19 +428,20 @@ function runTests() {
   throw e;
  }
  try {
   test_addpath_canvas();
  } catch(e) {
   ok(false, "unexpected exception thrown in: test_addpath_canvas");
   throw e;
  }
- SpecialPowers.setBoolPref("canvas.path.enabled", false);
  SimpleTest.finish();
 }
 
-addLoadEvent(runTests);
+addLoadEvent(function() {
+  SpecialPowers.pushPrefEnv({"set":[["canvas.path.enabled", true]]}, runTests);
+});
 
 // Don't leak the world via the Path2D reference to its window.
 document.all;
 window.p = new Path2D();
 
 </script>
--- a/dom/canvas/test/test_hitregion_canvas.html
+++ b/dom/canvas/test/test_hitregion_canvas.html
@@ -3,18 +3,16 @@
 <script src="/tests/SimpleTest/SimpleTest.js"></script>
 <link rel="stylesheet" href="/tests/SimpleTest/test.css">
 <body>
 <script>
 
 SimpleTest.waitForExplicitFinish();
 const Cc = SpecialPowers.Cc;
 const Cr = SpecialPowers.Cr;
-SpecialPowers.setBoolPref("canvas.hitregions.enabled", true);
-
 </script>
 
 <p>Canvas test: hit regions</p>
 <canvas id="c1" width="150" height="50">
   <a id="c1_a"></a>
 </canvas>
 <a id="c1_b"></a>
 
@@ -73,14 +71,14 @@ function test_hitregions() {
 function runTests() {
  try {
   test_hitregions();
  } catch(e) {
   throw e;
   ok(false, "unexpected exception thrown in: test_hitregions");
  }
  SimpleTest.finish();
- SpecialPowers.setBoolPref("canvas.hitregions.enabled", false);
 }
 
-addLoadEvent(runTests);
-
+addLoadEvent(function() {
+  SpecialPowers.pushPrefEnv({"set":[["canvas.hitregions.enabled", true]]}, runTests);
+});
 </script>
--- a/dom/datastore/tests/test_app_install.html
+++ b/dom/datastore/tests/test_app_install.html
@@ -9,32 +9,33 @@
 <body>
 <div id="container"></div>
   <script type="application/javascript;version=1.7">
 
   SimpleTest.waitForExplicitFinish();
 
   var gBaseURL = 'http://test/tests/dom/datastore/tests/';
   var gHostedManifestURL = gBaseURL + 'file_app.sjs?testToken=file_app_install.html';
-  var gGenerator = runTest();
+  var gGenerator;
 
   SpecialPowers.pushPermissions(
     [{ "type": "browser", "allow": 1, "context": document },
      { "type": "embed-apps", "allow": 1, "context": document },
      { "type": "webapps-manage", "allow": 1, "context": document }],
     function() {
       SpecialPowers.pushPrefEnv({"set": [["dom.datastore.enabled", true],
                                          ["dom.datastore.sysMsgOnChangeShortTimeoutSec", 1],
                                          ["dom.datastore.sysMsgOnChangeLongTimeoutSec", 3],
                                          ["dom.testing.ignore_ipc_principal", true],
-                                         ["dom.testing.datastore_enabled_for_hosted_apps", true]]}, function() {
-
+                                         ["dom.testing.datastore_enabled_for_hosted_apps", true],
+					 ["dom.mozBrowserFramesEnabled", true]]}, function() {
         if (SpecialPowers.isMainProcess()) {
           SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
         }
+        gGenerator = runTest();
         gGenerator.next(); });
     });
 
   function continueTest() {
     try {
       gGenerator.next();
     } catch (e if e instanceof StopIteration) { }
   }
@@ -44,18 +45,16 @@
     finish();
   }
 
   function runTest() {
     ok("getDataStores" in navigator, "getDataStores exists");
     is(typeof navigator.getDataStores, "function", "getDataStores exists and it's a function");
 
     SpecialPowers.setAllAppsLaunchable(true);
-    SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-
     SpecialPowers.autoConfirmAppInstall(continueTest);
     yield undefined;
 
     SpecialPowers.autoConfirmAppUninstall(continueTest);
     yield undefined;
 
     var request = navigator.mozApps.install(gHostedManifestURL);
     request.onerror = cbError;
@@ -97,15 +96,14 @@
 
     // This event is triggered when the app calls "alert".
     ifr.addEventListener('mozbrowsershowmodalprompt', listener, false);
 
     domParent.appendChild(ifr);
   }
 
   function finish() {
-    SpecialPowers.clearUserPref("dom.mozBrowserFramesEnabled");
     SimpleTest.finish();
   }
 
   </script>
 </body>
 </html>
--- a/dom/datastore/tests/test_arrays.html
+++ b/dom/datastore/tests/test_arrays.html
@@ -84,18 +84,17 @@
     },
 
     function() {
       if (SpecialPowers.isMainProcess()) {
         SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
       }
 
       SpecialPowers.setAllAppsLaunchable(true);
-      SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-      runTest();
+      SpecialPowers.pushPrefEnv({"set":[["dom.mozBrowserFramesEnabled", true]]}, runTest);
     },
 
     // No confirmation needed when an app is installed
     function() {
       SpecialPowers.autoConfirmAppInstall(() =>
         SpecialPowers.autoConfirmAppUninstall(runTest));
     },
 
--- a/dom/datastore/tests/test_basic.html
+++ b/dom/datastore/tests/test_basic.html
@@ -84,18 +84,17 @@
     },
 
     function() {
       if (SpecialPowers.isMainProcess()) {
         SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
       }
 
       SpecialPowers.setAllAppsLaunchable(true);
-      SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-      runTest();
+      SpecialPowers.pushPrefEnv({"set":[["dom.mozBrowserFramesEnabled", true]]}, runTest);
     },
 
     // No confirmation needed when an app is installed
     function() {
       SpecialPowers.autoConfirmAppInstall(() =>
         SpecialPowers.autoConfirmAppUninstall(runTest));
     },
 
--- a/dom/datastore/tests/test_basic_worker.html
+++ b/dom/datastore/tests/test_basic_worker.html
@@ -84,18 +84,17 @@
     },
 
     function() {
       if (SpecialPowers.isMainProcess()) {
         SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
       }
 
       SpecialPowers.setAllAppsLaunchable(true);
-      SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-      runTest();
+      SpecialPowers.pushPrefEnv({"set":[["dom.mozBrowserFramesEnabled", true]]}, runTest)
     },
 
     // No confirmation needed when an app is installed
     function() {
       SpecialPowers.autoConfirmAppInstall(() =>
         SpecialPowers.autoConfirmAppUninstall(runTest));
     },
 
--- a/dom/datastore/tests/test_bug1008044.html
+++ b/dom/datastore/tests/test_bug1008044.html
@@ -85,18 +85,17 @@
     },
 
     function() {
       if (SpecialPowers.isMainProcess()) {
         SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
       }
 
       SpecialPowers.setAllAppsLaunchable(true);
-      SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-      runTest();
+      SpecialPowers.pushPrefEnv({"set":[["dom.mozBrowserFramesEnabled", true]]}, runTest);
     },
 
     // No confirmation needed when an app is installed
     function() {
       SpecialPowers.autoConfirmAppInstall(() =>
         SpecialPowers.autoConfirmAppUninstall(runTest));
     },
 
--- a/dom/datastore/tests/test_bug1058108.html
+++ b/dom/datastore/tests/test_bug1058108.html
@@ -84,18 +84,17 @@
     },
 
     function() {
       if (SpecialPowers.isMainProcess()) {
         SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
       }
 
       SpecialPowers.setAllAppsLaunchable(true);
-      SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-      runTest();
+      SpecialPowers.pushPrefEnv({"set":[["dom.mozBrowserFramesEnabled", true]]}, runTest);
     },
 
     // No confirmation needed when an app is installed
     function() {
       SpecialPowers.autoConfirmAppInstall(() =>
         SpecialPowers.autoConfirmAppUninstall(runTest));
     },
 
--- a/dom/datastore/tests/test_bug924104.html
+++ b/dom/datastore/tests/test_bug924104.html
@@ -84,18 +84,17 @@
     },
 
     function() {
       if (SpecialPowers.isMainProcess()) {
         SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
       }
 
       SpecialPowers.setAllAppsLaunchable(true);
-      SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-      runTest();
+      SpecialPowers.pushPrefEnv({"set":[["dom.mozBrowserFramesEnabled", true]]}, runTest);
     },
 
     // No confirmation needed when an app is installed
     function() {
       SpecialPowers.autoConfirmAppInstall(() =>
         SpecialPowers.autoConfirmAppUninstall(runTest));
     },
 
--- a/dom/datastore/tests/test_bug957086.html
+++ b/dom/datastore/tests/test_bug957086.html
@@ -89,18 +89,17 @@
     },
 
     function() {
       if (SpecialPowers.isMainProcess()) {
         SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
       }
 
       SpecialPowers.setAllAppsLaunchable(true);
-      SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-      runTest();
+      SpecialPowers.pushPrefEnv({"set":[["dom.mozBrowserFramesEnabled", true]]}, runTest);
     },
 
     // No confirmation needed when an app is installed
     function() {
       SpecialPowers.autoConfirmAppInstall(runTest);
     },
 
     // Installing the app - access only
--- a/dom/datastore/tests/test_bug976311.html
+++ b/dom/datastore/tests/test_bug976311.html
@@ -89,18 +89,17 @@
     },
 
     function() {
       if (SpecialPowers.isMainProcess()) {
         SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
       }
 
       SpecialPowers.setAllAppsLaunchable(true);
-      SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-      runTest();
+      SpecialPowers.pushPrefEnv({"set":[["dom.mozBrowserFramesEnabled", true]]}, runTest);
     },
 
     // No confirmation needed when an app is installed
     function() {
       SpecialPowers.autoConfirmAppInstall(() =>
         SpecialPowers.autoConfirmAppUninstall(runTest));
     },
 
--- a/dom/datastore/tests/test_certifiedApp.html
+++ b/dom/datastore/tests/test_certifiedApp.html
@@ -91,18 +91,17 @@
     },
 
     function() {
       if (SpecialPowers.isMainProcess()) {
         SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
       }
 
       SpecialPowers.setAllAppsLaunchable(true);
-      SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-      runTest();
+      SpecialPowers.pushPrefEnv({"set":[["dom.mozBrowserFramesEnabled", true]]}, runTest);
     },
 
     // No confirmation needed when an app is installed
     function() {
       SpecialPowers.autoConfirmAppInstall(() =>
         SpecialPowers.autoConfirmAppUninstall(runTest));
     },
 
--- a/dom/datastore/tests/test_duplicate.html
+++ b/dom/datastore/tests/test_duplicate.html
@@ -84,18 +84,17 @@
     },
 
     function() {
       if (SpecialPowers.isMainProcess()) {
         SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
       }
 
       SpecialPowers.setAllAppsLaunchable(true);
-      SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-      runTest();
+      SpecialPowers.pushPrefEnv({"set":[["dom.mozBrowserFramesEnabled", true]]}, runTest);
     },
 
     // No confirmation needed when an app is installed
     function() {
       SpecialPowers.autoConfirmAppInstall(() =>
         SpecialPowers.autoConfirmAppUninstall(runTest));
     },
 
--- a/dom/datastore/tests/test_keys.html
+++ b/dom/datastore/tests/test_keys.html
@@ -84,18 +84,17 @@
     },
 
     function() {
       if (SpecialPowers.isMainProcess()) {
         SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
       }
 
       SpecialPowers.setAllAppsLaunchable(true);
-      SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-      runTest();
+      SpecialPowers.pushPrefEnv({"set":[["dom.mozBrowserFramesEnabled", true]]}, runTest);
     },
 
     // No confirmation needed when an app is installed
     function() {
       SpecialPowers.autoConfirmAppInstall(() =>
         SpecialPowers.autoConfirmAppUninstall(runTest));
     },
 
--- a/dom/datastore/tests/test_oop.html
+++ b/dom/datastore/tests/test_oop.html
@@ -85,18 +85,17 @@
     },
 
     function() {
       if (SpecialPowers.isMainProcess()) {
         SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
       }
 
       SpecialPowers.setAllAppsLaunchable(true);
-      SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-      runTest();
+      SpecialPowers.pushPrefEnv({"set":[["dom.mozBrowserFramesEnabled", true]]}, runTest);
     },
 
     // No confirmation needed when an app is installed
     function() {
       SpecialPowers.autoConfirmAppInstall(() =>
         SpecialPowers.autoConfirmAppUninstall(runTest));
     },
 
--- a/dom/datastore/tests/test_oop_events.html
+++ b/dom/datastore/tests/test_oop_events.html
@@ -113,18 +113,17 @@
     },
 
     function() {
       if (SpecialPowers.isMainProcess()) {
         SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
       }
 
       SpecialPowers.setAllAppsLaunchable(true);
-      SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-      runTest();
+      SpecialPowers.pushPrefEnv({"set":[["dom.mozBrowserFramesEnabled", true]]}, runTest);
     },
 
     // No confirmation needed when an app is installed
     function() {
       SpecialPowers.autoConfirmAppInstall(() =>
         SpecialPowers.autoConfirmAppUninstall(runTest));
     },
 
--- a/dom/datastore/tests/test_readonly.html
+++ b/dom/datastore/tests/test_readonly.html
@@ -6,23 +6,25 @@
   <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
 </head>
 <body>
   <div id="container"></div>
   <script type="application/javascript;version=1.7">
   var gHostedManifestURL = 'http://test/tests/dom/datastore/tests/file_app.sjs?testToken=file_readonly.html';
   var gHostedManifestURL2 = 'http://example.com/tests/dom/datastore/tests/file_app.sjs?testToken=file_readonly.html&template=file_app2.template.webapp';
-  var gGenerator = runTest();
-
-  SpecialPowers.pushPermissions(
-    [{ "type": "browser", "allow": 1, "context": document },
-     { "type": "embed-apps", "allow": 1, "context": document },
-     { "type": "webapps-manage", "allow": 1, "context": document }],
-    function() { gGenerator.next() });
+  var gGenerator;
+  SpecialPowers.pushPrefEnv({"set": [["dom.mozBrowserFramesEnabled", true]]}, function() {
+    gGenerator = runTest();
+    SpecialPowers.pushPermissions(
+      [{ "type": "browser", "allow": 1, "context": document },
+       { "type": "embed-apps", "allow": 1, "context": document },
+       { "type": "webapps-manage", "allow": 1, "context": document }],
+       function() { gGenerator.next() });
+  });
 
   function continueTest() {
     try { gGenerator.next(); }
     catch(e) {}
   }
 
   function cbError() {
     ok(false, "Error callback invoked");
@@ -30,18 +32,16 @@
   }
 
   function runTest() {
     if (SpecialPowers.isMainProcess()) {
       SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
     }
 
     SpecialPowers.setAllAppsLaunchable(true);
-    SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-
     SpecialPowers.autoConfirmAppInstall(continueTest);
     yield undefined;
 
     SpecialPowers.autoConfirmAppUninstall(continueTest);
     yield undefined;
 
     var request = navigator.mozApps.install(gHostedManifestURL);
     request.onerror = cbError;
@@ -93,17 +93,16 @@
 
     // This event is triggered when the app calls "alert".
     ifr.addEventListener('mozbrowsershowmodalprompt', listener, false);
 
     domParent.appendChild(ifr);
   }
 
   function finish() {
-    SpecialPowers.clearUserPref("dom.mozBrowserFramesEnabled");
     SimpleTest.finish();
   }
 
   SimpleTest.waitForExplicitFinish();
   SpecialPowers.pushPrefEnv({"set": [["dom.datastore.enabled", true],
                                      ["dom.datastore.sysMsgOnChangeShortTimeoutSec", 1],
                                      ["dom.datastore.sysMsgOnChangeLongTimeoutSec", 3],
                                      ["dom.testing.ignore_ipc_principal", true],
--- a/dom/datastore/tests/test_sync.html
+++ b/dom/datastore/tests/test_sync.html
@@ -83,18 +83,17 @@
                                          ["dom.testing.datastore_enabled_for_hosted_apps", true]]}, runTest);
     },
 
     function() {
       if (SpecialPowers.isMainProcess()) {
         SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
       }
 
-      SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-      runTest();
+      SpecialPowers.pushPrefEnv({"set":[["dom.mozBrowserFramesEnabled", true]]}, runTest);
     },
 
     // No confirmation needed when an app is installed
     function() {
       SpecialPowers.autoConfirmAppInstall(() =>
         SpecialPowers.autoConfirmAppUninstall(runTest));
     },
 
--- a/dom/datastore/tests/test_sync_worker.html
+++ b/dom/datastore/tests/test_sync_worker.html
@@ -83,18 +83,17 @@
                                          ["dom.testing.datastore_enabled_for_hosted_apps", true]]}, runTest);
     },
 
     function() {
       if (SpecialPowers.isMainProcess()) {
         SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
       }
 
-      SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-      runTest();
+      SpecialPowers.pushPrefEnv({"set":[["dom.mozBrowserFramesEnabled", true]]}, runTest)
     },
 
     // No confirmation needed when an app is installed
     function() {
       SpecialPowers.autoConfirmAppInstall(() =>
         SpecialPowers.autoConfirmAppUninstall(runTest));
     },
 
--- a/dom/datastore/tests/test_transactions.html
+++ b/dom/datastore/tests/test_transactions.html
@@ -84,18 +84,17 @@
     },
 
     function() {
       if (SpecialPowers.isMainProcess()) {
         SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
       }
 
       SpecialPowers.setAllAppsLaunchable(true);
-      SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-      runTest();
+      SpecialPowers.pushPrefEnv({"set":[["dom.mozBrowserFramesEnabled", true]]}, runTest);
     },
 
     // No confirmation needed when an app is installed
     function() {
       SpecialPowers.autoConfirmAppInstall(() =>
         SpecialPowers.autoConfirmAppUninstall(runTest));
     },
 
--- a/dom/datastore/tests/test_worker_close.html
+++ b/dom/datastore/tests/test_worker_close.html
@@ -84,18 +84,17 @@
     },
 
     function() {
       if (SpecialPowers.isMainProcess()) {
         SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
       }
 
       SpecialPowers.setAllAppsLaunchable(true);
-      SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-      runTest();
+      SpecialPowers.pushPrefEnv({"set":[["dom.mozBrowserFramesEnabled", true]]}, runTest);
     },
 
     // No confirmation needed when an app is installed
     function() {
       SpecialPowers.autoConfirmAppInstall(() =>
         SpecialPowers.autoConfirmAppUninstall(runTest));
     },
 
--- a/dom/events/test/test_bug422132.html
+++ b/dom/events/test/test_bug422132.html
@@ -21,33 +21,33 @@ https://bugzilla.mozilla.org/show_bug.cg
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 /** Test for Bug 422132 **/
 
 SimpleTest.waitForExplicitFinish();
 SimpleTest.requestFlakyTimeout("untriaged");
-SimpleTest.waitForFocus(runTests, window);
+SimpleTest.waitForFocus(function() {
+  SpecialPowers.pushPrefEnv({
+    "set":[["general.smoothScroll", false],
+           ["mousewheel.min_line_scroll_amount", 1],
+           ["mousewheel.transaction.timeout", 100000]]}, runTests)}, window);
 
 function hitEventLoop(aFunc, aTimes)
 {
   if (--aTimes) {
     setTimeout(hitEventLoop, 0, aFunc, aTimes);
   } else {
     setTimeout(aFunc, 20);
   }
 }
 
 function runTests()
 {
-  SpecialPowers.setBoolPref("general.smoothScroll", false);
-  SpecialPowers.setIntPref("mousewheel.min_line_scroll_amount", 1);
-  SpecialPowers.setIntPref("mousewheel.transaction.timeout", 100000);
-
   var target = document.getElementById("target");
 
   var scrollLeft = target.scrollLeft;
   var scrollTop = target.scrollTop;
   synthesizeWheel(target, 10, 10,
     { deltaMode: WheelEvent.DOM_DELTA_PIXEL,
       deltaX: 0.5, deltaY: 0.5, lineOrPageDeltaX: 0, lineOrPageDeltaY: 0 });
   hitEventLoop(function () {
@@ -76,19 +76,16 @@ function runTests()
         synthesizeWheel(target, 10, 10,
           { deltaMode: WheelEvent.DOM_DELTA_LINE,
             deltaX: 0.5, deltaY: 0.5, lineOrPageDeltaX: 1, lineOrPageDeltaY: 1 });
         hitEventLoop(function () {
           ok(target.scrollLeft > scrollLeft,
              "not scrolled to right by 0.5 line delta value with pending 0.5 line delta");
           ok(target.scrollTop > scrollTop,
              "not scrolled to bottom by 0.5 line delta value with pending 0.5 line delta");
-          SpecialPowers.clearUserPref("general.smoothScroll");
-          SpecialPowers.clearUserPref("mousewheel.min_line_scroll_amount");
-          SpecialPowers.clearUserPref("mousewheel.transaction.timeout");
           SimpleTest.finish();
         }, 20);
       }, 20);
     }, 20);
   }, 20);
 }
 
 </script>
--- a/dom/events/test/test_bug563329.html
+++ b/dom/events/test/test_bug563329.html
@@ -33,19 +33,16 @@ function getTests() {
   ];
 
   let i = 0;
   while (i < tests.length)
     yield tests[i++];
 }
 
 function doTest() {
-  // Enable context menus
-  SpecialPowers.setBoolPref("ui.click_hold_context_menus", true);
-
   target = document.getElementById("testTarget");
 
   document.documentElement.addEventListener("contextmenu", function() {
     SimpleTest.ok(true, currentTest.message);
     synthesizeMouse(target, 0, 0, {type: "mouseup"});
     SimpleTest.executeSoon(function() {
       currentTest = tests.next();
       currentTest.func();
@@ -61,36 +58,25 @@ function doTest() {
 function doCheckContextMenu() {
   synthesizeMouse(target, 0, 0, {type: "mousedown"});
 }
 
 function doCheckDuration() {
   var duration = 50;
 
   // Change click hold delay
-  SpecialPowers.setIntPref("ui.click_hold_context_menus.delay", duration);
-
-  synthesizeMouse(target, 0, 0, {type: "mousedown"});
+  SpecialPowers.pushPrefEnv({"set":[["ui.click_hold_context_menus.delay", duration]]}, function() { synthesizeMouse(target, 0, 0, {type: "mousedown"}); });
 }
 
 function finishTest() {
   synthesizeKey("VK_ESCAPE", {}, window);
-  try {
-    SpecialPowers.clearUserPref("ui.click_hold_context_menus");
-  }
-  catch(e) {}
-
-  try {
-    SpecialPowers.clearUserPref("ui.click_hold_context_menus.delay");
-  }
-  catch(e) {}
-
   SimpleTest.finish();
 }
 
 SimpleTest.waitForExplicitFinish();
-addLoadEvent(doTest);
-
+addLoadEvent(function() {
+  SpecialPowers.pushPrefEnv({"set":[["ui.click_hold_context_menus", true]]}, doTest);
+});
 </script>
 </pre>
 <span id="testTarget" style="border: 1px solid black;">testTarget</span>
 </body>
 </html>
--- a/dom/events/test/test_bug574663.html
+++ b/dom/events/test/test_bug574663.html
@@ -55,17 +55,16 @@ function runTest() {
     // grab the refresh driver, since we want to make sure
     // async scrolls happen in deterministic time
     winUtils.advanceTimeAndRefresh(1000);
 
     function nextTest() {
       if (!outstandingTests.length) {
         winUtils.restoreNormalRefresh();
         win.close();
-        clearPrefs();
         SimpleTest.finish();
         return;
       }
 
       let [ctrlKey, isMomentum] = outstandingTests.shift();
       let scrollTopBefore = scrollbox.scrollTop;
       let zoomFactorBefore = winUtils.fullZoom;
 
@@ -93,37 +92,22 @@ function runTest() {
 
         setTimeout(nextTest, 20);
       }, 20);
     }
     nextTest();
   }, win);
 }
 
-function initPrefs()
-{
-  SpecialPowers.setBoolPref("general.smoothScroll", false);
-  // Disables the app level scroll acceleration
-  SpecialPowers.setIntPref("mousewheel.acceleration.start", -1);
-  SpecialPowers.setBoolPref("mousewheel.system_scroll_override_on_root_content.enabled", false);
-  // Enable zooming for ctrl-scrolling
-  SpecialPowers.setIntPref("mousewheel.with_control.action", 3);
-}
-
-function clearPrefs()
-{
-  SpecialPowers.clearUserPref("general.smoothScroll");
-  SpecialPowers.clearUserPref("mousewheel.acceleration.start");
-  SpecialPowers.clearUserPref("mousewheel.system_scroll_override_on_root_content.enabled");
-  SpecialPowers.clearUserPref("mousewheel.with_control.action");
-}
-
-window.onload = function () {
-  initPrefs();
-  SimpleTest.executeSoon(runTest);
+window.onload = function() {
+  SpecialPowers.pushPrefEnv({
+    "set":[["general.smoothScroll", false],
+           ["mousewheel.acceleration.start", -1],
+           ["mousewheel.system_scroll_override_on_root_content.enabled", false],
+           ["mousewheel.with_control.action", 3]]}, runTest);
 }
 
 SimpleTest.waitForExplicitFinish();
 SimpleTest.requestFlakyTimeout("untriaged");
 
 </script>
 </pre>
 
--- a/dom/events/test/test_bug607464.html
+++ b/dom/events/test/test_bug607464.html
@@ -58,43 +58,27 @@ function runTest() {
     window.mozRequestAnimationFrame(function() {
       // actually, wait for the next one before checking results, since
       // scrolling might not be flushed until after this code has run
       window.mozRequestAnimationFrame(function() {
         is(scrollbox.scrollTop, scrollTopBefore + 15,
            "Pixel scrolling should have finished after one refresh driver iteration. " +
            "We shouldn't be scrolling smoothly, even though the pref is set.");
         win.close();
-        clearPrefs();
         SimpleTest.finish();
       });
     });
   }, win);
 }
 
-function initPrefs()
-{
-  // Disables the app level scroll acceleration
-  SpecialPowers.setIntPref("mousewheel.acceleration.start", -1);
-  SpecialPowers.setBoolPref("mousewheel.system_scroll_override_on_root_content.enabled", false);
-
-  // Enables smooth scrolling
-  SpecialPowers.setBoolPref("general.smoothScroll", true);
-}
-
-function clearPrefs()
-{
-  SpecialPowers.clearUserPref("mousewheel.acceleration.start");
-  SpecialPowers.clearUserPref("mousewheel.system_scroll_override_on_root_content.enabled");
-  SpecialPowers.clearUserPref("general.smoothScroll");
-}
-
-window.onload = function () {
-  initPrefs();
-  SimpleTest.executeSoon(runTest);
+window.onload = function() {
+  SpecialPowers.pushPrefEnv({
+    "set":[["general.smoothScroll", true],
+           ["mousewheel.acceleration.start", -1],
+           ["mousewheel.system_scroll_override_on_root_content.enabled", false]]}, runTest);
 }
 
 SimpleTest.waitForExplicitFinish();
 
 </script>
 </pre>
 
 </body>
--- a/dom/events/test/test_bug822898.html
+++ b/dom/events/test/test_bug822898.html
@@ -325,36 +325,24 @@ function runTests() {
   tests.push(testPreventDefault);
   tests.push(testBlockPreventDefault);
 
   tests.push(testBlockBubbling);
   tests.push(testOnPointerProperty());
   tests.push(testPointerEventCTORS());
 
   tests.push(function() {
-    clearPrefs();
     SimpleTest.finish();
   });
 
   nextTest();
 }
 
-function initPrefs()
-{
-  SpecialPowers.setBoolPref("dom.w3c_pointer_events.enabled", true);      // Enable Pointer Events
-}
-
-function clearPrefs()
-{
-  SpecialPowers.clearUserPref("dom.w3c_pointer_events.enabled");      // Disable Pointer Events
-}
-
-window.onload = function () {
-  initPrefs();
-  SimpleTest.executeSoon(runTests);
+window.onload = function() {
+  SpecialPowers.pushPrefEnv({"set":[["dom.w3c_pointer_events.enabled", true]]}, runTests);
 }
 
 SimpleTest.waitForExplicitFinish();
 
 </script>
 </pre>
 <div id="parent">
   <span id="testTarget" style="border: 1px solid black;">testTarget</span>
--- a/dom/html/test/file_fullscreen-api.html
+++ b/dom/html/test/file_fullscreen-api.html
@@ -45,20 +45,16 @@ var inDocElement = null;
 var container = null;
 var button = null;
 
 
 function sendMouseClick(element) {
   synthesizeMouseAtCenter(element, {});
 }
 
-function setRequireTrustedContext(value) {
-  opener.SpecialPowers.setBoolPref("full-screen-api.allow-trusted-requests-only", value);
-}
-
 function fullScreenElement() {
   return document.getElementById('full-screen-element');
 }
 
 function enter1(event) {
   ok(document.mozFullScreen, "1. Should be in full-screen mode (first time)");
   is(event.target, document, "2. Event target should be full-screen document #1");
   is(document.mozFullScreenElement, fullScreenElement(), "3. Full-screen element should be div element.");
@@ -208,20 +204,20 @@ function enter_from_arg_test_2(event) {
   ok(document.mozFullScreen, "Should have entered full-screen after calling with vrDisplay null argument (fifth time)");
   addFullscreenChangeContinuation("exit", exit4);
   document.mozCancelFullScreen();
   ok(!document.mozFullScreen, "Should have left full-screen mode.");
 }
 
 function exit4(event) {
   ok(!document.mozFullScreen, "38. Should be back in non-full-screen mode (fifth time)");
-  setRequireTrustedContext(true);
-
-  addFullscreenErrorContinuation(error2);
-  fullScreenElement().mozRequestFullScreen();
+  SpecialPowers.pushPrefEnv({"set":[["full-screen-api.allow-trusted-requests-only", true]]}, function() {
+    addFullscreenErrorContinuation(error2);
+    fullScreenElement().mozRequestFullScreen();
+  });
 }
 
 function error2(event) {
   ok(!document.mozFullScreen, "Should still be in normal mode, because calling context isn't trusted.");
   button = document.createElement("button");
   button.onclick = function(){fullScreenElement().mozRequestFullScreen();}
   fullScreenElement().appendChild(button);
   addFullscreenChangeContinuation("enter", enter5);
@@ -232,32 +228,32 @@ function enter5(event) {
   ok(document.mozFullScreen, "Moved to full-screen after mouse click");
   addFullscreenChangeContinuation("exit", exit5);
   document.mozCancelFullScreen();
   ok(!document.mozFullScreen, "Should have left full-screen mode.");
 }
 
 function exit5(event) {
   ok(!document.mozFullScreen, "Should have left full-screen mode (last time).");
-  setRequireTrustedContext(false);
-
-  SpecialPowers.setBoolPref("full-screen-api.enabled", false);
-  is(document.mozFullScreenEnabled, false, "document.mozFullScreenEnabled should be false if full-screen-api.enabled is false");
-
-  addFullscreenErrorContinuation(error3);
-  fullScreenElement().mozRequestFullScreen();
+  SpecialPowers.pushPrefEnv({
+    "set":[["full-screen-api.allow-trusted-requests-only", false],
+           ["full-screen-api.enabled", false]]}, function() {
+              is(document.mozFullScreenEnabled, false, "document.mozFullScreenEnabled should be false if full-screen-api.enabled is false");
+              addFullscreenErrorContinuation(error3);
+              fullScreenElement().mozRequestFullScreen();
+  });
 }
 
 function error3(event) {
   ok(!document.mozFullScreen, "Should still be in normal mode, because pref is not enabled.");
 
-  SpecialPowers.setBoolPref("full-screen-api.enabled", true);
-  is(document.mozFullScreenEnabled, true, "document.mozFullScreenEnabled should be true if full-screen-api.enabled is true");
-
-  opener.nextTest();
+  SpecialPowers.pushPrefEnv({"set":[["full-screen-api.enabled", true]]}, function() {
+    is(document.mozFullScreenEnabled, true, "document.mozFullScreenEnabled should be true if full-screen-api.enabled is true");
+    opener.nextTest();
+  });
 }
 
 function begin() {
   addFullscreenChangeContinuation("enter", enter1);
   fullScreenElement().mozRequestFullScreen();
 }
 
 </script>
--- a/dom/html/test/file_fullscreen-denied.html
+++ b/dom/html/test/file_fullscreen-denied.html
@@ -37,26 +37,28 @@ function begin() {
     function() {
       ok(false, "Should never receive a mozfullscreenchange event in the main window.");
       gotFullScreenChange = true;
     },
     false);
 
   // Request full-screen from a non trusted context (this script isn't a user
   // generated event!).
-  SpecialPowers.setBoolPref("full-screen-api.allow-trusted-requests-only", true);
-  addFullscreenErrorContinuation(
-    function() {
-      ok(!document.mozFullScreen, "Should not grant request in non-trusted context");
-      // Test requesting full-screen mode in a long-running user-generated event handler.
-      // The request in the key handler should not be granted.
-      window.addEventListener("keypress", keyHandler, false);
-      synthesizeKey("VK_A", {});
-    });
-  document.body.mozRequestFullScreen();
+  SpecialPowers.pushPrefEnv({"set":[["full-screen-api.allow-trusted-requests-only", true]]}, startTest);
+  function startTest() {
+    addFullscreenErrorContinuation(
+      function() {
+        ok(!document.mozFullScreen, "Should not grant request in non-trusted context");
+        // Test requesting full-screen mode in a long-running user-generated event handler.
+        // The request in the key handler should not be granted.
+        window.addEventListener("keypress", keyHandler, false);
+        synthesizeKey("VK_A", {});
+      });
+    document.body.mozRequestFullScreen();
+ }
 }
 
 function keyHandler(event) {
   window.removeEventListener("keypress", keyHandler, false);
 
   // Busy loop until 2s has passed. We should then be past the 1 second threshold, and so
   // our request for full-screen mode should be rejected.
   var end = (new Date()).getTime() + 2000;
@@ -64,24 +66,24 @@ function keyHandler(event) {
     ; // Wait...
   }
   addFullscreenErrorContinuation(
     function() {
       ok(!document.mozFullScreen, "Should not grant request in long-running event handler.");
 
       // Disable the requirement for trusted contexts only, so the tests are easier
       // to write.
-      SpecialPowers.setBoolPref("full-screen-api.allow-trusted-requests-only", false);
-
-      // Create an iframe without a allowfullscreen attribute, whose contents requests
-      // full-screen. The request should be denied, and we should not receive a fullscreenchange
-      // event in this document.
-      var iframe = document.createElement("iframe");
-      iframe.src = "file_fullscreen-denied-inner.html";
-      document.body.appendChild(iframe);
+      SpecialPowers.pushPrefEnv({"set":[["full-screen-api.allow-trusted-requests-only", false]]}, function() {
+        // Create an iframe without a allowfullscreen attribute, whose contents requests
+        // full-screen. The request should be denied, and we should not receive a fullscreenchange
+        // event in this document.
+        var iframe = document.createElement("iframe");
+        iframe.src = "file_fullscreen-denied-inner.html";
+        document.body.appendChild(iframe);
+      });
     });
   document.body.mozRequestFullScreen();
 }
 
 function finish() {
   ok(!gotFullScreenChange, "Should not ever grant a fullscreen request in this doc.");
   opener.nextTest();
 }
--- a/dom/html/test/file_fullscreen-esc-context-menu.html
+++ b/dom/html/test/file_fullscreen-esc-context-menu.html
@@ -51,22 +51,22 @@ function begin() {
                     .rootTreeItem
                     .QueryInterface(Ci.nsIInterfaceRequestor)
                     .getInterface(Ci.nsIDOMWindow)
                     .QueryInterface(Ci.nsIDOMChromeWindow);
   contextMenu = chromeWin.document.getElementById("contentAreaContextMenu");
   ok(contextMenu, "Got context menu XUL");
 
   addFullscreenChangeContinuation("enter", fullscreenEntered);
-  SpecialPowers.setBoolPref("full-screen-api.approval-required", false);
-  document.body.mozRequestFullScreen();
+  SpecialPowers.pushPrefEnv({"set":[["full-screen-api.approval-required", false]]}, function() {
+    document.body.mozRequestFullScreen();
+  });
 }
 
 function finish() {
-  SpecialPowers.clearUserPref("full-screen-api.approval-required");
   opener.nextTest();
 }
 
 function fullscreenEntered(event) {
   ok(document.mozFullScreen, "Should have entered fullscreen mode");
   is(document.mozFullScreenElement, document.body, "FSE should be doc");
   contextMenu.addEventListener("popupshown", contextMenuOpened, false);
   is(contextMenu.state, "closed", "Should not have opened context menu");
--- a/dom/html/test/forms/test_input_number_key_events.html
+++ b/dom/html/test/forms/test_input_number_key_events.html
@@ -20,25 +20,23 @@ https://bugzilla.mozilla.org/show_bug.cg
 <script type="application/javascript">
 
 /**
  * Test for Bug 935506
  * This test checks how the value of <input type=number> changes in response to
  * key events while it is in various states.
  **/
 SimpleTest.waitForExplicitFinish();
-
 // Turn off Spatial Navigation because it hijacks arrow keydown events:
-SpecialPowers.setBoolPref("snav.enabled", false);
-
 SimpleTest.waitForFocus(function() {
-  test();
-  SimpleTest.finish();
+  SpecialPowers.pushPrefEnv({"set":[["snav.enabled", false]]}, function() {
+    test();
+    SimpleTest.finish();
+  });
 });
-
 const defaultMinimum = "NaN";
 const defaultMaximum = "NaN";
 const defaultStep = 1;
 
 // Helpers:
 // For the sake of simplicity, we do not currently support fractional value,
 // step, etc.
 
--- a/dom/html/test/forms/test_input_radio_radiogroup.html
+++ b/dom/html/test/forms/test_input_radio_radiogroup.html
@@ -36,35 +36,40 @@ https://bugzilla.mozilla.org/show_bug.cg
 
   <fieldset>
     <input type="radio" name="testthree" id="start3"></input>
     <input type="radio" name="errorthree" id="testthree"></input>
   </fieldset>
 </form>
 <script class="testbody" type="text/javascript">
 /** Test for Bug 343444 **/
-document.getElementById("start").focus();
-var count=0;
-while (count < 2) {
-  sendKey("DOWN");
-  is(document.activeElement.type, "radio", "radioGroup should ignore non-radio input fields");
-  if (document.activeElement.id == "start") {
+SimpleTest.waitForExplicitFinish();
+SpecialPowers.pushPrefEnv({"set":[["snav.enabled", false]]}, startTest);
+function startTest() {
+  document.getElementById("start").focus();
+  var count=0;
+  while (count < 2) {
+    sendKey("DOWN");
+    is(document.activeElement.type, "radio", "radioGroup should ignore non-radio input fields");
+    if (document.activeElement.id == "start") {
+      count++;
+    }
+  }
+
+  document.getElementById("start2").focus();
+  count = 0;
+  while (count < 3) {
+    is(document.activeElement.name, "testtwo",
+       "radioGroup should only contain elements with the same @name")
+    sendKey("DOWN");
     count++;
   }
+
+  document.getElementById("start3").focus();
+  sendKey("DOWN");
+  is(document.activeElement.name, "testthree", "we don't have an infinite-loop");
+  SimpleTest.finish();
 }
-
-document.getElementById("start2").focus();
-count = 0;
-while (count < 3) {
-  is(document.activeElement.name, "testtwo",
-     "radioGroup should only contain elements with the same @name")
-  sendKey("DOWN");
-  count++;
-}
-
-document.getElementById("start3").focus();
-sendKey("DOWN");
-is(document.activeElement.name, "testthree", "we don't have an infinite-loop");
 </script>
 </pre>
 </body>
 </html>
 
--- a/dom/html/test/forms/test_input_range_key_events.html
+++ b/dom/html/test/forms/test_input_range_key_events.html
@@ -21,21 +21,21 @@ https://bugzilla.mozilla.org/show_bug.cg
 /**
  * Test for Bug 843725
  * This test checks how the value of <input type=range> changes in response to
  * various key events while it is in various states.
  **/
 SimpleTest.waitForExplicitFinish();
 
 // Turn off Spatial Navigation because it hijacks arrow keydown events:
-SpecialPowers.setBoolPref("snav.enabled", false);
-
 SimpleTest.waitForFocus(function() {
-  test();
-  SimpleTest.finish();
+  SpecialPowers.pushPrefEnv({"set":[["snav.enabled", false]]}, function() {
+    test();
+    SimpleTest.finish();
+  });
 });
 
 const defaultMinimum = 0;
 const defaultMaximum = 100;
 const defaultStep = 1;
 
 // Helpers:
 // For the sake of simplicity, we do not currently support fractional value,
--- a/dom/html/test/forms/test_input_range_rounding.html
+++ b/dom/html/test/forms/test_input_range_rounding.html
@@ -21,23 +21,22 @@ https://bugzilla.mozilla.org/show_bug.cg
 
 /**
  * Test for Bug 853525
  * This test checks that when <input type=range> has fractional step values,
  * the values that a content author will see in their script will not have
  * ugly rounding errors.
  **/
 SimpleTest.waitForExplicitFinish();
-
-// Turn off spatial navigation because it hijacks arrow keydown events:
-SpecialPowers.setBoolPref("snav.enabled", false);
-
+// Turn off Spatial Navigation because it hijacks arrow keydown events:
 SimpleTest.waitForFocus(function() {
-  test();
-  SimpleTest.finish();
+  SpecialPowers.pushPrefEnv({"set":[["snav.enabled", false]]}, function() {
+    test();
+    SimpleTest.finish();
+  });
 });
 
 /**
  * We can _NOT_ generate these values by looping and simply incrementing a
  * variable by 0.01 and stringifying it, since we'll end up with strings like
  * "0.060000000000000005" due to the inability of binary floating point numbers
  * to accurately represent decimal values.
  */
--- a/dom/html/test/forms/test_radio_in_label.html
+++ b/dom/html/test/forms/test_radio_in_label.html
@@ -18,34 +18,37 @@ https://bugzilla.mozilla.org/show_bug.cg
     <span id="s1">LABEL</span>
     <input type="radio" name="rdo" value="1" id="r1" onmousedown="document.body.appendChild(document.createTextNode('down'));">
     <input type="radio" name="rdo" value="2" id="r2" checked="checked">
   </label>
 </form>
 <script class="testbody" type="text/javascript">
 
 /** Test for Bug 229925 **/
+SimpleTest.waitForExplicitFinish();
 var r1 = document.getElementById("r1");
 var r2 = document.getElementById("r2");
 var s1 = document.getElementById("s1");
+SpecialPowers.pushPrefEnv({"set":[["snav.enabled", false]]}, startTest);
+function startTest() {
+  r1.click();
+  ok(r1.checked,
+     "The first radio input element should be checked by clicking the element");
+  r2.click();
+  ok(r2.checked,
+     "The second radio input element should be checked by clicking the element");
+  s1.click();
+  ok(r1.checked,
+     "The first radio input element should be checked by clicking other element");
 
-r1.click();
-ok(r1.checked,
-   "The first radio input element should be checked by clicking the element");
-r2.click();
-ok(r2.checked,
-   "The second radio input element should be checked by clicking the element");
-s1.click();
-ok(r1.checked,
-   "The first radio input element should be checked by clicking other element");
-
-r1.focus();
-synthesizeKey("VK_LEFT", {});
-ok(r2.checked,
-   "The second radio input element should be checked by key");
-synthesizeKey("VK_LEFT", {});
-ok(r1.checked,
-   "The first radio input element should be checked by key");
-
+  r1.focus();
+  synthesizeKey("VK_LEFT", {});
+  ok(r2.checked,
+     "The second radio input element should be checked by key");
+  synthesizeKey("VK_LEFT", {});
+  ok(r1.checked,
+     "The first radio input element should be checked by key");
+  SimpleTest.finish();
+}
 </script>
 </pre>
 </body>
 </html>
--- a/dom/html/test/forms/test_valueAsDate_pref.html
+++ b/dom/html/test/forms/test_valueAsDate_pref.html
@@ -15,26 +15,27 @@ https://bugzilla.mozilla.org/show_bug.cg
   var pref = SpecialPowers.getBoolPref("dom.experimental_forms");
 
   SimpleTest.waitForExplicitFinish();
 
   function runTest(iframe) {
     var state = states.shift();
 
     if (state == 'end') {
-      SpecialPowers.setBoolPref("dom.experimental_forms", pref);
       SimpleTest.finish();
       return;
     }
 
-    SpecialPowers.setBoolPref("dom.experimental_forms", state === 'true');
-    iframe.src = 'data:text/html,<script>' +
+    SpecialPowers.pushPrefEnv({"set":[["dom.experimental_forms", state === 'true']]}, 
+      function() {
+        iframe.src = 'data:text/html,<script>' +
                  'parent.is("valueAsDate" in document.createElement("input"), ' +
                  state + ', "valueAsDate presence state should be ' + state + '");' +
                  '<\/script>'
+     });
   }
 
   </script>
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=874640">Mozilla Bug 874640</a>
 <p id="display"></p>
 <div id="content" style="display: none">
--- a/dom/html/test/test_bug369370.html
+++ b/dom/html/test/test_bug369370.html
@@ -84,22 +84,23 @@ https://bugzilla.mozilla.org/show_bug.cg
         ok(true, "----- click 4 -----");
 
         is(img.width,  400, "image width");
         is(img.height, 300, "image height");
         is(kidDoc.body.scrollLeft,  0, "Checking scrollLeft");
         is(kidDoc.body.scrollTop,   0, "Checking scrollTop");
 
         kidWin.close();
-        SpecialPowers.clearUserPref("browser.enable_automatic_image_resizing");
         SimpleTest.finish();
     }
+    var kidWin;
+    var kidDoc;
 
     SimpleTest.waitForExplicitFinish();
-    SpecialPowers.setBoolPref("browser.enable_automatic_image_resizing", true);
-
-    var kidWin = window.open("bug369370-popup.png", "bug369370", "width=400,height=300");
-    var kidDoc; // will init onload
-    ok(kidWin, "opened child window");
-    kidWin.onload = childLoaded;
+    SpecialPowers.pushPrefEnv({"set":[["browser.enable_automatic_image_resizing", true]]}, function() {
+       kidWin = window.open("bug369370-popup.png", "bug369370", "width=400,height=300");
+       // will init onload
+       ok(kidWin, "opened child window");
+       kidWin.onload = childLoaded;
+    });
   </script>
 </body>
 </html>
--- a/dom/html/test/test_bug633058.html
+++ b/dom/html/test/test_bug633058.html
@@ -18,19 +18,20 @@ https://bugzilla.mozilla.org/show_bug.cg
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 633058 **/
 
 SimpleTest.waitForExplicitFinish();
 
 // Turn off Spatial Navigation so that the 'keypress' event fires.
-SpecialPowers.setBoolPref('snav.enabled', false);
-
 SimpleTest.waitForFocus(function() {
+  SpecialPowers.pushPrefEnv({"set":[['snav.enabled', false]]}, startTest);
+});
+function startTest() {
   var nbExpectedKeyPress = 8;
   var inputGotKeyPress = 0;
   var divGotKeyPress = 0;
 
   var input = document.getElementsByTagName('input')[0];
   var content = document.getElementById('content');
 
   content.addEventListener('keypress', function() {
@@ -55,14 +56,13 @@ SimpleTest.waitForFocus(function() {
     synthesizeKey('VK_RIGHT', {});
     synthesizeKey('VK_DOWN', {});
     synthesizeKey('VK_BACK_SPACE', {});
     synthesizeKey('VK_DELETE', {});
     synthesizeKey('VK_ESCAPE', {});
     synthesizeKey('VK_RETURN', {});
   }, false);
   input.focus();
-});
-
+}
 </script>
 </pre>
 </body>
 </html>
--- a/dom/html/test/test_bug674558.html
+++ b/dom/html/test/test_bug674558.html
@@ -17,19 +17,20 @@ https://bugzilla.mozilla.org/show_bug.cg
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 674558 **/
 SimpleTest.waitForExplicitFinish();
 
 // Turn off spatial navigation because it hijacks VK_RIGHT and VK_LEFT keydown
 // events.
-SpecialPowers.setBoolPref("snav.enabled", false);
-
 SimpleTest.waitForFocus(function() {
+  SpecialPowers.pushPrefEnv({"set":[["snav.enabled", false]]}, startTest);
+});
+function startTest() {
   function textAreaCtor() {
     return document.createElement("textarea");
   }
   var ctors = [textAreaCtor];
   ["text", "password", "search"].forEach(function(type) {
     ctors.push(function inputCtor() {
       var input = document.createElement("input");
       input.type = type;
@@ -37,17 +38,17 @@ SimpleTest.waitForFocus(function() {
     });
   });
 
   for (var ctor in ctors) {
     test(ctors[ctor]);
   }
 
   SimpleTest.finish();
-});
+}
 
 function test(ctor) {
   var elem = ctor();
   ok(true, "Testing " + name(elem));
 
   ok("selectionDirection" in elem, "elem should have the selectionDirection property");
 
   is(elem.selectionStart, 0, "Default value");
--- a/dom/html/test/test_fullscreen-api.html
+++ b/dom/html/test/test_fullscreen-api.html
@@ -17,24 +17,16 @@
 <p id="display"></p>
 <div id="content" style="display: none">
 
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 /** Tests for Bug 545812 **/
-
-// Ensure the full-screen api is enabled, and will be disabled on test exit.
-SpecialPowers.setBoolPref("full-screen-api.enabled", true);
-
-// Disable the requirement for trusted contexts only, so the tests are easier
-// to write.
-SpecialPowers.setBoolPref("full-screen-api.allow-trusted-requests-only", false);
-
 SimpleTest.requestFlakyTimeout("untriaged");
 
 // Run the tests which go full-screen in new windows, as mochitests normally
 // run in an iframe, which by default will not have the allowfullscreen
 // attribute set, so full-screen won't work.
 var gTestWindows = [
   "file_fullscreen-ancestor-stacking-context.html",
   "file_fullscreen-multiple.html",
@@ -89,31 +81,34 @@ function runNextTest() {
     testWindow.addEventListener("load", function onload() {
       testWindow.removeEventListener("load", onload, false);
       SimpleTest.waitForFocus(function() {
         SimpleTest.waitForFocus(testWindow.begin, testWindow);
       });
     }, false);
     gTestIndex++;
   } else {
-    SpecialPowers.clearUserPref("full-screen-api.enabled");
-    SpecialPowers.clearUserPref("full-screen-api.allow-trusted-requests-only");
     SimpleTest.finish();
   }
 }
 
 if (isOSXLion || isOSXMtnLion || isOSXYosemite) {
   todo(false, "Can't reliably run full-screen tests on OS X (bug 900453 comment 18 & bug 802504)");
 } else {
   try {
     window.fullScreen = true;
   } catch (e) {
   }
   is(window.fullScreen, false, "Shouldn't be able to set window fullscreen from content");
-
-  addLoadEvent(nextTest);
+  // Ensure the full-screen api is enabled, and will be disabled on test exit.
+  // Disable the requirement for trusted contexts only, so the tests are easier
+  // to write
+  addLoadEvent(function() {
+    SpecialPowers.pushPrefEnv({
+      "set":[["full-screen-api.enabled", true],
+             ["full-screen-api.allow-trusted-requests-only", false]]}, nextTest);
+  });
   SimpleTest.waitForExplicitFinish();
 }
-
 </script>
 </pre>
 </body>
 </html>
--- a/dom/network/tests/test_networkstats_enabled_no_perm.html
+++ b/dom/network/tests/test_networkstats_enabled_no_perm.html
@@ -9,40 +9,42 @@
 <p id="display"></p>
 <div id="content" style="display: none">
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 // Test to ensure NetworkStats is enabled but mozNetworkStats.getAvailableNetworks
 // does not work in content because mozNetworkStats is null when no permission.
-
-SpecialPowers.setBoolPref("dom.mozNetworkStats.enabled", true);
-SpecialPowers.removePermission("networkstats-manage", document);
+  SimpleTest.waitForExplicitFinish();
+  SpecialPowers.pushPrefEnv({"set": [['dom.mozNetworkStats.enabled', true]]}, runTest);
+  function runTest() {
+    SpecialPowers.removePermission("networkstats-manage", document);
 
-ok(SpecialPowers.getBoolPref("dom.mozNetworkStats.enabled"),
-   "Preference 'dom.mozNetworkStats.enabled' is true.");
+    ok(SpecialPowers.getBoolPref("dom.mozNetworkStats.enabled"),
+      "Preference 'dom.mozNetworkStats.enabled' is true.");
 
-ok(!SpecialPowers.hasPermission("networkstats-manage", document),
-   "Has no permission 'networkstats-manage'.");
+    ok(!SpecialPowers.hasPermission("networkstats-manage", document),
+      "Has no permission 'networkstats-manage'.");
 
-ok('mozNetworkStats' in navigator, "navigator.mozNetworkStats should exist");
+    ok('mozNetworkStats' in navigator, "navigator.mozNetworkStats should exist");
 
-is(navigator.mozNetworkStats, null,
-   "mozNetworkStats should be null when no permission.");
+    is(navigator.mozNetworkStats, null,
+      "mozNetworkStats should be null when no permission.");
 
-var error;
-try {
-  navigator.mozNetworkStats.getAvailableNetworks;
+    var error;
+    try {
+      navigator.mozNetworkStats.getAvailableNetworks;
 
-  ok(false,
-  	 "Accessing navigator.mozNetworkStats.getAvailableNetworks should throw!");
-} catch (ex) {
-  error = ex;
+      ok(false,
+    	   "Accessing navigator.mozNetworkStats.getAvailableNetworks should throw!");
+        } catch (ex) {
+          error = ex;
+        }
+
+   ok(error,
+     "Got an exception accessing navigator.mozNetworkStats.getAvailableNetworks");
+   SimpleTest.finish();
 }
-
-ok(error,
-   "Got an exception accessing navigator.mozNetworkStats.getAvailableNetworks");
-
 </script>
 </pre>
 </body>
 </html>
--- a/dom/network/tests/test_tcpsocket_enabled_no_perm.html
+++ b/dom/network/tests/test_tcpsocket_enabled_no_perm.html
@@ -11,25 +11,25 @@
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test to ensure TCPSocket permission being turned on enables 
   navigator.mozTCPSocket, but mozTCPSocket.open does not work
   in content.
 **/
-SpecialPowers.setBoolPref("dom.mozTCPSocket.enabled", true);
-
-ok('mozTCPSocket' in navigator, "navigator.mozTCPSocket should be accessible if dom.mozTCPSocket.enabled is true");
+SimpleTest.waitForExplicitFinish();
+SpecialPowers.pushPrefEnv({"set": [['dom.mozTCPSocket.enabled', true]]}, runTest);
+function runTest() {
+  ok('mozTCPSocket' in navigator, "navigator.mozTCPSocket should be accessible if dom.mozTCPSocket.enabled  is true");
 
-try {
-  navigator.mozTCPSocket.open('localhost', 80);
-  throw new Error("Error: navigator.mozTCPSocket.open should raise for content that does not have the tcp-socket permission");
-} catch (e) {
-  ok(true, "navigator.mozTCPSocket.open should raise for content that does not have the tcp-socket permission");
+  try {
+    navigator.mozTCPSocket.open('localhost', 80);
+    throw new Error("Error: navigator.mozTCPSocket.open should raise for content that does not have the tcp-socket permission");
+  } catch (e) {
+      ok(true, "navigator.mozTCPSocket.open should raise for content that does not have the tcp-socket permission");
+  }
+  SimpleTest.finish();
 }
-
-SpecialPowers.setBoolPref("dom.mozTCPSocket.enabled", false);
-
 </script>
 </pre>
 </body>
 </html>
--- a/dom/network/tests/test_tcpsocket_enabled_with_perm.html
+++ b/dom/network/tests/test_tcpsocket_enabled_with_perm.html
@@ -11,21 +11,22 @@
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test to ensure TCPSocket permission being turned on enables 
   navigator.mozTCPSocket, and mozTCPSocket.open works when
   the tcp-socket permission has been granted.
 **/
-SpecialPowers.setBoolPref("dom.mozTCPSocket.enabled", true);
-SpecialPowers.addPermission("tcp-socket", true, document);
-
-ok('mozTCPSocket' in navigator, "navigator.mozTCPSocket should be accessible if dom.mozTCPSocket.enabled is true");
+SimpleTest.waitForExplicitFinish();
+SpecialPowers.pushPrefEnv({"set": [['dom.mozTCPSocket.enabled', true]]}, runTest);
+function runTest() {
+  SpecialPowers.addPermission("tcp-socket", true, document);
 
-ok(navigator.mozTCPSocket.open('localhost', 80), "navigator.mozTCPSocket.open should work for content that has the tcp-socket permission");
+  ok('mozTCPSocket' in navigator, "navigator.mozTCPSocket should be accessible if dom.mozTCPSocket.enabled is true");
 
-SpecialPowers.setBoolPref("dom.mozTCPSocket.enabled", false);
-
+  ok(navigator.mozTCPSocket.open('localhost', 80), "navigator.mozTCPSocket.open should work for content that has the tcp-socket permission");
+  SimpleTest.finish();
+}
 </script>
 </pre>
 </body>
 </html>
--- a/dom/requestsync/tests/test_basic_app.html
+++ b/dom/requestsync/tests/test_basic_app.html
@@ -85,18 +85,17 @@
     },
 
     function() {
       if (SpecialPowers.isMainProcess()) {
         SpecialPowers.Cu.import("resource://gre/modules/RequestSyncService.jsm");
       }
 
       SpecialPowers.setAllAppsLaunchable(true);
-      SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
-      runTests();
+      SpecialPowers.pushPrefEnv({"set":[["dom.mozBrowserFramesEnabled", true]]}, runTests);
     },
 
     // No confirmation needed when an app is installed
     function() {
       SpecialPowers.autoConfirmAppInstall(() =>
         SpecialPowers.autoConfirmAppUninstall(runTests));
     },
 
--- a/dom/tests/mochitest/bugs/test_bug265203.html
+++ b/dom/tests/mochitest/bugs/test_bug265203.html
@@ -35,21 +35,16 @@ https://bugzilla.mozilla.org/show_bug.cg
 </p>
 <div id="content" style="display: none">
   
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 265203 **/
-
-// Turn off spatial navigation because it hijacks VK_RIGHT and VK_LEFT keydown
-// events
-SpecialPowers.setBoolPref("snav.enabled", false);
-
 var gTestStarted = false;
 var expectedResult = [ null, 0, null ];
 var nextTest;
 var test = 0;
 
 function testFocus() {
     var selection = window.getSelection()
     is(selection.focusNode, expectedResult[0],"test" + test + ": " + "caret node");
@@ -96,18 +91,19 @@ function test3() {
     nextTest = SimpleTest.finish;
     testFocus();
 }
 
 function startTest() {
   if (gTestStarted)
     return;
   gTestStarted = true;
-
-  SpecialPowers.pushPrefEnv({"set": [["accessibility.browsewithcaret", true]]}, test0);
+  // Turn off spatial navigation because it hijacks VK_RIGHT and VK_LEFT keydown
+  // events
+  SpecialPowers.pushPrefEnv({"set": [["accessibility.browsewithcaret", true], ["snav.enabled", false]]}, test0);
 }
 
 SimpleTest.waitForExplicitFinish();
 SimpleTest.waitForFocus(startTest);
 
 </script>
 </pre>
 </body>
--- a/dom/tests/mochitest/chrome/test_MozEnteredDomFullscreen_event.xul
+++ b/dom/tests/mochitest/chrome/test_MozEnteredDomFullscreen_event.xul
@@ -8,21 +8,18 @@
 
   <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>      
 
 <script>
 SimpleTest.waitForExplicitFinish();
 
 // Ensure the full-screen api is enabled, and will be disabled on test exit.
 var gPrevEnabled = SpecialPowers.getBoolPref("full-screen-api.enabled");
-SpecialPowers.setBoolPref("full-screen-api.enabled", true);
-
 var gPrevTrusted = SpecialPowers.getBoolPref("full-screen-api.allow-trusted-requests-only");
-SpecialPowers.setBoolPref("full-screen-api.allow-trusted-requests-only", false);
-
+var newwindow;
 const Cc = Components.classes;
 const Ci = Components.interfaces;
 
 function make_uri(url) {
   var ios = Cc["@mozilla.org/network/io-service;1"].
             getService(Ci.nsIIOService);
   return ios.newURI(url, null, null);
 }
@@ -30,23 +27,26 @@ function make_uri(url) {
 // Ensure "fullscreen" permissions are not present on the test URI.
 var pm = Cc["@mozilla.org/permissionmanager;1"].getService(Ci.nsIPermissionManager);
 var uri = make_uri("http://mochi.test:8888");
 var principal = Components.classes["@mozilla.org/scriptsecuritymanager;1"]
                   .getService(Ci.nsIScriptSecurityManager)
                   .getNoAppCodebasePrincipal(uri);
 pm.removeFromPrincipal(principal, "fullscreen");
 
-newwindow = window.open("MozEnteredDomFullscreen_chrome.xul", "_blank","chrome,resizable=yes,width=400,height=400");
+SpecialPowers.pushPrefEnv({"set": [['full-screen-api.enabled', true],
+                                   ['full-screen-api.allow-trusted-requests-only', false]]}, setup);
+
+function setup() {
+   newwindow = window.open("MozEnteredDomFullscreen_chrome.xul", "_blank","chrome,resizable=yes,width=400,height=400");
+}
 
 function done()
 {
   newwindow.close();
-  SpecialPowers.setBoolPref("full-screen-api.enabled", gPrevEnabled);
-  SpecialPowers.setBoolPref("full-screen-api.allow-trusted-requests-only", gPrevTrusted);
   SimpleTest.finish();
 }
 
 </script>
 
 <body xmlns="http://www.w3.org/1999/xhtml" style="height: 300px; overflow: auto;"/>
 
 </window>
--- a/dom/tests/mochitest/chrome/test_clipboard_events_chrome.html
+++ b/dom/tests/mochitest/chrome/test_clipboard_events_chrome.html
@@ -7,19 +7,20 @@
         src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"></script>
 
 <script>
 // This test checks that the dom.event.clipboardevents.enabled does not apply to chrome shells.
 
 SimpleTest.waitForExplicitFinish();
 function runTest()
 {
-  SpecialPowers.setBoolPref("dom.event.clipboardevents.enabled", false);
-  window.open("data:text/html,<body onload='window.opener.doChecks(this)'><input id='i' value='Sample Text'></body>",
-              "_blank", "chrome,width=200,height=200");
+  SpecialPowers.pushPrefEnv({"set": [['dom.event.clipboardevents.enabled', false]]}, function() {
+    window.open("data:text/html,<body onload='window.opener.doChecks(this)'><input id='i' value='Sample Text'></body>",
+                "_blank", "chrome,width=200,height=200");
+  });
 }
 
 var event_fired = false;
 
 function doChecks(win)
 {
   var windowFocused = function() {
     var textbox = win.document.getElementById("i");
@@ -44,17 +45,16 @@ function doChecks(win)
     ok(event_fired, "copy event fired when preference is disabled")
 
     event_fired = false;
     textbox.setSelectionRange(1, 4);
     synthesizeKey("v", {accelKey: 1}, win);
     is(textbox.value, "STeText", "paste changed text when preference is disabled");
     ok(event_fired, "paste event fired when preference is disabled")
 
-    SpecialPowers.clearUserPref("dom.event.clipboardevents.enabled");
     win.close();
     SimpleTest.finish();
   }
 
   SimpleTest.waitForFocus(windowFocused, win);
 }
 
 </script>
--- a/dom/tests/mochitest/general/test_clipboard_events.html
+++ b/dom/tests/mochitest/general/test_clipboard_events.html
@@ -674,9 +674,8 @@ function checkCachedDataTransfer(cd, eve
 
   is(getClipboardText(), "Some Clipboard Text", "clipboard not changed using " + testprefix);
 }
 
 </script>
 </pre>
 </body>
 </html>
-
--- a/dom/tests/mochitest/general/test_vibrator.html
+++ b/dom/tests/mochitest/general/test_vibrator.html
@@ -7,28 +7,29 @@
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 
 <!-- Although we can't test that the vibrator works properly, we can test that
      navigator.vibrate throws an exception where appropriate. -->
 
 <script class="testbody" type="text/javascript;version=1.7">
+SimpleTest.waitForExplicitFinish();
 var result;
 function expectFailure(param) {
   result = navigator.vibrate(param);
   is(result, false, 'vibrate(' + param + ') should have failed.');
 }
 
 function expectSuccess(param) {
   result = navigator.vibrate(param);
   is(result, true, 'vibrate(' + param + ') must succeed.');
 }
 
-function tests() {
+function tests(aEnabled) {
   // Some edge cases that the bindings should handle for us.
   expectSuccess(null);
   expectSuccess(undefined);
   // -1 will be converted to the highest unsigned long then clamped.
   expectSuccess(-1);
   expectSuccess('a');
   // -1 will be converted to the highest unsigned long then clamped.
   expectSuccess([100, -1]);
@@ -63,31 +64,25 @@ function tests() {
   expectSuccess([1000, 1000]);
   expectSuccess([1000, 1000.1]);
 
   // The following loop shouldn't cause us to crash.  See bug 701716.
   for (var i = 0; i < 10000; i++) {
     navigator.vibrate([100, 100]);
   }
   ok(true, "Didn't crash after issuing a lot of vibrate() calls.");
+  if(!aEnabled)
+    SimpleTest.finish();
 }
 
-var origVibratorEnabled = SpecialPowers.getBoolPref('dom.vibrator.enabled');
-
 // Test with the vibrator pref enabled.
-try {
-  SpecialPowers.setBoolPref('dom.vibrator.enabled', true);
-  tests();
-
-  // Everything should be the same when the vibrator is disabled -- in
-  // particular, a disabled vibrator shouldn't eat failures we'd otherwise
-  // observe.
-  SpecialPowers.setBoolPref('dom.vibrator.enabled', false);
-  tests();
-}
-finally {
-  SpecialPowers.setBoolPref('dom.vibrator.enabled', origVibratorEnabled);
-}
+SpecialPowers.pushPrefEnv({"set": [['dom.vibrator.enabled', true]]}, function() {
+  tests(true);
+  SpecialPowers.pushPrefEnv({"set": [['dom.vibrator.enabled', false]]}, tests(false));
+});
+// Everything should be the same when the vibrator is disabled -- in
+// particular, a disabled vibrator shouldn't eat failures we'd otherwise
+// observe.
 
 </script>
 </body>
 
 </html>
--- a/dom/tests/mochitest/localstorage/test_appIsolation.html
+++ b/dom/tests/mochitest/localstorage/test_appIsolation.html
@@ -7,28 +7,16 @@
 
 <script type="application/javascript;version=1.7">
 
 SimpleTest.waitForExplicitFinish();
 
 var fileTestOnCurrentOrigin = (location.protocol + "//" + location.host + location.pathname)
                               .replace("test_a", "frameA");
 
-var previousPrefs = {
-  mozBrowserFramesEnabled: undefined,
-};
-
-try {
-  previousPrefs.mozBrowserFramesEnabled = SpecialPowers.getBoolPref('dom.mozBrowserFramesEnabled');
-} catch(e)
-{
-}
-
-SpecialPowers.setBoolPref('dom.mozBrowserFramesEnabled', true);
-
 SpecialPowers.addPermission("browser", true, window.document);
 SpecialPowers.addPermission("embed-apps", true, window.document);
 
 var gData = [
   // APP 1
   {
     app: 'http://example.org/manifest.webapp',
     action: 'read-no',
@@ -105,20 +93,16 @@ function runTest()
 
         i++;
         if (i >= gData.length) {
           localStorage.clear();
 
           SpecialPowers.removePermission("browser", window.document);
           SpecialPowers.removePermission("embed-apps", window.document);
 
-          if (previousPrefs.mozBrowserFramesEnabled !== undefined) {
-            SpecialPowers.setBoolPref('dom.mozBrowserFramesEnabled', previousPrefs.mozBrowserFramesEnabled);
-          }
-
           SimpleTest.finish();
         } else {
           gTestRunner.next();
         }
       });
     }
 
     iframe.src = fileTestOnCurrentOrigin + "?" + data.action;
@@ -126,26 +110,27 @@ function runTest()
     document.body.appendChild(iframe);
 
     yield undefined;
   }
 }
 
 var gTestRunner = runTest();
 
+addLoadEvent(function() {
+  SpecialPowers.pushPrefEnv({"set": [['dom.mozBrowserFramesEnabled', true]]}, startTest);
+});
+
 function startTest()
 {
   is(localStorage.getItem("0"), null, "no data");
   localStorage.setItem("0", "foo");
   is(localStorage.getItem("0"), "foo", "data have been written");
 
   gTestRunner.next();
 }
-
-addLoadEvent(startTest);
-
 </script>
 
 </head>
 
 <body>
 </body>
 </html>
--- a/dom/tv/test/mochitest/test_tv_non_permitted_app.html
+++ b/dom/tv/test/mochitest/test_tv_non_permitted_app.html
@@ -9,24 +9,23 @@
 <p id="display"></p>
 <div id="content" style="display: none"></div>
 <pre id="test">
 <script type="application/javascript" src="./head.js"></script>
 <script type="application/javascript">
 
 var tests = [
   function() {
-    SpecialPowers.pushPrefEnv({"set": [["dom.tv.enabled", true]]}, function() {
+    SpecialPowers.pushPrefEnv({"set": [["dom.tv.enabled", true],["dom.mozBrowserFramesEnabled", true]]}, function() {
       SpecialPowers.pushPermissions(
         [{ "type": "browser", "allow": true, "context": document },
          { "type": "embed-apps", "allow": true, "context": document },
          { "type": "webapps-manage", "allow": true, "context": document }],
         function() {
           SpecialPowers.setAllAppsLaunchable(true);
-          SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
           // No confirmation needed when an app is installed and uninstalled.
           SpecialPowers.autoConfirmAppInstall(() => {
             SpecialPowers.autoConfirmAppUninstall(runTest);
           });
         });
     });
   },
 
--- a/dom/xul/test/test_bug757137.xul
+++ b/dom/xul/test/test_bug757137.xul
@@ -16,48 +16,37 @@ var Ci = Components.interfaces;
 var chromeWindowInterface = Ci.nsIDOMChromeWindow;
 
 SimpleTest.waitForExplicitFinish();
 
 // Force off out-of-process mozbrowser because we need to grab its
 // |window| synchronously from here.  Out-of-process docshell creation
 // for mozbrowser haves entirely differently.
 // XXX why doesn't pushPrefEnv() work here?
-var ipcTabsWereDisabled;
-try {
-  ipcTabsWereDisabled = SpecialPowers.getBoolPref("dom.ipc.tabs.disabled");
-} catch (e) {
-  ipcTabsWereDisabled = undefined;
-}
-SpecialPowers.setBoolPref("dom.ipc.tabs.disabled", true);
-
 var otherWindow = window.open("window_bug757137.xul", "", "chrome");
 ok(chromeWindowInterface !== null, 'nsIDOMChromeWindow interface is defined');
 var otherChromeWindow = null;
 try {
   otherChromeWindow = otherWindow.QueryInterface(chromeWindowInterface);
 } catch(e) {
   ok(false, 'exception when QI to ChromeWindow');
 }
 ok(otherChromeWindow !== null, 'XUL window should QI to ChromeWindow');
 
-otherWindow.onload = function () {
-  var w = otherWindow.document.getElementById('f').contentWindow;
-  ok(w !== null, 'got the |window| for a mozbrowser iframe');
-  var chromeWindow = null;
-  try {
-    var chromeWindow = w.QueryInterface(chromeWindowInterface);
-  } catch(e) { }
-  ok(chromeWindow === null, 'mozbrowser iframe should not get ChromeWindow');
+SpecialPowers.pushPrefEnv({"set":[["dom.ipc.tabs.disabled", true]]}, startTest);
 
-  otherWindow.close();
-  SimpleTest.waitForFocus(function() {
-    if (ipcTabsWereDisabled !== undefined) {
-      SpecialPowers.setBoolPref("dom.ipc.tabs.disabled", ipcTabsWereDisabled);
-    } else {
-      SpecialPowers.clearUserPref("dom.ipc.tabs.disabled");
-    }
-    SimpleTest.finish();
-  });
-};
+function startTest() {
+  otherWindow.onload = function () {
+    var w = otherWindow.document.getElementById('f').contentWindow;
+    ok(w !== null, 'got the |window| for a mozbrowser iframe');
+    var chromeWindow = null;
+    try {
+      var chromeWindow = w.QueryInterface(chromeWindowInterface);
+    } catch(e) { }
+      ok(chromeWindow === null, 'mozbrowser iframe should not get ChromeWindow');
+
+    otherWindow.close();
+    SimpleTest.waitForFocus(SimpleTest.finish);
+ };
+}
 </script>
 
 </window>
--- a/editor/libeditor/tests/test_bug549262.html
+++ b/editor/libeditor/tests/test_bug549262.html
@@ -15,28 +15,29 @@ https://bugzilla.mozilla.org/show_bug.cg
 <div id="content">
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 549262 **/
 
 var smoothScrollPref = "general.smoothScroll";
-SpecialPowers.setBoolPref(smoothScrollPref, false);
 SimpleTest.waitForExplicitFinish();
 var win = window.open("file_bug549262.html", "_blank", 
                       "width=600,height=600,scrollbars=yes");
 
 // grab the timer right at the start
 var cwu = SpecialPowers.getDOMWindowUtils(win);
 function step() {
   cwu.advanceTimeAndRefresh(100);
 }
-
 SimpleTest.waitForFocus(function() {
+  SpecialPowers.pushPrefEnv({"set":[[smoothScrollPref, false]]}, startTest);
+}, win);
+function startTest() {
   // Make sure that pressing Space when a contenteditable element is not focused
   // will scroll the page.
   var ed = win.document.getElementById("editor");
   var sc = win.document.querySelector("a");
   sc.focus();
   is(win.scrollY, 0, "Sanity check");
   synthesizeKey(" ", {}, win);
 
@@ -116,18 +117,16 @@ SimpleTest.waitForFocus(function() {
 
   step();
 
   is(win.scrollY, oldY, "Page is not scrolled down");
   is(win.getSelection().focusNode, ed.firstChild, "Correct element selected");
   is(win.getSelection().focusOffset, ed.textContent.length, "Selection should be moved to the end");
 
   win.close();
-  SpecialPowers.clearUserPref(smoothScrollPref);
   cwu.restoreNormalRefresh();
 
   SimpleTest.finish();
-}, win);
-
+}
 </script>
 </pre>
 </body>
 </html>
--- a/editor/libeditor/tests/test_bug578771.html
+++ b/editor/libeditor/tests/test_bug578771.html
@@ -21,43 +21,43 @@ https://bugzilla.mozilla.org/show_bug.cg
   </div>
 
   <pre id="test">
     <script type="application/javascript">
 
       /** Test for Bug 578771 **/
       SimpleTest.waitForExplicitFinish();
 
-      // Avoid platform selection differences
-      SpecialPowers.setBoolPref("layout.word_select.eat_space_to_next_word", false);
-
       function testElem(elem, elemTag) {
         var ce = document.getElementById("ce");
         ce.focus();
 
         synthesizeMouse(elem, 5, 5, {clickCount: 2 });   
         ok(elem.selectionStart == 0 && elem.selectionEnd == 7,
            " Double-clicking on another " + elemTag + " works correctly");
 
         ce.focus();
         synthesizeMouse(elem, 5, 5, {clickCount: 3 });   
         ok(elem.selectionStart == 0 && elem.selectionEnd == 14,
            "Triple-clicking on another " + elemTag + " works correctly");
       }
-
+      // Avoid platform selection differences
       SimpleTest.waitForFocus(function() {
-        var input = document.getElementById("ip");
-        testElem(input, "input");
+         SpecialPowers.pushPrefEnv({"set":[["layout.word_select.eat_space_to_next_word", false]]}, startTest);
+      });
 
-        var textarea = document.getElementById("ta");
-        testElem(textarea, "textarea");
+      function startTest() {
+         var input = document.getElementById("ip");
+         testElem(input, "input");
 
-        SpecialPowers.clearUserPref("layout.word_select.eat_space_to_next_word");
-        SimpleTest.finish();
-      });
+         var textarea = document.getElementById("ta");
+         testElem(textarea, "textarea");
+
+         SimpleTest.finish();
+      }
    </script>
   </pre>
 
   <input id="ip" type="text" value="Mozilla editor" />
   <textarea id="ta">Mozilla editor</textarea>
   <div id="ce" contenteditable="true">Contenteditable div that could interfere with focus</div>
 </body>
 </html>
--- a/editor/libeditor/tests/test_bug640321.html
+++ b/editor/libeditor/tests/test_bug640321.html
@@ -82,18 +82,16 @@ SimpleTest.waitForFocus(function() {
     // needlessGrowth means that we change the size of a dimension perpendecular to
     // the mouse movement axis in order to preserve the aspect ratio.
     // reversedGrowth means that we change the size of a dimension in the opposite
     // direction to the mouse movement in order to maintain the aspect ratio.
     const ignoredGrowth = preserveRatio ? 0 : 1;
     const needlessGrowth = preserveRatio ? 1 : 0;
     const reversedGrowth = preserveRatio ? -1 : 1;
 
-    SpecialPowers.setBoolPref("editor.resizing.preserve_ratio", preserveRatio);
-
     // top resizer
     testResizer(W/2,   0, -10, -10,   0,  10);
     testResizer(W/2,   0, -10,   0,   0,   0);
     testResizer(W/2,   0, -10,  10,   0, -10);
     testResizer(W/2,   0,   0, -10,   0,  10);
     testResizer(W/2,   0,   0,   0,   0,   0);
     testResizer(W/2,   0,   0,  10,   0, -10);
     testResizer(W/2,   0,  10, -10,   0,  10);
@@ -171,22 +169,22 @@ SimpleTest.waitForFocus(function() {
     testResizer(  0,   0, -10,   0,  10,  10 * needlessGrowth);
     testResizer(  0,   0, -10,  10,  10, -10 * reversedGrowth);
     testResizer(  0,   0,   0, -10,  10 * needlessGrowth,  10);
     testResizer(  0,   0,   0,   0,   0,   0);
     testResizer(  0,   0,   0,  10,   0, -10 * ignoredGrowth);
     testResizer(  0,   0,  10, -10, -10 * reversedGrowth,  10);
     testResizer(  0,   0,  10,   0, -10 * ignoredGrowth,   0);
     testResizer(  0,   0,  10,  10, -10, -10);
-
-    SpecialPowers.clearUserPref("editor.resizing.preserve_ratio");
-  }
-
-  runTests(false);
-  runTests(true);
-
-  SimpleTest.finish();
-});
+ }
+ SpecialPowers.pushPrefEnv({"set": [["editor.resizing.preserve_ratio", false]]}, function() {
+     runTests(false);
+     SpecialPowers.pushPrefEnv({"set": [["editor.resizing.preserve_ratio", true]]}, function() {
+       runTests(true);
+       SimpleTest.finish();
+     });
+   });
+ });
 
 </script>
 </pre>
 </body>
 </html>
--- a/editor/libeditor/tests/test_bug645914.html
+++ b/editor/libeditor/tests/test_bug645914.html
@@ -17,20 +17,21 @@ https://bugzilla.mozilla.org/show_bug.cg
 bar</textarea>
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 645914 **/
 SimpleTest.waitForExplicitFinish();
 SimpleTest.waitForFocus(function() {
+  SpecialPowers.pushPrefEnv({"set":[["layout.word_select.eat_space_to_next_word", true],
+                                    ["browser.triple_click_selects_paragraph", false]]}, startTest);
+});
+function startTest() {
   var textarea = document.querySelector("textarea");
-  SpecialPowers.setBoolPref("layout.word_select.eat_space_to_next_word", true);
-  SpecialPowers.setBoolPref("browser.triple_click_selects_paragraph", false);
-
   textarea.selectionStart = textarea.selectionEnd = 0;
 
   // Simulate a double click on foo
   synthesizeMouse(textarea, 5, 5, {clickCount: 2});
 
   ok(true, "Testing word selection");
   is(textarea.selectionStart, 0, "The start of the selection should be at the beginning of the text");
   is(textarea.selectionEnd, 3, "The end of the selection should not include a newline character");
@@ -49,17 +50,14 @@ SimpleTest.waitForFocus(function() {
 
   // Simulate a quadruple click on Very
   synthesizeMouse(textarea, 5, 5, {clickCount: 4});
 
   ok(true, "Testing paragraph selection");
   is(textarea.selectionStart, 0, "The start of the selection should be at the beginning of the text");
   is(textarea.selectionEnd, textarea.value.length, "The end of the selection should be the end of the paragraph");
 
-  SpecialPowers.clearUserPref("layout.word_select.eat_space_to_next_word");
-  SpecialPowers.clearUserPref("browser.triple_click_selects_paragraph");
   SimpleTest.finish();
-});
-
+}
 </script>
 </pre>
 </body>
 </html>
--- a/editor/libeditor/tests/test_bug674770-1.html
+++ b/editor/libeditor/tests/test_bug674770-1.html
@@ -19,17 +19,19 @@ https://bugzilla.mozilla.org/show_bug.cg
 <a href="file_bug674770-1.html" id="link2">test</a>
 </div>
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 SimpleTest.waitForExplicitFinish();
 SimpleTest.waitForFocus(function() {
-  SpecialPowers.setBoolPref("middlemouse.paste", true);
+  SpecialPowers.pushPrefEnv({"set":[["middlemouse.paste", true]]}, startTest);
+});
+function startTest() {
   localStorage.removeItem("clicked");
   window.linkWasClicked = false;
 
   var link = document.querySelector("#link1");
   addEventListener("storage", function(e) {
     is(e.key, "clicked", "Correct event");
     is(e.newValue, "true", "Correct value");
     window.linkWasClicked = true;
@@ -43,21 +45,20 @@ SimpleTest.waitForFocus(function() {
     link = document.querySelector("#link2");
     localStorage.removeItem("clicked");
     synthesizeMouseAtCenter(link, {button: 1});
 
     hitEventLoop(function() {
       ok(!window.linkWasClicked, "The click operation shouldn't work in the contenteditable area");
 
       localStorage.removeItem("clicked");
-      SpecialPowers.clearUserPref("middlemouse.paste");
       SimpleTest.finish();
     }, 100);
   }, 100);
-});
+}
 
 function hitEventLoop(func, times) {
   if (times > 0) {
     setTimeout(hitEventLoop, 0, func, times - 1);
   } else {
     setTimeout(func, 0);
   }
 }
--- a/editor/libeditor/tests/test_bug674770-2.html
+++ b/editor/libeditor/tests/test_bug674770-2.html
@@ -42,52 +42,49 @@ function clickEventHnalder(aEvent)
   if (gDoPreventDefault2 == aEvent.target) {
     aEvent.preventDefault();
   }
 }
 
 // NOTE: tests need to check the result *after* the content is actually
 //       modified.  Sometimes, the modification is delayed. Therefore, there
 //       are a lot of functions and SimpleTest.executeSoon()s.
-
 SimpleTest.waitForFocus(function() {
-  SpecialPowers.setBoolPref("middlemouse.contentLoadURL", false);
-  SpecialPowers.setBoolPref("middlemouse.paste", true);
-
+  SpecialPowers.pushPrefEnv({"set":[["middlemouse.contentLoadURL", false],
+                                    ["middlemouse.paste", true]]}, startTest);
+});
+function startTest() {
   frameWindow = iframe.contentWindow;
   frameDocument = iframe.contentDocument;
 
   frameDocument.getElementById("input").addEventListener("click", clickEventHnalder, false);
   frameDocument.getElementById("editor1").addEventListener("click", clickEventHnalder, false);
   frameDocument.getElementById("editor2").addEventListener("click", clickEventHnalder, false);
 
   var text = frameDocument.getElementById("text");
 
   text.focus();
-
-  SimpleTest.executeSoon(function() {
-    if (navigator.platform.indexOf("Linux") == 0) {
-      synthesizeKey("a", { altKey: true }, frameWindow);
-    } else {
-      synthesizeKey("a", { accelKey: true }, frameWindow);
-    }
-    // Windows and Mac don't have primary selection, we should copy the text to
-    // the global clipboard.
-    if (!SpecialPowers.supportsSelectionClipboard()) {
-      SimpleTest.waitForClipboard("pasted",
-        function() { synthesizeKey("c", { accelKey: true }, frameWindow); },
-        function() { SimpleTest.executeSoon(runInputTests1) },
-        cleanup);
-    } else {
-      // Otherwise, don't call waitForClipboard since it breaks primary
-      // selection.
-      runInputTests1();
-    }
-  });
-});
+  if (navigator.platform.indexOf("Linux") == 0) {
+    synthesizeKey("a", { altKey: true }, frameWindow);
+  } else {
+    synthesizeKey("a", { accelKey: true }, frameWindow);
+  }
+  // Windows and Mac don't have primary selection, we should copy the text to
+  // the global clipboard.
+  if (!SpecialPowers.supportsSelectionClipboard()) {
+    SimpleTest.waitForClipboard("pasted",
+      function() { synthesizeKey("c", { accelKey: true }, frameWindow); },
+      function() { SimpleTest.executeSoon(runInputTests1) },
+      cleanup);
+  } else {
+    // Otherwise, don't call waitForClipboard since it breaks primary
+    // selection.
+    runInputTests1();
+  }
+}
 
 function runInputTests1()
 {
   var input = frameDocument.getElementById("input");
 
   // first, copy text.
 
   // when middle clicked in focused input element, text should be pasted.
@@ -384,18 +381,15 @@ function runBodyEditableDocumentTests2()
        "pasted when middle clicked in non-editable element");
 
     SimpleTest.executeSoon(cleanup);
   });
 }
 
 function cleanup()
 {
-  SpecialPowers.clearUserPref("middlemouse.contentLoadURL");
-  SpecialPowers.clearUserPref("middlemouse.paste");
-
   SimpleTest.finish();
 }
 
 </script>
 </pre>
 </body>
 </html>
--- a/editor/libeditor/tests/test_bug795785.html
+++ b/editor/libeditor/tests/test_bug795785.html
@@ -24,20 +24,19 @@ https://bugzilla.mozilla.org/show_bug.cg
 <script class="testbody" type="application/javascript">
 
 
 SimpleTest.waitForExplicitFinish();
 SimpleTest.requestFlakyTimeout("This test uses setTimeouts in order to fix an intermittent failure.");
 
 // Turn off spatial navigation because it hijacks arrow key events and VK_RETURN
 // events.
-SpecialPowers.setBoolPref("snav.enabled", false);
-
-SimpleTest.waitForFocus(runTests);
-
+SimpleTest.waitForFocus(function() {
+  SpecialPowers.pushPrefEnv({"set":[["snav.enabled", false]]}, runTests);
+});
 var textarea = document.getElementById("textarea");
 var div = document.getElementById("div");
 
 function hitEventLoop(aFunc, aTimes)
 {
   if (--aTimes) {
     setTimeout(hitEventLoop, 0, aFunc, aTimes);
   } else {
--- a/extensions/cookie/test/test_permissionmanager_app_isolation.html
+++ b/extensions/cookie/test/test_permissionmanager_app_isolation.html
@@ -17,36 +17,24 @@ https://bugzilla.mozilla.org/show_bug.cg
 </div>
 <pre id="test">
 <script type="application/javascript;version=1.7">
 
 /** Test for Bug 758258 **/
 
 var Ci = Components.interfaces;
 var Cc = Components.classes;
-
+var gTestRunner;
 SimpleTest.waitForExplicitFinish();
 
 var permManager = Cc["@mozilla.org/permissionmanager;1"]
                     .getService(Ci.nsIPermissionManager);
 
 const gPermName = 'foobar';
 
-var previousPrefs = {
-  mozBrowserFramesEnabled: undefined,
-};
-
-try {
-  previousPrefs.mozBrowserFramesEnabled = SpecialPowers.getBoolPref('dom.mozBrowserFramesEnabled');
-} catch(e)
-{
-}
-
-SpecialPowers.setBoolPref('dom.mozBrowserFramesEnabled', true);
-
 // We use http://test/ as url so all apps use the same url and app isolation is
 // more obvious.
 var gData = [
   // APP 1
   {
     app: 'http://example.org/manifest.webapp',
     action: 'read-no',
     src: 'http://test/',
@@ -135,34 +123,32 @@ function runTest() {
             ok(false, "shouldn't be there");
         }
 
         // Calling removeChild() produces an error that creates failures.
         //document.getElementById('content').removeChild(iframe);
 
         i++;
         if (i >= gData.length) {
-          if (previousPrefs.mozBrowserFramesEnabled !== undefined) {
-            SpecialPowers.setBoolPref('dom.mozBrowserFramesEnabled', previousPrefs.mozBrowserFramesEnabled);
-          }
-
-          SimpleTest.finish();
+           SimpleTest.finish();
         } else {
           gTestRunner.next();
         }
       });
     }
 
     iframe.src = data.src;
 
     document.getElementById('content').appendChild(iframe);
 
     yield;
   }
 }
 
-var gTestRunner = runTest();
-gTestRunner.next();
-
+SpecialPowers.pushPrefEnv({"set":[["dom.mozBrowserFramesEnabled", true]]},
+  function() {
+    gTestRunner = runTest();
+    gTestRunner.next();
+});
 </script>
 </pre>
 </body>
 </html>
--- a/image/test/crashtests/ownerdiscard.html
+++ b/image/test/crashtests/ownerdiscard.html
@@ -25,28 +25,26 @@
       cleanupAndFinish();
     }
     observer = SpecialPowers.wrapCallbackObject(observer);
     var gObserver = Cc["@mozilla.org/image/tools;1"].getService(Ci.imgITools)
                                                     .createScriptedObserver(observer);
     var imgLoadingContent =
       SpecialPowers.wrap(img).QueryInterface(Ci.nsIImageLoadingContent);
     imgLoadingContent.addObserver(gObserver);
-
-    SpecialPowers.setBoolPref('min_discard_timeout_ms', 1);
-
     function initCF() {
       setTimeout(function() { document.adoptNode(tCF0); }, 0);
     }
     document.addEventListener("DOMContentLoaded", initCF, false);
 
     function cleanupAndFinish() {
-      SpecialPowers.clearUserPref('min_discard_timeout_ms');
       imgLoadingContent.removeObserver(gObserver);
       setTimeout("document.documentElement.className = '';", 0);
     }
     function loadhandler() {
       setTimeout("cleanupAndFinish();", 30000);
     }
-    window.addEventListener("load", loadhandler, false);
+    window.addEventListener("load", function() {
+      SpecialPowers.pushPrefEnv({"set":[["min_discard_timeout_ms", 1]]}, loadhandler)}, false);
+    });
   </script>
 </body>
 </html>
--- a/testing/mochitest/tests/Harness_sanity/test_SpecialPowersExtension.html
+++ b/testing/mochitest/tests/Harness_sanity/test_SpecialPowersExtension.html
@@ -185,9 +185,8 @@ function starttest(){
   // test_SpecialPowersExtension2.html.
   SpecialPowers.pushPrefEnv({set: [['testing.some_arbitrary_pref', true]]},
                             function() { SimpleTest.finish(); });
 }
 </script>
 </pre>
 </body>
 </html>
-
--- a/toolkit/components/passwordmgr/test/test_basic_form_2.html
+++ b/toolkit/components/passwordmgr/test/test_basic_form_2.html
@@ -9,18 +9,16 @@
 <body>
 Login Manager test: simple form fill with autofillForms disabled
 <script>
 commonInit();
 SimpleTest.waitForExplicitFinish();
 
 var pwmgr = SpecialPowers.Cc["@mozilla.org/login-manager;1"]
                          .getService(SpecialPowers.Ci.nsILoginManager);
-// Assume that the pref starts out true, so set to false
-SpecialPowers.setBoolPref("signon.autofillForms", false);
 </script>
 
 <p id="display"></p>
 
 <div id="content" style="display: block">
 
   <form id="form1" action="formtest.js">
     <p>This is form 1.</p>
@@ -47,20 +45,20 @@ function startTest(){
   pwmgr.fillForm(document.getElementById("form1"))
        .then(function(result) {
          is(result, true, "Checking return value of fillForm");
 
          // Check that the form was filled
          is($_(1, "uname").value, "testuser", "Checking for filled username");
          is($_(1, "pword").value, "testpass", "Checking for filled password");
 
-         // Reset pref (since we assumed it was true to start)
-         SpecialPowers.setBoolPref("signon.autofillForms", true);
-
          SimpleTest.finish();
        });
 }
-window.addEventListener("runTests", startTest);
-
+// Assume that the pref starts out true, so set to false
+SpecialPowers.pushPrefEnv({"set":[["signon.autofillForms", false]]}, setup);
+function setup() {
+ window.addEventListener("runTests", startTest);
+}
 </script>
 </pre>
 </body>
 </html>
--- a/toolkit/components/passwordmgr/test/test_basic_form_observer_autofillForms.html
+++ b/toolkit/components/passwordmgr/test/test_basic_form_observer_autofillForms.html
@@ -9,21 +9,20 @@
 <body>
 Login Manager test: simple form with autofillForms disabled and notifying observers
 <script>
 commonInit(true);
 SimpleTest.waitForExplicitFinish();
 
 const Cc = SpecialPowers.Cc;
 const Ci = SpecialPowers.Ci;
-
+var TestObserver;
 // Assume that the pref starts out true, so set to false
-SpecialPowers.setBoolPref("signon.autofillForms", false);
-
-var TestObserver = {
+SpecialPowers.pushPrefEnv({"set":[["signon.autofillForms", false]]}, function() {
+  TestObserver = {
   receivedNotificationFoundForm : false,
   receivedNotificationFoundLogins : false,
   dataFoundForm : "",
   dataFoundLogins : null,
   observe : function (subject, topic, data) {
     var pwmgr = Cc["@mozilla.org/login-manager;1"].
                 getService(Ci.nsILoginManager);
     if (topic == "passwordmgr-found-form") {
@@ -45,16 +44,17 @@ var TestObserver = {
       this.dataFoundLogins = subject.QueryInterface(Ci.nsIPropertyBag2);
     }
   }
 };
 
 // Add the observer
 SpecialPowers.addObserver(TestObserver, "passwordmgr-found-form", false);
 SpecialPowers.addObserver(TestObserver, "passwordmgr-found-logins", false);
+});
 </script>
 
 <p id="display"></p>
 
 <div id="content" style="display: block">
 
   <form id="form1" action="formtest.js">
     <p>This is form 1.</p>
@@ -85,20 +85,16 @@ function startTest() {
   is(TestObserver.dataFoundLogins.get("didntFillReason"), "noAutofillForms", "Checking didntFillReason is noAutofillForms");
   is(SpecialPowers.unwrap(TestObserver.dataFoundLogins.get("usernameField")), $_(1, "uname"), "Checking username field is correct");
   is(SpecialPowers.unwrap(TestObserver.dataFoundLogins.get("passwordField")), $_(1, "pword"), "Checking password field is correct");
   is(TestObserver.dataFoundLogins.get("foundLogins").constructor.name, "Array", "Checking foundLogins is array");
   is(TestObserver.dataFoundLogins.get("foundLogins").length, 1, "Checking foundLogins contains one login");
   ok(TestObserver.dataFoundLogins.get("selectedLogin").QueryInterface(Ci.nsILoginInfo), "Checking selectedLogin is nsILoginInfo");
   ok(TestObserver.dataFoundLogins.get("selectedLogin").equals(TestObserver.dataFoundLogins.get("foundLogins")[0]),
      "Checking selectedLogin is found login");
-
-  // Reset pref (since we assumed it was true to start)
-  SpecialPowers.setBoolPref("signon.autofillForms", true);
-
   // Remove the observer
   SpecialPowers.removeObserver(TestObserver, "passwordmgr-found-form");
   SpecialPowers.removeObserver(TestObserver, "passwordmgr-found-logins");
 
   SimpleTest.finish();
 }
 
 
--- a/toolkit/components/url-classifier/tests/mochitest/test_allowlisted_annotations.html
+++ b/toolkit/components/url-classifier/tests/mochitest/test_allowlisted_annotations.html
@@ -16,18 +16,16 @@
 
 var Cc = SpecialPowers.Cc;
 var Ci = SpecialPowers.Ci;
 
 // Add https://allowlisted.example.com to the permissions manager
 SpecialPowers.addPermission("trackingprotection",
                             Ci.nsIPermissionManager.ALLOW_ACTION,
                             { url: "https://allowlisted.example.com" });
-// Enable synthetic allowlist URL in nsChannelClassifier
-SpecialPowers.setBoolPref("channelclassifier.allowlist_example", true);
 
 // Add some URLs to the tracking database
 var testData = "tracking.example.com/";
 var testUpdate =
   "n:1000\ni:test-track-simple\nad:1\n" +
   "a:524:32:" + testData.length + "\n" +
   testData;
 
@@ -35,18 +33,16 @@ var dbService = Cc["@mozilla.org/url-cla
                 .getService(Ci.nsIUrlClassifierDBService);
 
 function clearPermissions() {
   SpecialPowers.removePermission("trackingprotection",
                                  { url: "https://allowlisted.example.com" });
   ok(!SpecialPowers.testPermission("trackingprotection",
                                    Ci.nsIPermissionManager.ALLOW_ACTION,
                                    { url: "https://allowlisted.example.com" }));
-  SpecialPowers.clearUserPref("privacy.trackingprotection.enabled");
-  SpecialPowers.clearUserPref("channelclassifier.allowlist_example");
 }
 
 function doUpdate(update) {
   var listener = {
     QueryInterface: function(iid)
     {
       if (iid.equals(Ci.nsISupports) ||
           iid.equals(Ci.nsIUrlClassifierUpdateObserver))
@@ -57,30 +53,31 @@ function doUpdate(update) {
     updateUrlRequested: function(url) { },
     streamFinished: function(status) { },
     updateError: function(errorCode) {
       ok(false, "Couldn't update classifier.");
       // Abort test.
       SimpleTest.finish();
     },
     updateSuccess: function(requestedTimeout) {
-      SpecialPowers.setBoolPref("privacy.trackingprotection.enabled", true);
       document.getElementById("testFrame").src = "allowlistAnnotatedFrame.html";
     }
   };
 
   dbService.beginUpdate(listener, "test-track-simple", "");
   dbService.beginStream("", "");
   dbService.updateStream(update);
   dbService.finishStream();
   dbService.finishUpdate();
 }
 
 SpecialPowers.pushPrefEnv(
-  {"set" : [["urlclassifier.trackingTable", "test-track-simple"]]},
+  {"set" : [["urlclassifier.trackingTable", "test-track-simple"],
+            ["privacy.trackingprotection.enabled", true],
+            ["channelclassifier.allowlist_example", true]]},
   function() { doUpdate(testUpdate); });
 
 // Expected finish() call is in "allowlistedAnnotatedFrame.html".
 SimpleTest.waitForExplicitFinish();
 
 </script>
 
 </pre>
--- a/toolkit/content/tests/chrome/test_preferences_beforeaccept.xul
+++ b/toolkit/content/tests/chrome/test_preferences_beforeaccept.xul
@@ -8,28 +8,21 @@
   <script type="application/javascript"
           src="chrome://mochikit/content/MochiKit/packed.js"/>
   <script type="application/javascript"
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
 
   <script type="application/javascript">
   <![CDATA[
     SimpleTest.waitForExplicitFinish();
+    SpecialPowers.pushPrefEnv({"set":[["browser.preferences.instantApply", false]]}, function() {
 
     // No instant-apply for this test
-    SpecialPowers.setBoolPref("browser.preferences.instantApply", false);
-
     var prefWindow = openDialog("window_preferences_beforeaccept.xul", "", "", windowOnload);
 
-    SimpleTest.registerCleanupFunction(() => {
-      SpecialPowers.clearUserPref("browser.preferences.instantApply");
-      SpecialPowers.clearUserPref("tests.beforeaccept.dialogShown");
-      SpecialPowers.clearUserPref("tests.beforeaccept.called");
-    });
-
     function windowOnload() {
       var dialogShown = prefWindow.document.getElementById("tests.beforeaccept.dialogShown");
       var called = prefWindow.document.getElementById("tests.beforeaccept.called");
       is(dialogShown.value, true, "dialog opened, shown pref set");
       is(dialogShown.valueFromPreferences, null, "shown pref not committed");
       is(called.value, null, "beforeaccept not yet called");
       is(called.valueFromPreferences, null, "beforeaccept not yet called, pref not committed");
 
@@ -44,16 +37,17 @@
       // try again, this one should succeed
       prefWindow.document.documentElement.acceptDialog();
       is(prefWindow.closed, true, "window now closed");
       is(dialogShown.valueFromPreferences, true, "shown pref committed");
       is(called.valueFromPreferences, true, "called pref committed");
 
       SimpleTest.finish();
     }
+});
   ]]>
   </script>
 
   <body xmlns="http://www.w3.org/1999/xhtml">
     <p id="display"></p>
     <div id="content" style="display: none"></div>
     <pre id="test"></pre>
   </body>
--- a/widget/tests/test_assign_event_data.html
+++ b/widget/tests/test_assign_event_data.html
@@ -629,48 +629,32 @@ function runNextTest()
     });
     return;
   }
   doTest(kTests[gIndex]);
 }
 
 function init()
 {
-  SpecialPowers.setBoolPref("middlemouse.contentLoadURL", false);
-  SpecialPowers.setBoolPref("middlemouse.paste", false);
-  SpecialPowers.setBoolPref("general.autoScroll", false);
-  SpecialPowers.setIntPref("mousewheel.default.action", 0);
-  SpecialPowers.setIntPref("mousewheel.default.action.override_x", -1);
-  SpecialPowers.setIntPref("mousewheel.with_shift.action", 0);
-  SpecialPowers.setIntPref("mousewheel.with_shift.action.override_x", -1);
-  SpecialPowers.setIntPref("mousewheel.with_control.action", 0);
-  SpecialPowers.setIntPref("mousewheel.with_control.action.override_x", -1);
-  SpecialPowers.setIntPref("mousewheel.with_alt.action", 0);
-  SpecialPowers.setIntPref("mousewheel.with_alt.action.override_x", -1);
-  SpecialPowers.setIntPref("mousewheel.with_meta.action", 0);
-  SpecialPowers.setIntPref("mousewheel.with_meta.action.override_x", -1);
-
-  runNextTest();
+  SpecialPowers.pushPrefEnv({"set":[["middlemouse.contentLoadURL", false],
+  			            ["middlemouse.paste", false],
+                                    ["general.autoScroll", false],
+                                    ["mousewheel.default.action", 0],
+                                    ["mousewheel.default.action.override_x", -1],
+                                    ["mousewheel.with_shift.action", 0],
+                                    ["mousewheel.with_shift.action.override_x", -1],
+                                    ["mousewheel.with_control.action", 0],
+                                    ["mousewheel.with_control.action.override_x", -1],
+                                    ["mousewheel.with_alt.action", 0],
+                                    ["mousewheel.with_alt.action.override_x", -1],
+                                    ["mousewheel.with_meta.action", 0],
+                                    ["mousewheel.with_meta.action.override_x", -1]]}, runNextTest);
 }
 
 function finish()
 {
-  SpecialPowers.clearUserPref("middlemouse.contentLoadURL");
-  SpecialPowers.clearUserPref("middlemouse.paste");
-  SpecialPowers.clearUserPref("general.autoScroll");
-  SpecialPowers.clearUserPref("mousewheel.default.action");
-  SpecialPowers.clearUserPref("mousewheel.default.action.override_x");
-  SpecialPowers.clearUserPref("mousewheel.with_shift.action");
-  SpecialPowers.clearUserPref("mousewheel.with_shift.action.override_x");
-  SpecialPowers.clearUserPref("mousewheel.with_control.action");
-  SpecialPowers.clearUserPref("mousewheel.with_control.action.override_x");
-  SpecialPowers.clearUserPref("mousewheel.with_alt.action");
-  SpecialPowers.clearUserPref("mousewheel.with_alt.action.override_x");
-  SpecialPowers.clearUserPref("mousewheel.with_meta.action");
-  SpecialPowers.clearUserPref("mousewheel.with_meta.action.override_x");
-
   SimpleTest.finish();
 }
 
 SimpleTest.waitForFocus(init);
 
 </script>
 </body>
--- a/widget/tests/test_imestate.html
+++ b/widget/tests/test_imestate.html
@@ -1423,18 +1423,17 @@ function runEditorReframeTests(aCallback
   }, 20);
 }
 
 function runTests()
 {
   if (!kIMEEnabledSupported && !kIMEOpenSupported)
     return;
 
-  SpecialPowers.setBoolPref("test.IME", true);
-
+  SpecialPowers.pushPrefEnv({"set":[["test.IME", true]]}, function() {
   // test for normal contents.
   runBasicTest(false, false, "Testing of normal contents");
 
   // test for plugin contents
   runPluginTest();
 
   var container = document.getElementById("display");
   // test for contentEditable="true"
@@ -1474,20 +1473,20 @@ function runTests()
   // XXX temporary disable against failure
   //runTestPasswordFieldOnDialog();
 
   // Asynchronous tests
   runEditorReframeTests(function () {
     // This will call onFinish(), so, this test must be the last.
     runEditableSubframeTests();
   });
+ });
 }
 
 function onFinish()
 {
-  SpecialPowers.clearUserPref("test.IME");
   SimpleTest.finish();
 }
 
 </script>
 </body>
 
 </html>