Bug 1348223 - Part 1 - Add SiteDataTestUtils.jsm. r=mak draft
authorJohann Hofmann <jhofmann@mozilla.com>
Thu, 22 Mar 2018 17:08:20 +0100
changeset 778137 e515a1a12f6a665f6a4b96deec73790540755189
parent 777984 110f32790d38a258cab722064aae40736478ef51
child 778138 2d48740a023f63a2ec7af06f4510ab9cbb91fc66
push id105397
push userjhofmann@mozilla.com
push dateThu, 05 Apr 2018 21:09:18 +0000
reviewersmak
bugs1348223
milestone61.0a1
Bug 1348223 - Part 1 - Add SiteDataTestUtils.jsm. r=mak This commit adds a helper module for doing common tasks related to site data, such as adding dummy data and getting usage. There are many places that would potentially need to be cleaned up to use this module instead, but I consider that work (and the likely try failure fallout) out of scope for this bug. MozReview-Commit-ID: 5eMDgHhClsO
browser/base/content/test/sanitize/SiteDataTestUtils.jsm
browser/base/moz.build
browser/components/preferences/in-content/tests/siteData/browser_clearSiteData.js
browser/components/preferences/in-content/tests/siteData/head.js
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/sanitize/SiteDataTestUtils.jsm
@@ -0,0 +1,78 @@
+"use strict";
+
+var EXPORTED_SYMBOLS = [
+  "SiteDataTestUtils",
+];
+
+ChromeUtils.import("resource://gre/modules/Services.jsm");
+const {Sanitizer} = ChromeUtils.import("resource:///modules/Sanitizer.jsm", {});
+
+/**
+ * This module assists with tasks around testing functionality that shows
+ * or clears site data.
+ *
+ * Please note that you will have to clean up changes made manually, for
+ * example using SiteDataTestUtils.clear().
+ */
+var SiteDataTestUtils = {
+
+  /**
+   * Adds a new entry to a dummy indexedDB database for the specified origin.
+   *
+   * @param {String} origin - the origin of the site to add test data for
+   *
+   * @returns a Promise that resolves when the data was added successfully.
+   */
+  addToIndexedDB(origin) {
+    return new Promise(resolve => {
+      let uri = Services.io.newURI(origin);
+      let principal = Services.scriptSecurityManager.createCodebasePrincipal(uri, {});
+      let request = indexedDB.openForPrincipal(principal, "TestDatabase", 1);
+      request.onupgradeneeded = function(e) {
+        let db = e.target.result;
+        db.createObjectStore("TestStore", { keyPath: "id" });
+      };
+      request.onsuccess = function(e) {
+        let db = e.target.result;
+        let tx = db.transaction("TestStore", "readwrite");
+        let store = tx.objectStore("TestStore");
+        tx.oncomplete = resolve;
+        store.put({ id: performance.now().toString(), description: "IndexedDB Test"});
+      };
+    });
+  },
+
+  /**
+   * Adds a new cookie for the specified origin, with the specified contents.
+   * The cookie will be valid for one day.
+   *
+   * @param {String} name - the cookie name
+   * @param {String} value - the cookie value
+   */
+  addToCookies(origin, name, value) {
+    let uri = Services.io.newURI(origin);
+    Services.cookies.add(uri.host, uri.pathQueryRef, name, value,
+      false, false, false, Date.now() + 24000 * 60 * 60);
+  },
+
+  /**
+   * Gets the current quota usage for the specified origin.
+   *
+   * @returns a Promise that resolves to an integer with the total
+   *          amount of disk usage by a given origin.
+   */
+  getQuotaUsage(origin) {
+    return new Promise(resolve => {
+      let uri = Services.io.newURI(origin);
+      let principal = Services.scriptSecurityManager.createCodebasePrincipal(uri, {});
+      Services.qms.getUsageForPrincipal(principal, request => resolve(request.result.usage));
+    });
+  },
+
+  /**
+   * Cleans up all site data.
+   */
+  clear() {
+    return Sanitizer.sanitize(["cookies", "cache", "siteSettings", "offlineApps"]);
+  },
+};
--- a/browser/base/moz.build
+++ b/browser/base/moz.build
@@ -16,16 +16,20 @@ with Files('content/docs/sslerrorreport/
 MOCHITEST_MANIFESTS += [
     'content/test/general/mochitest.ini',
 ]
 
 MOCHITEST_CHROME_MANIFESTS += [
     'content/test/chrome/chrome.ini',
 ]
 
+TESTING_JS_MODULES += [
+    'content/test/sanitize/SiteDataTestUtils.jsm',
+]
+
 BROWSER_CHROME_MANIFESTS += [
     'content/test/about/browser.ini',
     'content/test/alerts/browser.ini',
     'content/test/captivePortal/browser.ini',
     'content/test/contextMenu/browser.ini',
     'content/test/favicons/browser.ini',
     'content/test/forms/browser.ini',
     'content/test/general/browser.ini',
--- a/browser/components/preferences/in-content/tests/siteData/browser_clearSiteData.js
+++ b/browser/components/preferences/in-content/tests/siteData/browser_clearSiteData.js
@@ -25,17 +25,17 @@ async function testClearData(clearSiteDa
   // Register some service workers.
   await loadServiceWorkerTestPage(TEST_SERVICE_WORKER_URL);
   await promiseServiceWorkerRegisteredFor(TEST_SERVICE_WORKER_URL);
 
   await openPreferencesViaOpenPreferencesAPI("privacy", { leaveOpen: true });
 
   // Test the initial states.
   let cacheUsage = await SiteDataManager.getCacheSize();
-  let quotaUsage = await getQuotaUsage(TEST_QUOTA_USAGE_ORIGIN);
+  let quotaUsage = await SiteDataTestUtils.getQuotaUsage(TEST_QUOTA_USAGE_ORIGIN);
   let totalUsage = await SiteDataManager.getTotalUsage();
   Assert.greater(cacheUsage, 0, "The cache usage should not be 0");
   Assert.greater(quotaUsage, 0, "The quota usage should not be 0");
   Assert.greater(totalUsage, 0, "The total usage should not be 0");
 
   let initialSizeLabelValue = await ContentTask.spawn(gBrowser.selectedBrowser, null, async function() {
     let sizeLabel = content.document.getElementById("totalSiteDataSize");
     return sizeLabel.textContent;
@@ -122,17 +122,17 @@ async function testClearData(clearSiteDa
     await cookiesClearedPromise;
     await promiseServiceWorkersCleared();
 
     TestUtils.waitForCondition(async function() {
       let usage = await SiteDataManager.getTotalUsage();
       return usage == 0;
     }, "The total usage should be removed");
   } else {
-    quotaUsage = await getQuotaUsage(TEST_QUOTA_USAGE_ORIGIN);
+    quotaUsage = await SiteDataTestUtils.getQuotaUsage(TEST_QUOTA_USAGE_ORIGIN);
     totalUsage = await SiteDataManager.getTotalUsage();
     Assert.greater(quotaUsage, 0, "The quota usage should not be 0");
     Assert.greater(totalUsage, 0, "The total usage should not be 0");
   }
 
   if (clearCache || clearSiteData) {
     // Check that the size label in about:preferences updates after we cleared data.
     await ContentTask.spawn(gBrowser.selectedBrowser, {initialSizeLabelValue}, async function(opts) {
--- a/browser/components/preferences/in-content/tests/siteData/head.js
+++ b/browser/components/preferences/in-content/tests/siteData/head.js
@@ -12,16 +12,19 @@ const TEST_OFFLINE_URL = getRootDirector
 const TEST_SERVICE_WORKER_URL = getRootDirectory(gTestPath).replace("chrome://mochitests/content", TEST_OFFLINE_ORIGIN) + "/service_worker_test.html";
 
 const REMOVE_DIALOG_URL = "chrome://browser/content/preferences/siteDataRemoveSelected.xul";
 
 const { DownloadUtils } = ChromeUtils.import("resource://gre/modules/DownloadUtils.jsm", {});
 const { SiteDataManager } = ChromeUtils.import("resource:///modules/SiteDataManager.jsm", {});
 const { OfflineAppCacheHelper } = ChromeUtils.import("resource:///modules/offlineAppCache.jsm", {});
 
+ChromeUtils.defineModuleGetter(this, "SiteDataTestUtils",
+                               "resource://testing-common/SiteDataTestUtils.jsm");
+
 XPCOMUtils.defineLazyServiceGetter(this, "serviceWorkerManager", "@mozilla.org/serviceworkers/manager;1", "nsIServiceWorkerManager");
 
 function promiseSiteDataManagerSitesUpdated() {
   return TestUtils.topicObserved("sitedatamanager:sites-updated", () => true);
 }
 
 function is_hidden(aElement) {
   var style = aElement.ownerGlobal.getComputedStyle(aElement);
@@ -182,24 +185,16 @@ const mockSiteDataManager = {
   async unregister() {
     await this._SiteDataManager.removeAll();
     this.fakeSites = null;
     this._SiteDataManager._qms = this._originalQMS;
     this._SiteDataManager._removeQuotaUsage = this._originalRemoveQuotaUsage;
   }
 };
 
-function getQuotaUsage(origin) {
-  return new Promise(resolve => {
-    let uri = NetUtil.newURI(origin);
-    let principal = Services.scriptSecurityManager.createCodebasePrincipal(uri, {});
-    Services.qms.getUsageForPrincipal(principal, request => resolve(request.result.usage));
-  });
-}
-
 function promiseCookiesCleared() {
   return TestUtils.topicObserved("cookie-changed", (subj, data) => {
     return data === "cleared";
   });
 }
 
 async function loadServiceWorkerTestPage(url) {
   let tab = await BrowserTestUtils.openNewForegroundTab(gBrowser, url);