Bug 1018300 - Convert test_pop3MoveFilter.js to use Promises. r=rkent
authorSuyash Agarwal <syshagarwal@gmail.com>
Tue, 10 Jun 2014 21:12:00 -0400
changeset 16330 1a9fcf6700ebab6d45c9a41dcbbeb1ff6579dbcf
parent 16329 935a121a00df9146fc1ea276ff2129d4298b4c58
child 16331 791d5276e5cbac9f528c8291907482cf72f9835d
push id10205
push userryanvm@gmail.com
push dateThu, 12 Jun 2014 12:30:08 +0000
treeherdercomm-central@4dc50f495b53 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersrkent
bugs1018300
Bug 1018300 - Convert test_pop3MoveFilter.js to use Promises. r=rkent
mailnews/local/test/unit/test_pop3MoveFilter.js
mailnews/test/resources/PromiseTestUtils.jsm
--- a/mailnews/local/test/unit/test_pop3MoveFilter.js
+++ b/mailnews/local/test/unit/test_pop3MoveFilter.js
@@ -2,105 +2,96 @@
  * This file tests that a pop3 move filter doesn't leave the
  * original message in the inbox.
  *
  * Original author: David Bienvenu <dbienvenu@mozilla.com>
  */
 
 
 load("../../../resources/POP3pump.js");
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
 Components.utils.import("resource:///modules/mailServices.js");
 Components.utils.import("resource://gre/modules/Services.jsm");
+Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
+Components.utils.import("resource://testing-common/mailnews/PromiseTestUtils.jsm");
+
 const gFiles = ["../../../data/bugmail10", "../../../data/bugmail11"];
 
 // make sure limiting download size doesn't causes issues with move filters.
 Services.prefs.setBoolPref("mail.server.default.limit_offline_message_size", true);
 Services.prefs.setBoolPref("mail.server.default.leave_on_server", true);
 
 const bugmail10_preview = 'Do not reply to this email. You can add comments to this bug at https://bugzilla.mozilla.org/show_bug.cgi?id=436880 -- Configure bugmail: https://bugzilla.mozilla.org/userprefs.cgi?tab=email ------- You are receiving this mail because: -----';
 const bugmail11_preview = 'Bugzilla has received a request to create a user account using your email address (example@example.org). To confirm that you want to create an account using that email address, visit the following link: https://bugzilla.mozilla.org/token.cgi?t=xxx';
 
 var gMoveFolder;
 var gFilter; // the test filter
 var gFilterList;
-var gCurTestNum = 1;
 const gTestArray =
 [
   function createFilters() {
     gFilterList = gPOP3Pump.fakeServer.getFilterList(null);
     gFilter = gFilterList.createFilter("MoveAll");
     let searchTerm = gFilter.createTerm();
     searchTerm.matchAll = true;
     gFilter.appendTerm(searchTerm);
     let moveAction = gFilter.createAction();
     moveAction.type = Ci.nsMsgFilterAction.MoveToFolder;
     moveAction.targetFolderUri = gMoveFolder.URI;
     gFilter.appendAction(moveAction);
     gFilter.enabled = true;
     gFilter.filterType = Ci.nsMsgFilterType.InboxRule;
     gFilterList.insertFilterAt(0, gFilter);
-    ++gCurTestNum;
-    doTest();
   },
   // just get a message into the local folder
-  function getLocalMessages1() {
+  function *getLocalMessages1() {
     gPOP3Pump.files = gFiles;
-    gPOP3Pump.onDone = doTest;
-    ++gCurTestNum;
-    gPOP3Pump.run();
+    yield gPOP3Pump.run();
   },
-  function verifyFolders2() {
+  function *verifyFolders2() {
     do_check_eq(folderCount(gMoveFolder), 2);
     // the local inbox folder should now be empty, since we moved incoming mail.
     do_check_eq(folderCount(localAccountUtils.inboxFolder), 0);
 
     // invalidate the inbox summary file, to be sure that we really moved
     // the mail.
     localAccountUtils.inboxFolder.msgDatabase.summaryValid = false;
     localAccountUtils.inboxFolder.msgDatabase = null;
     localAccountUtils.inboxFolder.ForceDBClosed();
+    let promiseUrlListener = new PromiseTestUtils.PromiseUrlListener();
     try {
-      localAccountUtils.inboxFolder.getDatabaseWithReparse(ParseListener, null);
-    } catch (ex) {
+      localAccountUtils.inboxFolder
+                       .getDatabaseWithReparse(promiseUrlListener, null);
+    } catch(ex) {
+      yield promiseUrlListener.promise;
       do_check_true(ex.result == Cr.NS_ERROR_NOT_INITIALIZED);
+      return;
     }
+    // This statement isn't reached since the error is thrown.
+    do_check_true(false);
   },
   function verifyMessages() {
     let hdrs = [];
     let keys = [];
-    let asyncResults = new Object;
     let enumerator = gMoveFolder.msgDatabase.EnumerateMessages();
     while (enumerator.hasMoreElements())
     {
       let hdr = enumerator.getNext().QueryInterface(Ci.nsIMsgDBHdr);
       keys.push(hdr.messageKey);
       hdrs.push(hdr);
     }
-    gMoveFolder.fetchMsgPreviewText(keys, keys.length, false, null, asyncResults);
+    do_check_false(gMoveFolder.fetchMsgPreviewText(keys, keys.length, false,
+                                                   null));
     do_check_eq(hdrs[0].getStringProperty('preview'), bugmail10_preview);
     do_check_eq(hdrs[1].getStringProperty('preview'), bugmail11_preview);
-    ++gCurTestNum;
-    doTest();
+  },
+  function endTest() {
+    gPOP3Pump = null;
   },
 ];
 
-var ParseListener =
-{
-  OnStartRunningUrl: function (aUrl) {
-  },
-  OnStopRunningUrl: function (aUrl, aExitCode) {
-    do_check_eq(aExitCode, 0);
-    do_check_true(localAccountUtils.inboxFolder.msgDatabase.summaryValid);
-    do_check_eq(folderCount(localAccountUtils.inboxFolder), 0);
-    ++gCurTestNum;
-    doTest();
-  }
-};
-
 function folderCount(folder)
 {
   let enumerator = folder.msgDatabase.EnumerateMessages();
   let count = 0;
   while (enumerator.hasMoreElements())
   {
     count++;
     let hdr = enumerator.getNext();
@@ -112,72 +103,11 @@ function run_test()
 {
   // Make sure we're not quarantining messages
   Services.prefs.setBoolPref("mailnews.downloadToTempFile", false);
   if (!localAccountUtils.inboxFolder)
     localAccountUtils.loadLocalMailAccount();
 
   gMoveFolder = localAccountUtils.rootFolder.createLocalSubfolder("MoveFolder");
 
-  MailServices.mailSession.AddFolderListener(FolderListener,
-                                             Ci.nsIFolderListener.event |
-                                               Ci.nsIFolderListener.added |
-                                               Ci.nsIFolderListener.removed);
-
-  // "Master" do_test_pending(), paired with a do_test_finished() at the end of
-  // all the operations.
-  do_test_pending();
-
-  //start first test
-  doTest();
-}
-
-function doTest()
-{
-  var test = gCurTestNum;
-  if (test <= gTestArray.length)
-  {
-    var testFn = gTestArray[test-1];
-    dump("Doing test " + test + " " + testFn.name + "\n");
-
-    try {
-      testFn();
-    } catch(ex) {
-      do_throw ('TEST FAILED ' + ex);
-    }
-  }
-  else
-    do_timeout(1000, endTest);
+  gTestArray.forEach(add_task);
+  run_next_test();
 }
-
-// nsIFolderListener implementation
-var FolderListener = {
-  OnItemAdded: function OnItemAdded(aParentItem, aItem) {
-    this._showEvent(aParentItem, "OnItemAdded");
-  },
-  OnItemRemoved: function OnItemRemoved(aParentItem, aItem) {
-    this._showEvent(aParentItem, "OnItemRemoved");
-    // continue test, as all tests remove a message during the move
-    do_timeout(0, doTest);
-  },
-  OnItemEvent: function OnItemEvent(aEventFolder, aEvent) {
-    this._showEvent(aEventFolder, aEvent.toString())
-  },
-  _showEvent: function showEvent(aFolder, aEventString) {
-        dump("received folder event " + aEventString +
-         " folder " + aFolder.name +
-         "\n");
-  }
-};
-
-function endTest()
-{
-  // Cleanup, null out everything, close all cached connections and stop the
-  // server
-  dump("Exiting mail tests\n");
-  let thread = gThreadManager.currentThread;
-  while (thread.hasPendingEvents())
-    thread.processNextEvent(true);
-  gPOP3Pump = null;
-
-  do_test_finished(); // for the one in run_test()
-}
-
--- a/mailnews/test/resources/PromiseTestUtils.jsm
+++ b/mailnews/test/resources/PromiseTestUtils.jsm
@@ -24,35 +24,38 @@ Cu.import("resource://gre/modules/Promis
  * @param [aWrapped] The nsIUrlListener to pass all notifications through to.
  *     This gets called prior to the callback (or async resumption).
  */
 
 var PromiseTestUtils = {};
 
 PromiseTestUtils.PromiseUrlListener = function(aWrapped) {
   this.wrapped = aWrapped ? aWrapped.QueryInterface(Ci.nsIUrlListener) : null;
-  this._deferred = Promise.defer();
+  this._promise = new Promise((resolve, reject) => {
+    this._resolve = resolve;
+    this._reject = reject;
+  });
 };
 
 PromiseTestUtils.PromiseUrlListener.prototype = {
   QueryInterface:   XPCOMUtils.generateQI([Ci.nsIUrlListener]),
 
   OnStartRunningUrl: function(aUrl) {
     if (this.wrapped)
       this.wrapped.OnStartRunningUrl(aUrl);
   },
   OnStopRunningUrl: function(aUrl, aExitCode) {
     if (this.wrapped)
       this.wrapped.OnStopRunningUrl(aUrl, aExitCode);
     if (aExitCode == Cr.NS_OK)
-      this._deferred.resolve();
+      this._resolve();
     else
-      this._deferred.reject(aExitCode);
+      this._reject(aExitCode);
   },
-  get promise() { return this._deferred.promise; },
+  get promise() { return this._promise; },
 };
 
 /**
  * Stream listener that can wrap another listener and trigger a callback.
  *
  * @param [aWrapped] The nsIStreamListener to pass all notifications through to.
  *     This gets called prior to the callback (or async resumption).
  */