Bug 668154 - Use the same mock file picker for all mochitests and xpcshell tests; r=jmaher
authorGeoff Lankow <geoff@darktrojan.net>
Sat, 22 Oct 2011 12:39:30 +1300
changeset 81207 53ba7abbf1daf97cf43da3bf41c757a2b157c6f2
parent 81206 b316ac07d768b9bb89a1eb5a7dd648b2cf68b80d
child 81208 06292dba305205f823d4043be55f35988806fc1d
child 81254 be8056caccb4db8b1ff89dba474847d2a65b9184
push id90
push userffxbld
push dateSun, 29 Jan 2012 07:46:52 +0000
treeherdermozilla-release@acddb6b6a01c [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersjmaher
bugs668154
milestone10.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 668154 - Use the same mock file picker for all mochitests and xpcshell tests; r=jmaher
browser/base/content/test/browser_save_video.js
content/html/content/test/test_bug500885.html
content/html/content/test/test_bug592802.html
layout/forms/test/bug536567_subframe.html
layout/forms/test/test_bug36619.html
layout/forms/test/test_bug377624.html
layout/forms/test/test_bug536567.html
testing/mochitest/MockFilePicker.jsm
testing/mochitest/jar.mn
testing/mochitest/tests/SimpleTest/specialpowersAPI.js
toolkit/content/tests/browser/browser_save_resend_postdata.js
toolkit/content/tests/browser/common/Makefile.in
toolkit/content/tests/browser/common/mockFilePicker.js
toolkit/mozapps/downloads/tests/Makefile.in
toolkit/mozapps/downloads/tests/unit/test_privatebrowsing_downloadLastDir.js
toolkit/mozapps/extensions/test/browser/browser_bug567127.js
toolkit/mozapps/extensions/test/browser/browser_inlinesettings.js
--- a/browser/base/content/test/browser_save_video.js
+++ b/browser/base/content/test/browser_save_video.js
@@ -1,17 +1,21 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
+var MockFilePicker = SpecialPowers.MockFilePicker;
+MockFilePicker.reset();
+
 /**
  * TestCase for bug 564387
  * <https://bugzilla.mozilla.org/show_bug.cgi?id=564387>
  */
 function test() {
   waitForExplicitFinish();
+  var fileName;
 
   gBrowser.loadURI("http://mochi.test:8888/browser/browser/base/content/test/bug564387.html");
 
   registerCleanupFunction(function () {
     gBrowser.addTab();
     gBrowser.removeCurrentTab();
   });
 
@@ -30,60 +34,57 @@ function test() {
     });
   });
 
   function contextMenuOpened(event) {
     event.currentTarget.removeEventListener("popupshown", contextMenuOpened);
 
     // Create the folder the video will be saved into.
     var destDir = createTemporarySaveDirectory();
+    var destFile = destDir.clone();
 
-    mockFilePickerSettings.destDir = destDir;
-    mockFilePickerSettings.filterIndex = 1; // kSaveAsType_URL
-    mockFilePickerRegisterer.register();
+    MockFilePicker.displayDirectory = destDir;
+    MockFilePicker.showCallback = function(fp) {
+      fileName = fp.defaultString;
+      destFile.append (fileName);
+      MockFilePicker.returnFiles = [destFile];
+      MockFilePicker.filterIndex = 1; // kSaveAsType_URL
+    };
 
     mockTransferCallback = onTransferComplete;
     mockTransferRegisterer.register();
 
     registerCleanupFunction(function () {
       mockTransferRegisterer.unregister();
-      mockFilePickerRegisterer.unregister();
+      MockFilePicker.reset();
       destDir.remove(true);
     });
 
     // Select "Save Video As" option from context menu
     var saveVideoCommand = document.getElementById("context-savevideo");
     saveVideoCommand.doCommand();
 
     event.target.hidePopup();
   }
 
   function onTransferComplete(downloadSuccess) {
     ok(downloadSuccess, "Video file should have been downloaded successfully");
 
-    // Read the name of the saved file.
-    var fileName = mockFilePickerResults.selectedFile.leafName;
-
     is(fileName, "Bug564387-expectedName.ogv",
        "Video file name is correctly retrieved from Content-Disposition http header");
 
     finish();
   }
 }
 
 Cc["@mozilla.org/moz/jssubscript-loader;1"]
   .getService(Ci.mozIJSSubScriptLoader)
   .loadSubScript("chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockTransfer.js",
                  this);
 
-Cc["@mozilla.org/moz/jssubscript-loader;1"]
-  .getService(Ci.mozIJSSubScriptLoader)
-  .loadSubScript("chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockFilePicker.js",
-                 this);
-
 function createTemporarySaveDirectory() {
   var saveDir = Cc["@mozilla.org/file/directory_service;1"]
                   .getService(Ci.nsIProperties)
                   .get("TmpD", Ci.nsIFile);
   saveDir.append("testsavedir");
   if (!saveDir.exists())
     saveDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0755);
   return saveDir;
--- a/content/html/content/test/test_bug500885.html
+++ b/content/html/content/test/test_bug500885.html
@@ -2,99 +2,59 @@
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=500885
 -->
 <head>
   <title>Test for Bug 500885</title>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
-  <script type="text/javascript" src="/tests/SimpleTest/mockObjects.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=500885">Mozilla Bug 500885</a>
 <div>
   <input id="file" type="file" />
 </div>
 <script type="text/javascript">
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-var Cu = Components.utils;
-var Ci = Components.interfaces;
-var Cr = Components.results;
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-function MockFilePicker() { };
-MockFilePicker.prototype = {
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIFilePicker]),
-  init: function(aParent, aTitle, aMode) { },
-  appendFilters: function(aFilterMask) { },
-  appendFilter: function(aTitle, aFilter) { },
-  defaultString: "",
-  defaultExtension: "",
-  filterIndex: 0,
-  displayDirectory: null,
-  file: null,
-  get fileURL() {
-    throw Cr.NS_ERROR_NOT_IMPLEMENTED;
-  },
-  get files() {
-    throw Cr.NS_ERROR_NOT_IMPLEMENTED;
-  },
-  show: function MFP_show() {
-    return Ci.nsIFilePicker.returnOK;
-  }
-};
-
-var mockFilePickerRegisterer = 
-  new MockObjectRegisterer("@mozilla.org/filepicker;1",MockFilePicker);
+var MockFilePicker = SpecialPowers.MockFilePicker;
+MockFilePicker.reset();
+MockFilePicker.returnValue = MockFilePicker.returnOK;
 
 function test() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  var wu = window.QueryInterface(Ci.nsIInterfaceRequestor)
-                  .getInterface(Ci.nsIDOMWindowUtils);
-                  
+  // SpecialPowers.DOMWindowUtils doesn't appear to fire mouseEvents correctly
+  var wu = SpecialPowers.getDOMWindowUtils(window);
 
-  mockFilePickerRegisterer.register();
   try {
     var domActivateEvents;
     var fileInput = document.getElementById("file");
     var rect = fileInput.getBoundingClientRect();
 
     fileInput.addEventListener ("DOMActivate", function (e) {
-      ok("detail" in e, "DOMActivate should have .detail!");
-      is(e.detail, 1, "detail should be 1!");
+      ok("detail" in e, "DOMActivate should have .detail");
+      is(e.detail, 1, ".detail should be 1");
       domActivateEvents++;
     }, false);
 
     domActivateEvents = 0;
     wu.sendMouseEvent("mousedown", rect.left + 5, rect.top + 5, 0, 1, 0);
     wu.sendMouseEvent("mouseup", rect.left + 5, rect.top + 5, 0, 1, 0);
-    is(domActivateEvents, 1, "click on text field should only fire 1 DOMActivate event");
+    is(domActivateEvents, 1, "click on text field should fire 1 DOMActivate event");
 
     domActivateEvents = 0;
     wu.sendMouseEvent("mousedown", rect.right - 5, rect.top + 5, 0, 1, 0);
     wu.sendMouseEvent("mouseup", rect.right - 5, rect.top + 5, 0, 1, 0);
-    is(domActivateEvents, 1, "click on button should only fire 1 DOMActivate event");
+    is(domActivateEvents, 1, "click on button should fire 1 DOMActivate event");
 
   } finally {
-    SimpleTest.executeSoon(unregister);
-    
+    SimpleTest.executeSoon(SimpleTest.finish);
   }
 }
 
-function unregister()
-{
-  mockFilePickerRegisterer.unregister();
-  SimpleTest.finish();
-}
-
-window.onload = function() {
-  SimpleTest.waitForExplicitFinish();
-  setTimeout(test, 0);
-};
+SimpleTest.waitForExplicitFinish();
+SimpleTest.waitForFocus(test);
 
 </script>
 </body>
 
 </html>
--- a/content/html/content/test/test_bug592802.html
+++ b/content/html/content/test/test_bug592802.html
@@ -2,17 +2,16 @@
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=592802
 -->
 <head>
   <title>Test for Bug 592802</title>
   <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <script type="application/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
-  <script type="application/javascript" src="/tests/SimpleTest/mockObjects.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=592802">Mozilla Bug 592802</a>
 <p id="display"></p>
 <div id="content">
   <input id='a' type='file'>
   <input id='a2' type='file'>
@@ -21,173 +20,53 @@ https://bugzilla.mozilla.org/show_bug.cg
 <button id='b2' onclick="document.getElementById('a2').click();">Show Filepicker</button>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 592802 **/
 
 SimpleTest.waitForExplicitFinish();
 
-netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-
-var Cu = Components.utils;
-var Ci = Components.interfaces;
-var Cr = Components.results;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-function simpleEnumerator(items)
-{
-  this._items = items;
-  this._nextIndex = 0;
-}
-
-simpleEnumerator.prototype = {
-  QueryInterface: function(aIID)
-  {
-    if (Ci.nsISimpleEnumerator.equals(aIID) ||
-        Ci.nsISupports.equals(aIID)) {
-      return this;
-    }
-
-    throw Cr.NS_ERROR_NO_INTERFACE;
-  },
-
-  hasMoreElements: function()
-  {
-    return this._nextIndex < this._items.length;
-  },
-
-  getNext: function()
-  {
-    if (!this.hasMoreElements()) {
-      throw Cr.NS_ERROR_FAILURE;
-    }
-
-    return this._items[this._nextIndex++];
-  }
-};
-
-function MockFilePicker()
-{
-}
-
-MockFilePicker.prototype = {
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIFilePicker]),
-
-  // Constants
-  returnOK: 0, // the user hits OK (select a file)
-  returnCancel: 1, // the user cancel the file selection
-  returnReplace: 2, // the user replace the selection
-
-  // Properties
-  defaultExtension: "",
-  defaultString: "",
-  get displayDirectory() { return null; },
-  set displayDirectory(val) { },
-  get fileURL() { return null; },
-  filterIndex: 0,
-
-  get file() {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-    var fileName = "592808_file";
-    var fileData = "file content";
-
-    var dirSvc = Components.classes["@mozilla.org/file/directory_service;1"]
-                           .getService(Components.interfaces.nsIProperties);
-    var testFile = dirSvc.get("ProfD", Components.interfaces.nsIFile);
-    testFile.append(fileName);
-    var outStream = Components.
-                    classes["@mozilla.org/network/file-output-stream;1"].
-                    createInstance(Components.interfaces.nsIFileOutputStream);
-    outStream.init(testFile, 0x02 | 0x08 | 0x20, // write, create, truncate
-                   0666, 0);
-    outStream.write(fileData, fileData.length);
-    outStream.close();
-
-    return testFile;
-  },
-
-  get files() {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-    var fileName = "592808_file";
-    var fileData = "file content";
-
-    var dirSvc = Components.classes["@mozilla.org/file/directory_service;1"]
-                           .getService(Components.interfaces.nsIProperties);
-    var testFile = dirSvc.get("ProfD", Components.interfaces.nsIFile);
-    testFile.append(fileName);
-    var outStream = Components.
-                    classes["@mozilla.org/network/file-output-stream;1"].
-                    createInstance(Components.interfaces.nsIFileOutputStream);
-    outStream.init(testFile, 0x02 | 0x08 | 0x20, // write, create, truncate
-                   0666, 0);
-    outStream.write(fileData, fileData.length);
-    outStream.close();
-
-    return new simpleEnumerator([testFile]);
-  },
-
-  appendFilter: function(val) {},
-
-  appendFilters: function(val) {},
-
-  init: function() {},
-
-  show: function()
-  {
-    if (firstFilePickerShow) {
-      firstFilePickerShow = false;
-      return this.returnCancel;
-    } else {
-      return this.returnOK;
-    }
-  }
-};
-
-var mockFilePickerRegisterer =
-  new MockObjectRegisterer("@mozilla.org/filepicker;1",MockFilePicker);
-
-mockFilePickerRegisterer.register();
+var MockFilePicker = SpecialPowers.MockFilePicker;
+MockFilePicker.reset();
 
 var testData = [
 /* visibility | display | multiple */
   [ "",       "",     false ],
   [ "hidden", "",     false ],
   [ "",       "none", false ],
   [ "",       "",     true ],
   [ "hidden", "",     true ],
   [ "",       "none", true ],
 ];
 
 var testCounter = 0;
 var testNb = testData.length;
 
-var firstFilePickerShow = true;
-
 function finished()
 {
-  mockFilePickerRegisterer.unregister();
-
   SimpleTest.finish();
 }
 
 SimpleTest.waitForFocus(function() {
   // mockFilePicker will simulate a cancel for the first time the file picker will be shown.
+  MockFilePicker.returnValue = MockFilePicker.returnCancel;
+
   var b2 = document.getElementById('b2');
   b2.focus(); // Be sure the element is visible.
   document.getElementById('b2').addEventListener("change", function(aEvent) {
     aEvent.target.removeEventListener("change", arguments.callee, false);
     ok(false, "When cancel is received, change should not fire");
   }, false);
-  synthesizeMouse(b2, 2, 2, {});
+  b2.click();
 
   // Now, we can launch tests when file picker isn't canceled.
+  MockFilePicker.useAnyFile();
+  MockFilePicker.returnValue = MockFilePicker.returnOK;
+
   var b = document.getElementById('b');
   b.focus(); // Be sure the element is visible.
 
   document.getElementById('a').addEventListener("change", function(aEvent) {
     ok(true, "change event correctly sent");
     ok(aEvent.bubbles, "change event should bubble");
     ok(!aEvent.cancelable, "change event should not be cancelable");
     testCounter++;
@@ -198,20 +77,20 @@ SimpleTest.waitForFocus(function() {
     } else {
       var data = testData[testCounter];
       var a = document.getElementById('a');
       a.style.visibility = data[0];
       a.style.display = data[1];
       a.multiple = data[2];
 
       SimpleTest.executeSoon(function() {
-        synthesizeMouse(b, 2, 2, {});
+        b.click();
       });
     }
   }, false);
 
-  synthesizeMouse(b, 2, 2, {});
+  b.click();
 });
 
 </script>
 </pre>
 </body>
 </html>
--- a/layout/forms/test/bug536567_subframe.html
+++ b/layout/forms/test/bug536567_subframe.html
@@ -1,77 +1,14 @@
 <!DOCTYPE html>
 <html>
-  <head>
-    <script type="application/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
-    <script type="application/javascript" src="/tests/SimpleTest/mockObjects.js"></script>
-  </head>
 <body>
 <input id="target" type="file" />
 <script type="text/javascript">
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-var Cu = Components.utils;
-var Ci = Components.interfaces;
-var Cr = Components.results;
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-function MockFilePicker() { };
-MockFilePicker.prototype = {
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIFilePicker]),
-  init: function(aParent, aTitle, aMode) { },
-  appendFilters: function(aFilterMask) { },
-  appendFilter: function(aTitle, aFilter) { },
-  defaultString: "",
-  defaultExtension: "",
-  filterIndex: 0,
-  displayDirectory: null,
-  get file() {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-    var f = window.parent.dirs[window.parent.index].clone();
-    f.append("aFile.txt");
-    return f;
-  },
-  get fileURL() {
-    throw Cr.NS_ERROR_NOT_IMPLEMENTED;
-  },
-  get files() {
-    throw Cr.NS_ERROR_NOT_IMPLEMENTED;
-  },
-  show: function MFP_show() {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-    if (this.displayDirectory)
-      window.parent.postMessage(this.displayDirectory.path, "*");
-    else
-      window.parent.postMessage("", "*");
-    mockFilePickerRegisterer.unregister();  
-    return Ci.nsIFilePicker.returnOK;
-  }
-};
-
-var mockFilePickerRegisterer =
-  new MockObjectRegisterer("@mozilla.org/filepicker;1",MockFilePicker);
-
-function test() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  var wu = window.QueryInterface(Ci.nsIInterfaceRequestor)
-                 .getInterface(Ci.nsIDOMWindowUtils);
-
+window.onload = function() {
   var fileInput = document.getElementById("target");
-  var rect = fileInput.getBoundingClientRect();
-
-  mockFilePickerRegisterer.register();
-  try {
-    wu.sendMouseEvent("mousedown", rect.left + 5, rect.top + 5, 0, 1, 0);
-    wu.sendMouseEvent("mouseup", rect.left + 5, rect.top + 5, 0, 1, 0);
-  } catch (e) {
-    Cu.reportError(e);
-  } finally {
-  }
-}
-
-window.onload = function() {
-  setTimeout(test, 0);
+  fileInput.click();
 };
 
 </script>
 </body>
 </html>
--- a/layout/forms/test/test_bug36619.html
+++ b/layout/forms/test/test_bug36619.html
@@ -2,112 +2,58 @@
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=36619
 -->
 <head>
   <title>Test for Bug 36619</title>
   <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <script type="application/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
-  <script type="application/javascript" src="/tests/SimpleTest/mockObjects.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=36619">Mozilla Bug 36619</a>
 <p id="display"></p>
 <div id="content" style="display:none;">
   <input id='a' type='file'>
 </div>
 <button id='b' onclick="document.getElementById('a').click();">Show Filepicker</button>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 36619 **/
 
 SimpleTest.waitForExplicitFinish();
 
-netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-var Cu = Components.utils;
-var Ci = Components.interfaces;
-var Cc = Components.classes;
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-function MockFilePicker()
-{
-}
-
-MockFilePicker.prototype = {
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIFilePicker]),
-
-  // properties
-  defaultExtension: "",
-  defaultString: "",
-  get displayDirectory() { return null; },
-  set displayDirectory(val) { },
-  file: null,
-  get files() { return null; },
-  get fileURL() { return null; },
-  filterIndex: 0,
-
-  // methods
-  appendFilter: function(val)
-  {
-  },
-
-  appendFilters: function(val)
-  {
-  },
-
-  init: function() {
-  },
-
-  show: function()
-  {
-    shown = true;
-  }
-};
-
-var mockFilePickerRegisterer =
-  new MockObjectRegisterer("@mozilla.org/filepicker;1",MockFilePicker);
-
-mockFilePickerRegisterer.register();
+var MockFilePicker = SpecialPowers.MockFilePicker;
+MockFilePicker.reset();
 
 // enable popups the first time
-var pbi = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch2);
-var oldAllow = pbi.getBoolPref("dom.disable_open_during_load");
-var oldShowBar = pbi.getBoolPref("privacy.popups.showBrowserMessage");
-pbi.setBoolPref("dom.disable_open_during_load", true);
-pbi.setBoolPref("privacy.popups.showBrowserMessage", false);
-
-var shown = false;
-
-function checkFirst()
-{
-  netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-  ok(shown, "File picker show method should have been called");
-  shown = false;
-  document.getElementById("a").click();
-  setTimeout(finishTest, 1000);
-}
+SpecialPowers.pushPrefEnv({'set': [
+  ["dom.disable_open_during_load", true],
+  ["privacy.popups.showBrowserMessage", false]
+]}, function() {
+  SimpleTest.waitForFocus(function() {
 
-function finishTest()
-{
-  netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-  ok(!shown, "File picker show method should not have been called");
-
-  mockFilePickerRegisterer.unregister();
+    // Tests that a click on 'b' calls the show method.
+    var b = document.getElementById('b');
+    b.focus(); // Be sure the element is visible.
+    synthesizeMouse(b, 2, 2, {});
+    SimpleTest.executeSoon(function() {
+      ok(MockFilePicker.shown, "File picker show method should have been called");
+      MockFilePicker.reset();
 
-  pbi.setBoolPref("dom.disable_open_during_load", oldAllow);
-  pbi.setBoolPref("privacy.popups.showBrowserMessage", oldShowBar);
-  SimpleTest.finish();
-}
+      // Tests that a click on 'a' doesn't call the show method, because it is hidden.
+      document.getElementById("a").click();
+      SimpleTest.executeSoon(function() {
+        ok(!MockFilePicker.shown, "File picker show method should not have been called");
+        MockFilePicker.reset();
 
-SimpleTest.waitForFocus(function() {
-  var b = document.getElementById('b');
-  b.focus(); // Be sure the element is visible.
-  synthesizeMouse(b, 2, 2, {});
-  SimpleTest.executeSoon(checkFirst);
+        SimpleTest.finish();
+      });
+    });
+  });
 });
 
 </script>
 </pre>
 </body>
 </html>
--- a/layout/forms/test/test_bug377624.html
+++ b/layout/forms/test/test_bug377624.html
@@ -4,17 +4,17 @@
 https://bugzilla.mozilla.org/show_bug.cgi?id=377624
 -->
 <head>
   <title>Test for Bug 377624</title>
   <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <script type="application/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
 </head>
-<body onload="runTests();">
+<body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=377624">Mozilla Bug 377624</a>
 <p id="display"></p>
 <div id="content">
   <input id='a' type='file' accept="image/*">
   <input id='b' type='file' accept="audio/*">
   <input id='c' type='file' accept="video/*">
   <input id='d' type='file' accept="image/*, audio/* ">
   <input id='e' type='file' accept=" image/*,video/*">
@@ -27,206 +27,79 @@ https://bugzilla.mozilla.org/show_bug.cg
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 377624 **/
 
 SimpleTest.waitForExplicitFinish();
 
-netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cm = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
-const Cu = Components.utils;
-
-const FILE_PICKER_CID = "@mozilla.org/filepicker;1";
-const FILE_PICKER_ID = Components.ID(Cc[FILE_PICKER_CID].number);
-const CUSTOM_FILE_PICKER_ID = Components.ID("d63dee33-fb6d-4547-a8d1-c12197655cce");
-const FILE_PICKER_DESCRIPTION = "File Picker Test Service";
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-// disable popups to make sure that the popup blocker does not interfere
-// with manually opened file pickers.
-var pbi = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch2);
-var oldAllow = pbi.getBoolPref("dom.disable_open_during_load");
-pbi.setBoolPref("dom.disable_open_during_load", true);
-
-function FilePickerService()
-{
-}
-
-FilePickerService.prototype = {
-  _obs: Cc["@mozilla.org/observer-service;1"].
-        getService(Ci.nsIObserverService),
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIFilePicker]),
+var MockFilePicker = SpecialPowers.MockFilePicker;
+MockFilePicker.reset();
 
-  // constants
-  modeOpen: 0,
-  modeSave: 1,
-  modeGetFolder: 2,
-  modeOpenMultiple: 3,
-  returnOK: 0,
-  returnCancel: 1,
-  returnReplace: 2,
-  filterAll: 1,
-  filterHTML: 2,
-  filterText: 4,
-  filterImages: 8,
-  filterXML: 16,
-  filterXUL: 32,
-  filterApps: 64,
-  filterAllowURLs: 128,
-  filterAudio: 256,
-  filterVideo: 512,
-
-  // properties
-  defaultExtension: "",
-  defaultString: "",
-  get displayDirectory() { return null; },
-  set displayDirectory(val) { },
-  file: null,
-  get files() { return null; },
-  get fileURL() { return null; },
-  filterIndex: 0,
-
-  // methods
-  appendFilter: function(val)
-  {
-    this._obs.notifyObservers(null, "TEST_FILEPICKER_APPENDFILTER", val);
-  },
-
-  appendFilters: function(val)
-  {
-    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-    this._obs.notifyObservers(null, "TEST_FILEPICKER_APPENDFILTERS", val);
-  },
-
-  init: function() {},
-
-  show: function()
-  {
-    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-    this._obs.notifyObservers(null, "TEST_FILEPICKER_SHOW", this.filterIndex);
-    return this.returnOK;
-  }
-};
-
-factory = {
-  createInstance: function(aOuter, aIid) {
-    if (aOuter != null)
-      throw Cr.NS_ERROR_NO_AGGREGATION;
-    return new FilePickerService().QueryInterface(aIid);
-  }
-};
-
-var testData = [["a", FilePickerService.prototype.filterImages, 1],
-                ["b", FilePickerService.prototype.filterAudio, 1],
-                ["c", FilePickerService.prototype.filterVideo, 1],
+var testData = [["a", MockFilePicker.filterImages, 1],
+                ["b", MockFilePicker.filterAudio, 1],
+                ["c", MockFilePicker.filterVideo, 1],
                 ["d", 0, 0],
                 ["e", 0, 0],
                 ["f", 0, 0],
                 ["g", 0, 0],
-                ["h", FilePickerService.prototype.filterImages, 1],
-                ["i", FilePickerService.prototype.filterVideo, 1],
-                ["j", FilePickerService.prototype.filterAudio, 1],
+                ["h", MockFilePicker.filterImages, 1],
+                ["i", MockFilePicker.filterVideo, 1],
+                ["j", MockFilePicker.filterAudio, 1],
                 ["z", 0, 0]];
 
-testData.forEach(function (datum) {
-document.getElementById(datum[0]).addEventListener("focus", function (aEvent) {
-    aEvent.target.removeEventListener("focus", arguments.callee, false);
-    synthesizeKey('VK_SPACE', {});
-  }, false);
-});
-
 var currentTest = 0;
+var appendFilterCalled;
+var filters;
+var filterIndex;
 
-function launchNextTest(aObserver)
-{
-  aObserver.shown = false;
-  aObserver.appendFilterCalled = false;
-  aObserver.filters = [];
-  aObserver.filterIndex = 0;
+// disable popups to make sure that the popup blocker does not interfere
+// with manually opened file pickers.
+SpecialPowers.pushPrefEnv({'set': [["dom.disable_open_during_load", false]]}, runTests);
 
-  document.getElementById(testData[currentTest][0]).focus();
+function launchNextTest() {
+  MockFilePicker.shown = false;
+  appendFilterCalled = false;
+  filters = [];
+  filterIndex = 0;
+
+  document.getElementById(testData[currentTest][0]).click();
 }
 
-function runTests()
-{
-  netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-
-  Cm.registerFactory(CUSTOM_FILE_PICKER_ID,
-                     FILE_PICKER_DESCRIPTION,
-                     FILE_PICKER_CID,
-                     factory);
-
-  var obs = Cc["@mozilla.org/observer-service;1"].
-            getService(Ci.nsIObserverService);
-
-  var observer = {
-    observe: function(aSubject, aTopic, aData) {
-      switch (aTopic) {
-        case "TEST_FILEPICKER_APPENDFILTER":
-          this.appendFilterCalled = true;
-          break;
-        case "TEST_FILEPICKER_APPENDFILTERS":
-          this.filters.push(aData);
-          break;
-        case "TEST_FILEPICKER_SHOW":
-          this.shown = true;
-          this.filterIndex = aData;
-
-          SimpleTest.executeSoon(function () {
-            netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
+function runTests() {
+  MockFilePicker.appendFilterCallback = function(filepicker, title, val) {
+    this.appendFilterCalled = true;
+  };
+  MockFilePicker.appendFiltersCallback = function(filepicker, val) {
+    filters.push(val);
+  };
+  MockFilePicker.showCallback = function(filepicker) {
+    filterIndex = filepicker.filterIndex;
+    SimpleTest.executeSoon(function () {
+      ok(MockFilePicker.shown,
+         "File picker show method should have been called");
+      ok(!appendFilterCalled,
+         "appendFilter should not have been called");
+      is(filters.length, 1,
+         "appendFilters should have been called once");
+      is(filters[0], MockFilePicker.filterAll +
+         testData[currentTest][1],
+         "Correct filters should have been added");
+      is(filterIndex, testData[currentTest][2],
+         "File picker should show the correct filter index");
 
-            ok(observer.shown,
-               "File picker show method should have been called");
-            ok(!observer.appendFilterCalled,
-               "appendFilter should not have been called");
-            is(observer.filters.length, 1,
-               "appendFilters should have been called once");
-            is(observer.filters[0], FilePickerService.prototype.filterAll +
-               testData[currentTest][1],
-               "Correct filters should have been added");
-            is(observer.filterIndex, testData[currentTest][2],
-               "File picker should show the correct filter index");
-
-            if (++currentTest == testData.length) {
-              obs.removeObserver(observer, "TEST_FILEPICKER_APPENDFILTER", false);
-              obs.removeObserver(observer, "TEST_FILEPICKER_APPENDFILTERS", false);
-              obs.removeObserver(observer, "TEST_FILEPICKER_SHOW", false);
-              Cm.unregisterFactory(CUSTOM_FILE_PICKER_ID, factory);
-
-              Cm.registerFactory(FILE_PICKER_ID,
-                                 "File Picker Service",
-                                 FILE_PICKER_CID,
-                                 null);
-                                 
-              pbi.setBoolPref("dom.disable_open_during_load", oldAllow);
-              SimpleTest.finish();
-            } else {
-              launchNextTest(observer);
-            }
-          } );
-          break;
+      if (++currentTest == testData.length) {
+        MockFilePicker.reset();
+        SimpleTest.finish();
+      } else {
+        launchNextTest();
       }
-    },
-    shown: false,
-    appendFilterCalled: false,
-    filters: [],
-    filterIndex: 0
+    });
   };
 
-  obs.addObserver(observer, "TEST_FILEPICKER_APPENDFILTER", false);
-  obs.addObserver(observer, "TEST_FILEPICKER_APPENDFILTERS", false);
-  obs.addObserver(observer, "TEST_FILEPICKER_SHOW", false);
-
-  // We are simulating a focus then a SPACE key press to open the file picker.
-  // We were not able to do this with |synthesizeMouse|.
-  launchNextTest(observer);
+  launchNextTest();
 }
 
 </script>
 </pre>
 </body>
 </html>
--- a/layout/forms/test/test_bug536567.html
+++ b/layout/forms/test/test_bug536567.html
@@ -2,31 +2,35 @@
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=536567
 -->
 <head>
   <title>Test for Bug 536567</title>
   <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
   <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"></script>
+  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=536567">Mozilla Bug 536567</a>
 <p id="display"></p>
 <iframe id="content"></iframe>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 536567 **/
 
 const Cc = Components.classes;
 const Ci = Components.interfaces;
 const Cu = Components.utils;
 const Cm = Components.manager;
 
+var MockFilePicker = SpecialPowers.MockFilePicker;
+MockFilePicker.reset();
+
 var ioSvc = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
 var dirSvc = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties);
 var prefSvc = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
 var obSvc = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
 if ("@mozilla.org/privatebrowsing;1" in Cc) {
   var pbSvc = Cc["@mozilla.org/privatebrowsing;1"].getService(Ci.nsIPrivateBrowsingService);
 }
 
@@ -87,17 +91,16 @@ var tests = [
   [2, 3, 3], //-> x
   "clear history",
   [0, 6, 0],
   [1, 6, 1],
   [2, 6, 2],
   "pb off"
 ];
 
-var index;
 var testIndex = 0;
 var content = document.getElementById('content');
 
 function runTest() {
   var test = tests[testIndex];
   if (test == undefined) {
     endTest();
   } else if (test == "pb on") {
@@ -113,48 +116,53 @@ function runTest() {
     pbSvc.privateBrowsingEnabled = false;
     testIndex++;
     runTest();
   } else if (test == "clear history") {
     obSvc.notifyObservers(null, "browser:purge-session-history", "");
     testIndex++;
     runTest();
   } else {
-    index = test[2];
+    var file = dirs[test[2]].clone();
+    file.append("file.file");
+    MockFilePicker.returnFiles = [file];
     content.setAttribute ('src', domains[test[0]] + '/chrome/layout/forms/test/bug536567_subframe.html');
   }
 }
 
 function endTest() {
     prefSvc.clearUserPref("browser.privatebrowsing.keep_current_session");
     for(var i = 0; i < dirs.length - 1; i++) {
       dirs[i].remove(true);
     }
 
+    MockFilePicker.reset();
     SimpleTest.finish();
 }
 
-window.addEventListener("message", function(event) {
+MockFilePicker.showCallback = function(filepicker) {
   var test = tests[testIndex];
   var returned = -1;
   for (var i = 0; i < dirs.length; i++) {
-    if (dirs[i].path == event.data) {
+    if (dirs[i].path == MockFilePicker.displayDirectory.path) {
       returned = i;
       break;
     }
   }
   if (test[1] == -1) {
     ok(false, "We should never get an unknown directory back");
   } else {
     is(returned, test[1], 'test ' + testIndex);
   }
-  
-  testIndex++;
-  runTest();
-}, false);
+
+  SimpleTest.executeSoon(function() {
+    testIndex++;
+    runTest();
+  });
+};
 
 window.onload = function() {
   SimpleTest.waitForExplicitFinish();
   setTimeout(runTest, 0);
 };
 
 </script>
 </pre>
new file mode 100644
--- /dev/null
+++ b/testing/mochitest/MockFilePicker.jsm
@@ -0,0 +1,138 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Mochitest Reusable Mock File Picker.
+ *
+ * The Initial Developer of the Original Code is
+ * Geoff Lankow <geoff@darktrojan.net>.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+var EXPORTED_SYMBOLS = ["MockFilePicker"];
+
+const Cc = Components.classes;
+const Ci = Components.interfaces;
+const Cm = Components.manager;
+const Cu = Components.utils;
+
+const CONTRACT_ID = "@mozilla.org/filepicker;1";
+const CLASS_ID = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator).generateUUID();
+
+Cu.import("resource://gre/modules/FileUtils.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+var registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
+
+var MockFilePickerFactory = {
+  createInstance: function(aOuter, aIID) {
+    if (aOuter)
+      throw Components.results.NS_ERROR_NO_AGGREGATION;
+    return new MockFilePickerInstance().QueryInterface(aIID);
+  },
+  lockFactory: function(aLock) {
+    throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
+  },
+  QueryInterface: XPCOMUtils.generateQI([Ci.nsIFactory])
+};
+
+var MockFilePicker = {
+  returnOK: Ci.nsIFilePicker.returnOK,
+  returnCancel: Ci.nsIFilePicker.returnCancel,
+  returnReplace: Ci.nsIFilePicker.returnReplace,
+
+  filterAll: Ci.nsIFilePicker.filterAll,
+  filterHTML: Ci.nsIFilePicker.filterHTML,
+  filterText: Ci.nsIFilePicker.filterText,
+  filterImages: Ci.nsIFilePicker.filterImages,
+  filterXML: Ci.nsIFilePicker.filterXML,
+  filterXUL: Ci.nsIFilePicker.filterXUL,
+  filterApps: Ci.nsIFilePicker.filterApps,
+  filterAllowURLs: Ci.nsIFilePicker.filterAllowURLs,
+  filterAudio: Ci.nsIFilePicker.filterAudio,
+  filterVideo: Ci.nsIFilePicker.filterVideo,
+
+  reset: function() {
+    this.appendFilterCallback = null;
+    this.appendFiltersCallback = null;
+    this.displayDirectory = null;
+    this.filterIndex = 0;
+    this.mode = null;
+    this.returnFiles = [];
+    this.returnValue = null;
+    this.showCallback = null;
+    this.shown = false;
+    if (!registrar.isCIDRegistered(CLASS_ID))
+      registrar.registerFactory(CLASS_ID, "", CONTRACT_ID, MockFilePickerFactory);
+  },
+
+  useAnyFile: function() {
+    var file = FileUtils.getFile("TmpD", ["testfile"]);
+    file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0644);
+    this.returnFiles = [file];
+  }
+};
+
+function MockFilePickerInstance() { };
+MockFilePickerInstance.prototype = {
+  QueryInterface: XPCOMUtils.generateQI([Ci.nsIFilePicker]),
+  init: function(aParent, aTitle, aMode) {
+    MockFilePicker.mode = aMode;
+    this.filterIndex = MockFilePicker.filterIndex;
+  },
+  appendFilter: function(aTitle, aFilter) {
+    if (typeof MockFilePicker.appendFilterCallback == "function")
+      MockFilePicker.appendFilterCallback(this, aTitle, aFilter);
+  },
+  appendFilters: function(aFilterMask) {
+    if (typeof MockFilePicker.appendFiltersCallback == "function")
+      MockFilePicker.appendFiltersCallback(this, aFilterMask);
+  },
+  defaultString: "",
+  defaultExtension: "",
+  filterIndex: 0,
+  displayDirectory: null,
+  get file() {
+    if (MockFilePicker.returnFiles.length >= 1)
+      return MockFilePicker.returnFiles[0];
+    return null;
+  },
+  get fileURL() {
+    if (MockFilePicker.returnFiles.length >= 1)
+      return Services.io.newFileURI(MockFilePicker.returnFiles[0]);
+    return null;
+  },
+  get files() {
+    return {
+      index: 0,
+      QueryInterface: XPCOMUtils.generateQI([Ci.nsISimpleEnumerator]),
+      hasMoreElements: function() {
+        return this.index < MockFilePicker.returnFiles.length;
+      },
+      getNext: function() {
+        return MockFilePicker.returnFiles[this.index++];
+      }
+    };
+  },
+  show: function() {
+    MockFilePicker.displayDirectory = this.displayDirectory;
+    MockFilePicker.shown = true;
+    if (typeof MockFilePicker.showCallback == "function")
+      MockFilePicker.showCallback(this);
+    return MockFilePicker.returnValue;
+  }
+};
--- a/testing/mochitest/jar.mn
+++ b/testing/mochitest/jar.mn
@@ -21,8 +21,10 @@ mochikit.jar:
   content/tests/SimpleTest/setup.js (tests/SimpleTest/setup.js)
   content/tests/SimpleTest/SimpleTest.js (tests/SimpleTest/SimpleTest.js)
   content/tests/SimpleTest/test.css (tests/SimpleTest/test.css)
   content/tests/SimpleTest/TestRunner.js (tests/SimpleTest/TestRunner.js)
   content/tests/SimpleTest/WindowSnapshot.js (tests/SimpleTest/WindowSnapshot.js)
   content/tests/SimpleTest/mockObjects.js (../../toolkit/content/tests/browser/common/mockObjects.js)
   content/tests/SimpleTest/docshell_helpers.js (../..//docshell/test/chrome/docshell_helpers.js)
 
+% resource mochikit %modules/
+  modules/MockFilePicker.jsm (MockFilePicker.jsm)
--- a/testing/mochitest/tests/SimpleTest/specialpowersAPI.js
+++ b/testing/mochitest/tests/SimpleTest/specialpowersAPI.js
@@ -37,16 +37,18 @@
  * ***** END LICENSE BLOCK *****/
 /* This code is loaded in every child process that is started by mochitest in
  * order to be used as a replacement for UniversalXPConnect
  */
 
 var Ci = Components.interfaces;
 var Cc = Components.classes;
 
+Components.utils.import("resource://mochikit/MockFilePicker.jsm");
+
 function SpecialPowersAPI() { 
   this._consoleListeners = [];
   this._encounteredCrashDumpFiles = [];
   this._unexpectedCrashDumpFiles = { };
   this._crashDumpDir = null;
   this._mfl = null;
   this._prefEnvUndoStack = [];
   this._pendingPrefs = [];
@@ -127,16 +129,20 @@ Observer.prototype = {
               .QueryInterface(Ci.nsIObserverService);
       os.removeObserver(this, this._topic);
     }
   },
 };
 
 SpecialPowersAPI.prototype = {
 
+  get MockFilePicker() {
+    return MockFilePicker
+  },
+
   getDOMWindowUtils: function(aWindow) {
     if (aWindow == this.window && this.DOMWindowUtils != null)
       return this.DOMWindowUtils;
 
     return bindDOMWindowUtils(aWindow);
   },
 
   removeExpectedCrashDumpFiles: function(aExpectingProcessCrash) {
--- a/toolkit/content/tests/browser/browser_save_resend_postdata.js
+++ b/toolkit/content/tests/browser/browser_save_resend_postdata.js
@@ -29,16 +29,19 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
+var MockFilePicker = SpecialPowers.MockFilePicker;
+MockFilePicker.reset();
+
 /**
  * Test for bug 471962 <https://bugzilla.mozilla.org/show_bug.cgi?id=471962>:
  * When saving an inner frame as file only, the POST data of the outer page is
  * sent to the address of the inner page.
  *
  * Test for bug 485196 <https://bugzilla.mozilla.org/show_bug.cgi?id=485196>:
  * Web page generated by POST is retried as GET when Save Frame As used, and the
  * page is no longer in the cache.
@@ -80,44 +83,47 @@ function test() {
     innerFrame.contentDocument.getElementById("postForm").submit();
   }
 
   function handleInnerSubmit() {
     gBrowser.removeEventListener("DOMContentLoaded", handleInnerSubmit);
 
     // Create the folder the page will be saved into.
     var destDir = createTemporarySaveDirectory();
-
-    mockFilePickerSettings.destDir = destDir;
-    mockFilePickerSettings.filterIndex = 1; // kSaveAsType_URL
-    mockFilePickerRegisterer.register();
+    var file = destDir.clone();
+    file.append("no_default_file_name");
+    MockFilePicker.returnFiles = [file];
+    MockFilePicker.showCallback = function(fp) {
+      MockFilePicker.filterIndex = 1; // kSaveAsType_URL
+    };
 
     mockTransferCallback = onTransferComplete;
     mockTransferRegisterer.register();
 
     registerCleanupFunction(function () {
       mockTransferRegisterer.unregister();
-      mockFilePickerRegisterer.unregister();
+      MockFilePicker.reset();
       destDir.remove(true);
     });
 
     var docToSave = innerFrame.contentDocument;
     // We call internalSave instead of saveDocument to bypass the history
     // cache.
     internalSave(docToSave.location.href, docToSave, null, null,
                  docToSave.contentType, false, null, null,
                  docToSave.referrer ? makeURI(docToSave.referrer) : null,
                  false, null);
   }
 
   function onTransferComplete(downloadSuccess) {
     ok(downloadSuccess, "The inner frame should have been downloaded successfully");
 
     // Read the entire saved file.
-    var fileContents = readShortFile(mockFilePickerResults.selectedFile);
+    var file = MockFilePicker.returnFiles[0];
+    var fileContents = readShortFile(file);
 
     // Check if outer POST data is found (bug 471962).
     is(fileContents.indexOf("inputfield=outer"), -1,
        "The saved inner frame does not contain outer POST data");
 
     // Check if inner POST data is found (bug 485196).
     isnot(fileContents.indexOf("inputfield=inner"), -1,
           "The saved inner frame was generated using the correct POST data");
@@ -126,21 +132,16 @@ function test() {
   }
 }
 
 Cc["@mozilla.org/moz/jssubscript-loader;1"]
   .getService(Ci.mozIJSSubScriptLoader)
   .loadSubScript("chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockTransfer.js",
                  this);
 
-Cc["@mozilla.org/moz/jssubscript-loader;1"]
-  .getService(Ci.mozIJSSubScriptLoader)
-  .loadSubScript("chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockFilePicker.js",
-                 this);
-
 function createTemporarySaveDirectory() {
   var saveDir = Cc["@mozilla.org/file/directory_service;1"]
                   .getService(Ci.nsIProperties)
                   .get("TmpD", Ci.nsIFile);
   saveDir.append("testsavedir");
   if (!saveDir.exists())
     saveDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0755);
   return saveDir;
--- a/toolkit/content/tests/browser/common/Makefile.in
+++ b/toolkit/content/tests/browser/common/Makefile.in
@@ -40,15 +40,14 @@ topsrcdir      = @top_srcdir@
 srcdir         = @srcdir@
 VPATH          = @srcdir@
 relativesrcdir = toolkit/content/tests/browser/common
 
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _COMMON_FILES = \
-  mockFilePicker.js \
   mockObjects.js \
   mockTransfer.js \
   $(NULL)
 
 libs:: $(_COMMON_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/browser/$(relativesrcdir)
deleted file mode 100644
--- a/toolkit/content/tests/browser/common/mockFilePicker.js
+++ /dev/null
@@ -1,119 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is Mozilla XUL Toolkit Testing Code.
- *
- * The Initial Developer of the Original Code is
- * Paolo Amadini <http://www.amadzone.org/>.
- * Portions created by the Initial Developer are Copyright (C) 2009
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-Cc["@mozilla.org/moz/jssubscript-loader;1"]
-  .getService(Ci.mozIJSSubScriptLoader)
-  .loadSubScript("chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockObjects.js",
-                 this);
-
-var mockFilePickerSettings = {
-  /**
-   * File object pointing to the directory where the files will be saved.
-   * The files will be saved with the default name, and will be overwritten
-   * if they exist.
-   */
-  destDir: null,
-
-  /**
-   * Index of the filter to be returned by the file picker, or -1 to return
-   * the filter proposed by the caller.
-   */
-  filterIndex: -1
-};
-
-var mockFilePickerResults = {
-  /**
-   * File object corresponding to the last automatically selected file.
-   */
-  selectedFile: null,
-
-  /**
-   * Index of the filter that was set on the file picker by the caller.
-   */
-  proposedFilterIndex: -1
-};
-
-/**
- * This file picker implementation uses the global settings defined in
- * mockFilePickerSettings, and updates the mockFilePickerResults object
- * when its "show" method is called.
- */
-function MockFilePicker() { };
-MockFilePicker.prototype = {
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIFilePicker]),
-  init: function () {},
-  appendFilters: function () {},
-  appendFilter: function () {},
-  defaultString: "",
-  defaultExtension: "",
-  filterIndex: 0,
-  displayDirectory: null,
-  file: null,
-  get fileURL() {
-    return Cc["@mozilla.org/network/io-service;1"].
-           getService(Ci.nsIIOService).newFileURI(this.file);
-  },
-  get files() {
-    throw Cr.NS_ERROR_NOT_IMPLEMENTED;
-  },
-  show: function MFP_show() {
-    // Select the destination file with the specified default file name. If the
-    // default file name was never specified or was set to an empty string by
-    // the caller, ensure that a fallback file name is used.
-    this.file = mockFilePickerSettings.destDir.clone();
-    this.file.append(this.defaultString || "no_default_file_name");
-    // Store the current file picker settings for testing them later.
-    mockFilePickerResults.selectedFile = this.file.clone();
-    mockFilePickerResults.proposedFilterIndex = this.filterIndex;
-    // Select a different file filter if required.
-    if (mockFilePickerSettings.filterIndex != -1)
-      this.filterIndex = mockFilePickerSettings.filterIndex;
-    // Assume we overwrite the file if it exists.
-    return (this.file.exists() ?
-            Ci.nsIFilePicker.returnReplace :
-            Ci.nsIFilePicker.returnOK);
-  }
-};
-
-// Create an instance of a MockObjectRegisterer whose methods can be used to
-// temporarily replace the default "@mozilla.org/filepicker;1" object factory
-// with one that provides the mock implementation above. To activate the mock
-// object factory, call the "register" method. Starting from that moment, all
-// the file picker objects that are requested will be mock objects, until the
-// "unregister" method is called.
-var mockFilePickerRegisterer =
-  new MockObjectRegisterer("@mozilla.org/filepicker;1",
-                           MockFilePicker);
--- a/toolkit/mozapps/downloads/tests/Makefile.in
+++ b/toolkit/mozapps/downloads/tests/Makefile.in
@@ -49,8 +49,11 @@ MODULE = test_downloads
 
 XPCSHELL_TESTS = \
   unit \
   $(NULL)
 
 DIRS += chrome
 
 include $(topsrcdir)/config/rules.mk
+
+libs:: 
+	$(INSTALL) $(topsrcdir)/testing/mochitest/MockFilePicker.jsm $(DEPTH)/_tests/xpcshell/$(relativesrcdir)/unit
--- a/toolkit/mozapps/downloads/tests/unit/test_privatebrowsing_downloadLastDir.js
+++ b/toolkit/mozapps/downloads/tests/unit/test_privatebrowsing_downloadLastDir.js
@@ -35,21 +35,16 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 const Ci = Components.interfaces;
 const Cc = Components.classes;
 const Cu = Components.utils;
 const Cr = Components.results;
-const Cm = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
-
-const FILE_PICKER_CID = "@mozilla.org/filepicker;1";
-const FILE_PICKER_ID = Components.ID("fa71ce55-6524-4744-ba75-71a4c126cfa3");
-const FILE_PICKER_DESCRIPTION = "File Picker Test Service";
 
 // Code borrowed from toolkit/components/downloadmgr/test/unit/head_download_manager.js
 var dirSvc = Cc["@mozilla.org/file/directory_service;1"].
              getService(Ci.nsIProperties);
 var profileDir = null;
 try {
   profileDir = dirSvc.get("ProfD", Ci.nsIFile);
 } catch (e) { }
@@ -77,105 +72,42 @@ if (!profileDir) {
       throw Cr.NS_ERROR_NO_INTERFACE;
     }
   };
   dirSvc.QueryInterface(Ci.nsIDirectoryService).registerProvider(provider);
 }
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/DownloadLastDir.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 
 let context = {
   QueryInterface: XPCOMUtils.generateQI([Ci.nsIInterfaceRequestor]),
   getInterface: XPCOMUtils.generateQI([Ci.nsIDOMWindow])
 };
 
-function FilePickerService() {
-}
-
-FilePickerService.prototype = {
-  _obs: Cc["@mozilla.org/observer-service;1"].
-        getService(Ci.nsIObserverService),
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIFilePicker]),
-
-  // constants
-  modeOpen: 0,
-  modeSave: 1,
-  modeGetFolder: 2,
-  modeOpenMultiple: 3,
-  returnOK: 0,
-  returnCancel: 1,
-  returnReplace: 2,
-  filterAll: 1,
-  filterHTML: 2,
-  filterText: 4,
-  filterImages: 8,
-  filterXML: 16,
-  filterXUL: 32,
-  filterApps: 64,
-
-  // properties
-  defaultExtension: "",
-  defaultString: "",
-  get displayDirectory() { return null; },
-  set displayDirectory(val) {
-    this._obs.notifyObservers(val, "TEST_FILEPICKER_SETDISPLAYDIRECTORY", "");
-  },
-  file: null,
-  get files() { return null; },
-  get fileURL() { return null; },
-  filterIndex: 0,
-
-  // methods
-  appendFilter: function() {},
-  appendFilters: function() {},
-  init: function() {
-    var fileptr = Cc["@mozilla.org/supports-interface-pointer;1"].
-                  createInstance(Ci.nsISupportsInterfacePointer);
-    this._obs.notifyObservers(fileptr, "TEST_FILEPICKER_GETFILE", "");
-    this.file = fileptr.data.QueryInterface(fileptr.dataIID);
-  },
-  show: function() {
-    return this.returnOK;
-  }
-};
-
-let factory = {
-  createInstance: function(aOuter, aIid) {
-    if (aOuter != null)
-      throw Cr.NS_ERROR_NO_AGGREGATION;
-    return new FilePickerService().QueryInterface(aIid);
-  }
-};
+Cu.import("resource://test/MockFilePicker.jsm");
+MockFilePicker.reset();
+MockFilePicker.returnValue = Ci.nsIFilePicker.returnOK;
 
 function run_test()
 {
   let pb;
   try {
     pb = Cc["@mozilla.org/privatebrowsing;1"].
          getService(Ci.nsIPrivateBrowsingService);
   } catch (e) {
     print("PB service is not available, bail out");
     return;
   }
 
-  //do_load_module("filepicker.js");
-  Cm.registerFactory(FILE_PICKER_ID,
-                     FILE_PICKER_DESCRIPTION,
-                     FILE_PICKER_CID,
-                     factory);
-
   let prefsService = Cc["@mozilla.org/preferences-service;1"].
                      getService(Ci.nsIPrefService).
                      QueryInterface(Ci.nsIPrefBranch);
   prefsService.setBoolPref("browser.privatebrowsing.keep_current_session", true);
   let prefs = prefsService.getBranch("browser.download.");
-  let obs = Cc["@mozilla.org/observer-service;1"].
-            getService(Ci.nsIObserverService);
   let launcher = Cc["@mozilla.org/helperapplauncherdialog;1"].
                  getService(Ci.nsIHelperAppLauncherDialog);
   let dirSvc = Cc["@mozilla.org/file/directory_service;1"].
                getService(Ci.nsIProperties);
   let tmpDir = dirSvc.get("TmpD", Ci.nsILocalFile);
   function newDirectory() {
     let dir = tmpDir.clone();
     dir.append("testdir" + Math.floor(Math.random() * 10000));
@@ -190,73 +122,54 @@ function run_test()
   }
   let dir1 = newDirectory();
   let dir2 = newDirectory();
   let dir3 = newDirectory();
   let file1 = newFileInDirectory(dir1);
   let file2 = newFileInDirectory(dir2);
   let file3 = newFileInDirectory(dir3);
 
-  let observer = {
-    observe: function(aSubject, aTopic, aData) {
-      switch (aTopic) {
-      case "TEST_FILEPICKER_GETFILE":
-        let fileptr = aSubject.QueryInterface(Ci.nsISupportsInterfacePointer);
-        fileptr.data = this.file;
-        fileptr.dataIID = Ci.nsILocalFile;
-        break;
-      case "TEST_FILEPICKER_SETDISPLAYDIRECTORY":
-        this.displayDirectory = aSubject.QueryInterface(Ci.nsILocalFile);
-        break;
-      }
-    },
-    file: null,
-    displayDirectory: null
-  };
-  obs.addObserver(observer, "TEST_FILEPICKER_GETFILE", false);
-  obs.addObserver(observer, "TEST_FILEPICKER_SETDISPLAYDIRECTORY", false);
-
   prefs.setComplexValue("lastDir", Ci.nsILocalFile, tmpDir);
 
-  observer.file = file1;
+  MockFilePicker.returnFiles = [file1];
   let file = launcher.promptForSaveToFile(null, context, null, null, null);
   do_check_true(!!file);
   // file picker should start with browser.download.lastDir
-  do_check_eq(observer.displayDirectory.path, tmpDir.path);
+  do_check_eq(MockFilePicker.displayDirectory.path, tmpDir.path);
   // browser.download.lastDir should be modified before entering the private browsing mode
   do_check_eq(prefs.getComplexValue("lastDir", Ci.nsILocalFile).path, dir1.path);
   // gDownloadLastDir should be usable outside of the private browsing mode
   do_check_eq(gDownloadLastDir.file.path, dir1.path);
 
   pb.privateBrowsingEnabled = true;
   do_check_eq(prefs.getComplexValue("lastDir", Ci.nsILocalFile).path, dir1.path);
-  observer.file = file2;
-  observer.displayDirectory = null;
+  MockFilePicker.returnFiles = [file2];
+  MockFilePicker.displayDirectory = null;
   file = launcher.promptForSaveToFile(null, context, null, null, null);
   do_check_true(!!file);
   // file picker should start with browser.download.lastDir as set before entering the private browsing mode
-  do_check_eq(observer.displayDirectory.path, dir1.path);
+  do_check_eq(MockFilePicker.displayDirectory.path, dir1.path);
   // browser.download.lastDir should not be modified inside the private browsing mode
   do_check_eq(prefs.getComplexValue("lastDir", Ci.nsILocalFile).path, dir1.path);
   // but gDownloadLastDir should be modified
   do_check_eq(gDownloadLastDir.file.path, dir2.path);
 
   pb.privateBrowsingEnabled = false;
   // gDownloadLastDir should be cleared after leaving the private browsing mode
   do_check_eq(gDownloadLastDir.file.path, dir1.path);
-  observer.file = file3;
-  observer.displayDirectory = null;
+  MockFilePicker.returnFiles = [file3];
+  MockFilePicker.displayDirectory = null;
   file = launcher.promptForSaveToFile(null, context, null, null, null);
   do_check_true(!!file);
   // file picker should start with browser.download.lastDir as set before entering the private browsing mode
-  do_check_eq(observer.displayDirectory.path, dir1.path);
+  do_check_eq(MockFilePicker.displayDirectory.path, dir1.path);
   // browser.download.lastDir should be modified after leaving the private browsing mode
   do_check_eq(prefs.getComplexValue("lastDir", Ci.nsILocalFile).path, dir3.path);
   // gDownloadLastDir should be usable after leaving the private browsing mode
   do_check_eq(gDownloadLastDir.file.path, dir3.path);
 
   // cleanup
   prefsService.clearUserPref("browser.privatebrowsing.keep_current_session");
   [dir1, dir2, dir3].forEach(function(dir) dir.remove(true));
   dirSvc.QueryInterface(Ci.nsIDirectoryService).unregisterProvider(provider);
-  obs.removeObserver(observer, "TEST_FILEPICKER_GETFILE", false);
-  obs.removeObserver(observer, "TEST_FILEPICKER_SETDISPLAYDIRECTORY", false);
+
+  MockFilePicker.reset();
 }
--- a/toolkit/mozapps/extensions/test/browser/browser_bug567127.js
+++ b/toolkit/mozapps/extensions/test/browser/browser_bug567127.js
@@ -1,48 +1,20 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/
  */
 
 // Tests bug 567127 - Add install button to the add-ons manager
 
+var MockFilePicker = SpecialPowers.MockFilePicker;
+MockFilePicker.reset();
 
-var gFilePickerFiles = [];
-var gMockFilePickerFactory;
-var gMockFilePickerFactoryCID;
 var gManagerWindow;
 var gSawInstallNotification = false;
 
-function MockFilePicker() { }
-
-MockFilePicker.prototype = {
-  QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIFilePicker]),
-  init: function(aParent, aTitle, aMode) { },
-  appendFilters: function(aFilterMask) { },
-  appendFilter: function(aTitle, aFilter) { },
-  defaultString: "",
-  defaultExtension: "",
-  filterIndex: 0,
-  displayDirectory: null,
-  file: null,
-  fileURL: null,
-  get files() {
-    var i = 0;
-    return {
-      getNext: function() gFilePickerFiles[i++],
-      hasMoreElements: function() gFilePickerFiles.length > i
-    };
-  },
-  show: function() {
-    return gFilePickerFiles.length == 0 ?
-           Components.interfaces.nsIFilePicker.returnCancel :
-           Components.interfaces.nsIFilePicker.returnOK;
-  }
-};
-
 // This listens for the next opened window and checks it is of the right url.
 // opencallback is called when the new window is fully loaded
 // closecallback is called when the window is closed
 function WindowOpenListener(url, opencallback, closecallback) {
   this.url = url;
   this.opencallback = opencallback;
   this.closecallback = closecallback;
 
@@ -126,48 +98,38 @@ function test_confirmation(aWindow, aExp
 
   aWindow.document.documentElement.cancelDialog();
 }
 
 
 function test() {
   waitForExplicitFinish();
   
-  gMockFilePickerFactoryCID = Components.ID("{4f595df2-9108-42c6-9910-0dc392a310c9}");
-  gMockFilePickerFactory = XPCOMUtils._getFactory(MockFilePicker);
-  var compReg = Components.manager.QueryInterface(Components.interfaces.nsIComponentRegistrar);
-  compReg.registerFactory(gMockFilePickerFactoryCID,
-                          "Mock FilePicker",
-                          "@mozilla.org/filepicker;1",
-                          gMockFilePickerFactory);
-
   open_manager("addons://list/extension", function(aWindow) {
     gManagerWindow = aWindow;
     run_next_test();
   });
 }
 
 function end_test() {
   is(gSawInstallNotification, true, "Should have seen addon-install-started notification.");
 
-  var compReg = Components.manager.QueryInterface(Components.interfaces.nsIComponentRegistrar);
-  compReg.unregisterFactory(gMockFilePickerFactoryCID,
-                            gMockFilePickerFactory);
+  MockFilePicker.reset();
   close_manager(gManagerWindow, function() {
     finish();
   });
 }
 
 
 add_test(function() {
   var filePaths = [
                    get_addon_file_url("browser_bug567127_1.xpi"),
                    get_addon_file_url("browser_bug567127_2.xpi")
                   ];
-  gFilePickerFiles = filePaths.map(function(aPath) aPath.file);
+  MockFilePicker.returnFiles = filePaths.map(function(aPath) aPath.file);
   
   Services.obs.addObserver(gInstallNotificationObserver,
                            "addon-install-started", false);
 
   new WindowOpenListener(INSTALL_URI, function(aWindow) {
     test_confirmation(aWindow, filePaths.map(function(aPath) aPath.spec));
   }, run_next_test);
 
--- a/toolkit/mozapps/extensions/test/browser/browser_inlinesettings.js
+++ b/toolkit/mozapps/extensions/test/browser/browser_inlinesettings.js
@@ -5,16 +5,19 @@
 // Tests various aspects of the details view
 
 var gManagerWindow;
 var gCategoryUtilities;
 var gProvider;
 
 const SETTINGS_ROWS = 8;
 
+var MockFilePicker = SpecialPowers.MockFilePicker;
+MockFilePicker.reset();
+
 var observer = {
   lastData: null,
   observe: function(aSubject, aTopic, aData) {
     if (aTopic == "addon-options-displayed")
       this.lastData = aData;
   }
 };
 
@@ -77,16 +80,18 @@ function end_test() {
   Services.prefs.clearUserPref("extensions.inlinesettings1.color");
   Services.prefs.clearUserPref("extensions.inlinesettings1.file");
   Services.prefs.clearUserPref("extensions.inlinesettings1.directory");
   Services.prefs.clearUserPref("extensions.inlinesettings3.radioBool");
   Services.prefs.clearUserPref("extensions.inlinesettings3.radioInt");
   Services.prefs.clearUserPref("extensions.inlinesettings3.radioString");
   Services.prefs.clearUserPref("extensions.inlinesettings3.menulist");
 
+  MockFilePicker.reset();
+
   close_manager(gManagerWindow, function() {
     AddonManager.getAddonByID("inlinesettings1@tests.mozilla.org", function(aAddon) {
       aAddon.uninstall();
       finish();
     });
   });
 }
 
@@ -207,62 +212,58 @@ add_test(function() {
     EventUtils.synthesizeKey("VK_RIGHT", {}, gManagerWindow);
     EventUtils.synthesizeKey("VK_RIGHT", {}, gManagerWindow);
     EventUtils.synthesizeKey("VK_RETURN", {}, gManagerWindow);
     input.hidePopup();
     is(input.color, "#FF9900", "Color picker should have updated value");
     is(Services.prefs.getCharPref("extensions.inlinesettings1.color"), "#FF9900", "Color pref should have been updated");
 
     try {
-      mockFilePickerFactory.register();
-
       ok(!settings[6].hasAttribute("first-row"), "Not the first row");
       var button = gManagerWindow.document.getAnonymousElementByAttribute(settings[6], "anonid", "button");
       input = gManagerWindow.document.getAnonymousElementByAttribute(settings[6], "anonid", "input");
       is(input.value, "", "Label value should be empty");
 
       var profD = Services.dirsvc.get("ProfD", Ci.nsIFile);
       var curProcD = Services.dirsvc.get("CurProcD", Ci.nsIFile);
 
-      _returnFile = profD;
-      _returnValue = Ci.nsIFilePicker.returnOK;
+      MockFilePicker.returnFiles = [profD];
+      MockFilePicker.returnValue = Ci.nsIFilePicker.returnOK;
       EventUtils.synthesizeMouseAtCenter(button, { clickCount: 1 }, gManagerWindow);
-      is(_mode, Ci.nsIFilePicker.modeOpen, "File picker mode should be open file");
+      is(MockFilePicker.mode, Ci.nsIFilePicker.modeOpen, "File picker mode should be open file");
       is(input.value, profD.path, "Label value should match file chosen");
       is(Services.prefs.getCharPref("extensions.inlinesettings1.file"), profD.path, "File pref should match file chosen");
 
-      _returnFile = curProcD;
-      _returnValue = Ci.nsIFilePicker.returnCancel;
+      MockFilePicker.returnFiles = [curProcD];
+      MockFilePicker.returnValue = Ci.nsIFilePicker.returnCancel;
       EventUtils.synthesizeMouseAtCenter(button, { clickCount: 1 }, gManagerWindow);
-      is(_mode, Ci.nsIFilePicker.modeOpen, "File picker mode should be open file");
+      is(MockFilePicker.mode, Ci.nsIFilePicker.modeOpen, "File picker mode should be open file");
       is(input.value, profD.path, "Label value should not have changed");
       is(Services.prefs.getCharPref("extensions.inlinesettings1.file"), profD.path, "File pref should not have changed");
 
       ok(!settings[7].hasAttribute("first-row"), "Not the first row");
       button = gManagerWindow.document.getAnonymousElementByAttribute(settings[7], "anonid", "button");
       input = gManagerWindow.document.getAnonymousElementByAttribute(settings[7], "anonid", "input");
       is(input.value, "", "Label value should be empty");
 
-      _returnFile = profD;
-      _returnValue = Ci.nsIFilePicker.returnOK;
+      MockFilePicker.returnFiles = [profD];
+      MockFilePicker.returnValue = Ci.nsIFilePicker.returnOK;
       EventUtils.synthesizeMouseAtCenter(button, { clickCount: 1 }, gManagerWindow);
-      is(_mode, Ci.nsIFilePicker.modeGetFolder, "File picker mode should be directory");
+      is(MockFilePicker.mode, Ci.nsIFilePicker.modeGetFolder, "File picker mode should be directory");
       is(input.value, profD.path, "Label value should match file chosen");
       is(Services.prefs.getCharPref("extensions.inlinesettings1.directory"), profD.path, "Directory pref should match file chosen");
 
-      _returnFile = curProcD;
-      _returnValue = Ci.nsIFilePicker.returnCancel;
+      MockFilePicker.returnFiles = [curProcD];
+      MockFilePicker.returnValue = Ci.nsIFilePicker.returnCancel;
       EventUtils.synthesizeMouseAtCenter(button, { clickCount: 1 }, gManagerWindow);
-      is(_mode, Ci.nsIFilePicker.modeGetFolder, "File picker mode should be directory");
+      is(MockFilePicker.mode, Ci.nsIFilePicker.modeGetFolder, "File picker mode should be directory");
       is(input.value, profD.path, "Label value should not have changed");
       is(Services.prefs.getCharPref("extensions.inlinesettings1.directory"), profD.path, "Directory pref should not have changed");
 
     } finally {
-      mockFilePickerFactory.unregister();
-
       button = gManagerWindow.document.getElementById("detail-prefs-btn");
       is_element_hidden(button, "Preferences button should not be visible");
 
       gCategoryUtilities.openType("extension", run_next_test);
     }
   });
 });
 
@@ -470,65 +471,8 @@ add_test(function() {
         settings = grid.querySelectorAll("rows > setting");
         is(settings.length, SETTINGS_ROWS, "Grid should have settings children");
 
         gCategoryUtilities.openType("extension", run_next_test);
       });
     });
   });
 });
-
-var _returnFile, _returnValue, _mode;
-
-function MockFilePicker() { };
-MockFilePicker.prototype = {
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIFilePicker]),
-  init: function(aParent, aTitle, aMode) {
-    _mode = aMode;
-  },
-  appendFilters: function(aFilterMask) { },
-  appendFilter: function(aTitle, aFilter) { },
-  defaultString: "",
-  defaultExtension: "",
-  filterIndex: 0,
-  displayDirectory: null,
-  get file() {
-    return _returnFile;
-  },
-  get fileURL() {
-    throw Cr.NS_ERROR_NOT_IMPLEMENTED;
-  },
-  get files() {
-    throw Cr.NS_ERROR_NOT_IMPLEMENTED;
-  },
-  show: function() {
-    return _returnValue;
-  }
-};
-var mockFilePickerFactory = {
-  registrar: Components.manager.QueryInterface(Ci.nsIComponentRegistrar),
-  contractID: "@mozilla.org/filepicker;1",
-  classID: Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator).generateUUID(),
-
-  register: function() {
-    this.registrar.registerFactory(this.classID, "", this.contractID, this);
-  },
-
-  unregister: function() {
-    this.registrar.unregisterFactory(this.classID, this);
-  },
-
-  // nsIFactory
-  createInstance: function(aOuter, aIID) {
-    if (aOuter) {
-      throw Components.results.NS_ERROR_NO_AGGREGATION;
-    }
-    return new MockFilePicker().QueryInterface(aIID);
-  },
-
-  lockFactory: function(aLock) {
-    throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
-  },
-
-  QueryInterface: XPCOMUtils.generateQI([
-    Ci.nsIFactory
-  ])
-};