Bug 1249259 - Update Firefox puppeteer for deprecated places API. r=mak
authorHenrik Skupin <mail@hskupin.info>
Tue, 08 Mar 2016 23:36:38 +0100
changeset 291146 02ad453e3bfc684965c54defd01f310b8f7b93cf
parent 291145 f1cfe4b34e8da1b44551bff44827812a43d2864c
child 291147 69de5a5abae7d05b87dd4a36ee120349f6483683
push id19656
push usergwagner@mozilla.com
push dateMon, 04 Apr 2016 13:43:23 +0000
treeherderb2g-inbound@e99061fde28a [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmak
bugs1249259
milestone48.0a1
Bug 1249259 - Update Firefox puppeteer for deprecated places API. r=mak MozReview-Commit-ID: HXLTybsEb4R This patch exchanges all old and deprecated API calls with the ones in PlacesUtils. As a side-effect we can also condense some other code by using promises.
testing/puppeteer/firefox/firefox_puppeteer/api/places.py
--- a/testing/puppeteer/firefox/firefox_puppeteer/api/places.py
+++ b/testing/puppeteer/firefox/firefox_puppeteer/api/places.py
@@ -1,178 +1,145 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this file,
 # You can obtain one at http://mozilla.org/MPL/2.0/.
 
 from collections import namedtuple
 from time import sleep
 
-from marionette_driver.errors import MarionetteException, TimeoutException
+from marionette_driver.errors import MarionetteException
 
 from firefox_puppeteer.base import BaseLib
 
 
 class Places(BaseLib):
     """Low-level access to several bookmark and history related actions."""
 
     BookmarkFolders = namedtuple('bookmark_folders',
-                                 ['root', 'menu', 'toolbar', 'tags', 'unfiled'])
-    bookmark_folders = BookmarkFolders(1, 2, 3, 4, 5)
+                                 ['root', 'menu', 'toolbar', 'unfiled'])
+    bookmark_folders = BookmarkFolders('root________', 'menu________',
+                                       'toolbar_____', 'unfiled_____')
 
     # Bookmark related helpers #
 
     def is_bookmarked(self, url):
-        """Checks if the given URL is bookmarked.
+        """Check if the given URL is bookmarked.
 
         :param url: The URL to Check
 
         :returns: True, if the URL is a bookmark
         """
-        return self.marionette.execute_script("""
-          let url = arguments[0];
+        return self.marionette.execute_async_script("""
+          Components.utils.import("resource://gre/modules/PlacesUtils.jsm");
 
-          let bs = Components.classes["@mozilla.org/browser/nav-bookmarks-service;1"]
-                   .getService(Components.interfaces.nsINavBookmarksService);
-          let ios = Components.classes["@mozilla.org/network/io-service;1"]
-                    .getService(Components.interfaces.nsIIOService);
-
-          let uri = ios.newURI(url, null, null);
-          let results = bs.getBookmarkIdsForURI(uri, {});
-
-          return results.length == 1;
+          PlacesUtils.bookmarks.fetch({url: arguments[0]}).then(bm => {
+            marionetteScriptFinished(bm != null);
+          });
         """, script_args=[url])
 
     def get_folder_ids_for_url(self, url):
-        """Retrieves the folder ids where the given URL has been bookmarked in.
-
-         :param url: URL of the bookmark
+        """Retrieve the folder ids where the given URL has been bookmarked in.
 
-         :returns: List of folder ids
-        """
-        return self.marionette.execute_script("""
-          let url = arguments[0];
+        :param url: URL of the bookmark
 
-          let bs = Components.classes["@mozilla.org/browser/nav-bookmarks-service;1"]
-                   .getService(Components.interfaces.nsINavBookmarksService);
-          let ios = Components.classes["@mozilla.org/network/io-service;1"]
-                    .getService(Components.interfaces.nsIIOService);
+        :returns: List of folder ids
+        """
+        return self.marionette.execute_async_script("""
+          Components.utils.import("resource://gre/modules/PlacesUtils.jsm");
 
-          let bookmarkIds = bs.getBookmarkIdsForURI(ios.newURI(url, null, null), {});
-          let folderIds = [];
+          let folderGuids = []
 
-          for (let i = 0; i < bookmarkIds.length; i++) {
-            folderIds.push(bs.getFolderIdForItem(bookmarkIds[i]));
+          function onResult(bm) {
+            folderGuids.push(bm.parentGuid);
           }
 
-          return folderIds;
+          PlacesUtils.bookmarks.fetch({url: arguments[0]}, onResult).then(() => {
+            marionetteScriptFinished(folderGuids);
+          });
         """, script_args=[url])
 
     def is_bookmark_star_button_ready(self):
-        """Checks if the status of the star-button is not updating.
+        """Check if the status of the star-button is not updating.
 
         :returns: True, if the button is ready
         """
         return self.marionette.execute_script("""
           let button = window.BookmarkingUI;
 
           return button.status !== button.STATUS_UPDATING;
         """)
 
     def restore_default_bookmarks(self):
-        """Restores the default bookmarks for the current profile."""
+        """Restore the default bookmarks for the current profile."""
         retval = self.marionette.execute_async_script("""
           Components.utils.import("resource://gre/modules/BookmarkHTMLUtils.jsm");
-          Components.utils.import("resource://gre/modules/Services.jsm");
 
           // Default bookmarks.html file is stored inside omni.jar,
           // so get it via a resource URI
           let defaultBookmarks = 'chrome://browser/locale/bookmarks.html';
 
-          let observer = {
-            observe: function (aSubject, aTopic, aData) {
-              Services.obs.removeObserver(observer, "bookmarks-restore-success");
-              Services.obs.removeObserver(observer, "bookmarks-restore-failed");
-
-              marionetteScriptFinished(aTopic == "bookmarks-restore-success");
-            }
-          };
-
           // Trigger the import of the default bookmarks
-          Services.obs.addObserver(observer, "bookmarks-restore-success", false);
-          Services.obs.addObserver(observer, "bookmarks-restore-failed", false);
-          BookmarkHTMLUtils.importFromURL(defaultBookmarks, true);
+          BookmarkHTMLUtils.importFromURL(defaultBookmarks, true)
+                           .then(() => marionetteScriptFinished(true))
+                           .catch(() => marionetteScriptFinished(false));
         """, script_timeout=10000)
 
         if not retval:
             raise MarionetteException("Restore Default Bookmarks failed")
 
     # Browser history related helpers #
 
     def get_all_urls_in_history(self):
+        """Retrieve any URLs which have been stored in the history."""
         return self.marionette.execute_script("""
-          let hs = Cc["@mozilla.org/browser/nav-history-service;1"]
-                   .getService(Ci.nsINavHistoryService);
+          Components.utils.import("resource://gre/modules/PlacesUtils.jsm");
+
+          let options = PlacesUtils.history.getNewQueryOptions();
+          let root = PlacesUtils.history.executeQuery(
+                       PlacesUtils.history.getNewQuery(), options).root;
           let urls = [];
 
-          let options = hs.getNewQueryOptions();
-          options.resultType = options.RESULTS_AS_URI;
-
-          let root = hs.executeQuery(hs.getNewQuery(), options).root
           root.containerOpen = true;
           for (let i = 0; i < root.childCount; i++) {
             urls.push(root.getChild(i).uri)
           }
           root.containerOpen = false;
 
           return urls;
         """)
 
     def remove_all_history(self):
-        """Removes all history items."""
-        with self.marionette.using_context('chrome'):
-            try:
-                self.marionette.execute_async_script("""
-                    Components.utils.import("resource://gre/modules/Services.jsm");
-
-                    let hs = Components.classes["@mozilla.org/browser/nav-history-service;1"]
-                             .getService(Components.interfaces.nsIBrowserHistory);
-
-                    let observer = {
-                      observe: function (aSubject, aTopic, aData) {
-                        Services.obs.removeObserver(observer, 'places-expiration-finished');
+        """Remove all history items."""
+        retval = self.marionette.execute_async_script("""
+            Components.utils.import("resource://gre/modules/PlacesUtils.jsm");
 
-                        marionetteScriptFinished(true);
-                      }
-                    };
+            PlacesUtils.history.clear()
+                       .then(() => marionetteScriptFinished(true))
+                       .catch(() => marionetteScriptFinished(false));
+        """, script_timeout=10000)
 
-                    // Remove the pages, then block until we're done or until timeout is reached
-                    Services.obs.addObserver(observer, 'places-expiration-finished', false);
-
-                    hs.removeAllPages();
-                """, script_timeout=10000)
-            except TimeoutException:
-                # TODO: In case of a timeout clean-up the registered topic
-                pass
+        if not retval:
+            raise MarionetteException("Removing all history failed")
 
     def wait_for_visited(self, urls, callback):
-        """Waits until all passed-in urls have been visited.
+        """Wait until all passed-in urls have been visited.
 
         :param urls: List of URLs which need to be visited and indexed
 
         :param callback: Method to execute which triggers loading of the URLs
         """
         # Bug 1121691: Needs observer handling support with callback first
         # Until then we have to wait about 4s to ensure the page has been indexed
         callback()
         sleep(4)
 
     # Plugin related helpers #
 
     def clear_plugin_data(self):
-        """Clears any kind of locally stored data from plugins."""
+        """Clear any kind of locally stored data from plugins."""
         self.marionette.execute_script("""
           let host = Components.classes["@mozilla.org/plugin/host;1"]
                      .getService(Components.interfaces.nsIPluginHost);
           let tags = host.getPluginTags();
 
           tags.forEach(aTag => {
             try {
               host.clearSiteData(aTag, null, Components.interfaces.nsIPluginHost