Bug 712518 - Improve MockFilePicker.jsm; r=jmaher
authorGeoff Lankow <geoff@darktrojan.net>
Fri, 23 Dec 2011 11:10:52 +1300
changeset 83394 e20ed47b03f26c0e06a5698cb080a75c4e4fd008
parent 83393 b58836d3fa78b07e02f79a2d5f6f386d1f130415
child 83395 14a16133c0c2f93d1b390784860461dcecfad810
push id4383
push usergeoff@darktrojan.net
push dateTue, 27 Dec 2011 12:27:46 +0000
treeherdermozilla-inbound@e20ed47b03f2 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersjmaher
bugs712518
milestone12.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 712518 - Improve MockFilePicker.jsm; 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/test_bug36619.html
layout/forms/test/test_bug377624.html
layout/forms/test/test_bug536567.html
testing/mochitest/MockFilePicker.jsm
toolkit/content/tests/browser/browser_save_resend_postdata.js
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,13 +1,13 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 var MockFilePicker = SpecialPowers.MockFilePicker;
-MockFilePicker.reset();
+MockFilePicker.init();
 
 /**
  * TestCase for bug 564387
  * <https://bugzilla.mozilla.org/show_bug.cgi?id=564387>
  */
 function test() {
   waitForExplicitFinish();
   var fileName;
@@ -49,17 +49,17 @@ function test() {
       MockFilePicker.filterIndex = 1; // kSaveAsType_URL
     };
 
     mockTransferCallback = onTransferComplete;
     mockTransferRegisterer.register();
 
     registerCleanupFunction(function () {
       mockTransferRegisterer.unregister();
-      MockFilePicker.reset();
+      MockFilePicker.cleanup();
       destDir.remove(true);
     });
 
     // Select "Save Video As" option from context menu
     var saveVideoCommand = document.getElementById("context-savevideo");
     saveVideoCommand.doCommand();
 
     event.target.hidePopup();
--- a/content/html/content/test/test_bug500885.html
+++ b/content/html/content/test/test_bug500885.html
@@ -13,17 +13,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 <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">
 
 var MockFilePicker = SpecialPowers.MockFilePicker;
-MockFilePicker.reset();
+MockFilePicker.init();
 MockFilePicker.returnValue = MockFilePicker.returnOK;
 
 function test() {
   // SpecialPowers.DOMWindowUtils doesn't appear to fire mouseEvents correctly
   var wu = SpecialPowers.getDOMWindowUtils(window);
 
   try {
     var domActivateEvents;
@@ -42,17 +42,20 @@ function test() {
     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 fire 1 DOMActivate event");
 
   } finally {
-    SimpleTest.executeSoon(SimpleTest.finish);
+    SimpleTest.executeSoon(function() {
+      MockFilePicker.cleanup();
+      SimpleTest.finish();
+    });
   }
 }
 
 SimpleTest.waitForExplicitFinish();
 SimpleTest.waitForFocus(test);
 
 </script>
 </body>
--- a/content/html/content/test/test_bug592802.html
+++ b/content/html/content/test/test_bug592802.html
@@ -21,33 +21,34 @@ https://bugzilla.mozilla.org/show_bug.cg
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 592802 **/
 
 SimpleTest.waitForExplicitFinish();
 
 var MockFilePicker = SpecialPowers.MockFilePicker;
-MockFilePicker.reset();
+MockFilePicker.init();
 
 var testData = [
 /* visibility | display | multiple */
   [ "",       "",     false ],
   [ "hidden", "",     false ],
   [ "",       "none", false ],
   [ "",       "",     true ],
   [ "hidden", "",     true ],
   [ "",       "none", true ],
 ];
 
 var testCounter = 0;
 var testNb = testData.length;
 
 function finished()
 {
+  MockFilePicker.cleanup();
   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');
--- a/layout/forms/test/test_bug36619.html
+++ b/layout/forms/test/test_bug36619.html
@@ -19,17 +19,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 36619 **/
 
 SimpleTest.waitForExplicitFinish();
 
 var MockFilePicker = SpecialPowers.MockFilePicker;
-MockFilePicker.reset();
+MockFilePicker.init();
 
 // enable popups the first time
 SpecialPowers.pushPrefEnv({'set': [
   ["dom.disable_open_during_load", true],
   ["privacy.popups.showBrowserMessage", false]
 ]}, function() {
   SimpleTest.waitForFocus(function() {
 
@@ -40,17 +40,17 @@ SpecialPowers.pushPrefEnv({'set': [
     SimpleTest.executeSoon(function() {
       ok(MockFilePicker.shown, "File picker show method should have been called");
       MockFilePicker.reset();
 
       // 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();
+        MockFilePicker.cleanup();
 
         SimpleTest.finish();
       });
     });
   });
 });
 
 </script>
--- a/layout/forms/test/test_bug377624.html
+++ b/layout/forms/test/test_bug377624.html
@@ -28,17 +28,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 377624 **/
 
 SimpleTest.waitForExplicitFinish();
 
 var MockFilePicker = SpecialPowers.MockFilePicker;
-MockFilePicker.reset();
+MockFilePicker.init();
 
 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],
@@ -83,17 +83,17 @@ function runTests() {
          "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");
 
       if (++currentTest == testData.length) {
-        MockFilePicker.reset();
+        MockFilePicker.cleanup();
         SimpleTest.finish();
       } else {
         launchNextTest();
       }
     });
   };
 
   launchNextTest();
--- a/layout/forms/test/test_bug536567.html
+++ b/layout/forms/test/test_bug536567.html
@@ -19,17 +19,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 /** 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();
+MockFilePicker.init();
 
 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);
 }
@@ -129,17 +129,17 @@ function runTest() {
 }
 
 function endTest() {
     prefSvc.clearUserPref("browser.privatebrowsing.keep_current_session");
     for(var i = 0; i < dirs.length - 1; i++) {
       dirs[i].remove(true);
     }
 
-    MockFilePicker.reset();
+    MockFilePicker.cleanup();
     SimpleTest.finish();
 }
 
 MockFilePicker.showCallback = function(filepicker) {
   var test = tests[testIndex];
   var returned = -1;
   for (var i = 0; i < dirs.length; i++) {
     if (dirs[i].path == MockFilePicker.displayDirectory.path) {
--- a/testing/mochitest/MockFilePicker.jsm
+++ b/testing/mochitest/MockFilePicker.jsm
@@ -1,49 +1,61 @@
 /* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1
+ * 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 Mochitest Reusable Mock File Picker.
+ * The Original Code is 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):
  *
+ * 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 ***** */
 
 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 = {
+var oldClassID, oldFactory;
+var newClassID = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator).generateUUID();
+var newFactory = {
   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;
   },
@@ -61,28 +73,44 @@ var MockFilePicker = {
   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,
 
+  init: function() {
+    this.reset();
+    if (!registrar.isCIDRegistered(newClassID)) {
+      oldClassID = registrar.contractIDToCID(CONTRACT_ID);
+      oldFactory = Cm.getClassObject(Cc[CONTRACT_ID], Ci.nsIFactory);
+      registrar.unregisterFactory(oldClassID, oldFactory);
+      registrar.registerFactory(newClassID, "", CONTRACT_ID, newFactory);
+    }
+  },
+  
   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);
+  },
+  
+  cleanup: function() {
+    this.reset();
+    if (oldFactory) {
+      registrar.unregisterFactory(newClassID, newFactory);
+      registrar.registerFactory(oldClassID, "", CONTRACT_ID, oldFactory);
+    }
   },
 
   useAnyFile: function() {
     var file = FileUtils.getFile("TmpD", ["testfile"]);
     file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0644);
     this.returnFiles = [file];
   }
 };
@@ -126,13 +154,16 @@ MockFilePickerInstance.prototype = {
       getNext: function() {
         return MockFilePicker.returnFiles[this.index++];
       }
     };
   },
   show: function() {
     MockFilePicker.displayDirectory = this.displayDirectory;
     MockFilePicker.shown = true;
-    if (typeof MockFilePicker.showCallback == "function")
-      MockFilePicker.showCallback(this);
+    if (typeof MockFilePicker.showCallback == "function") {
+      var returnValue = MockFilePicker.showCallback(this);
+      if (typeof returnValue != "undefined")
+        return returnValue;
+    }
     return MockFilePicker.returnValue;
   }
 };
--- a/toolkit/content/tests/browser/browser_save_resend_postdata.js
+++ b/toolkit/content/tests/browser/browser_save_resend_postdata.js
@@ -30,17 +30,17 @@
  * 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();
+MockFilePicker.init();
 
 /**
  * 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
@@ -95,17 +95,17 @@ function test() {
       MockFilePicker.filterIndex = 1; // kSaveAsType_URL
     };
 
     mockTransferCallback = onTransferComplete;
     mockTransferRegisterer.register();
 
     registerCleanupFunction(function () {
       mockTransferRegisterer.unregister();
-      MockFilePicker.reset();
+      MockFilePicker.cleanup();
       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,
--- a/toolkit/mozapps/downloads/tests/unit/test_privatebrowsing_downloadLastDir.js
+++ b/toolkit/mozapps/downloads/tests/unit/test_privatebrowsing_downloadLastDir.js
@@ -52,17 +52,17 @@ let context = {
   getInterface: XPCOMUtils.generateQI([Ci.nsIDOMWindow])
 };
 
 let launcher = {
   source: Services.io.newURI("http://test1.com/file", null, null)
 };
 
 Cu.import("resource://test/MockFilePicker.jsm");
-MockFilePicker.reset();
+MockFilePicker.init();
 MockFilePicker.returnValue = Ci.nsIFilePicker.returnOK;
 
 function run_test()
 {
   let pb;
   try {
     pb = Cc["@mozilla.org/privatebrowsing;1"].
          getService(Ci.nsIPrivateBrowsingService);
@@ -138,10 +138,10 @@ function run_test()
   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));
 
-  MockFilePicker.reset();
+  MockFilePicker.cleanup();
 }
--- a/toolkit/mozapps/extensions/test/browser/browser_bug567127.js
+++ b/toolkit/mozapps/extensions/test/browser/browser_bug567127.js
@@ -1,16 +1,16 @@
 /* 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();
+MockFilePicker.init();
 
 var gManagerWindow;
 var gSawInstallNotification = false;
 
 // 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) {
@@ -107,17 +107,17 @@ function test() {
     gManagerWindow = aWindow;
     run_next_test();
   });
 }
 
 function end_test() {
   is(gSawInstallNotification, true, "Should have seen addon-install-started notification.");
 
-  MockFilePicker.reset();
+  MockFilePicker.cleanup();
   close_manager(gManagerWindow, function() {
     finish();
   });
 }
 
 
 add_test(function() {
   var filePaths = [
--- a/toolkit/mozapps/extensions/test/browser/browser_inlinesettings.js
+++ b/toolkit/mozapps/extensions/test/browser/browser_inlinesettings.js
@@ -6,17 +6,17 @@
 
 var gManagerWindow;
 var gCategoryUtilities;
 var gProvider;
 
 const SETTINGS_ROWS = 8;
 
 var MockFilePicker = SpecialPowers.MockFilePicker;
-MockFilePicker.reset();
+MockFilePicker.init();
 
 var observer = {
   lastData: null,
   observe: function(aSubject, aTopic, aData) {
     if (aTopic == "addon-options-displayed") {
       this.lastData = aData;
       // Test if the binding has applied before the observers are notified. We test the second setting here,
       // because the code operates on the first setting and we want to check it applies to all.
@@ -86,17 +86,17 @@ 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();
+  MockFilePicker.cleanup();
 
   close_manager(gManagerWindow, function() {
     AddonManager.getAddonByID("inlinesettings1@tests.mozilla.org", function(aAddon) {
       aAddon.uninstall();
       finish();
     });
   });
 }