Bug 1460768 - Part 4 - Update tests draft
authorJohann Hofmann <jhofmann@mozilla.com>
Thu, 05 Jul 2018 23:42:02 +0200
changeset 814659 d4cc82e43588d7b3b632af8433b596caa9fa433e
parent 814658 dfb2de29e9d6e6360486729fa25c1bea9cc65808
push id115305
push userjhofmann@mozilla.com
push dateThu, 05 Jul 2018 21:44:52 +0000
bugs1460768
milestone62.0a1
Bug 1460768 - Part 4 - Update tests MozReview-Commit-ID: 1fPCAW13plZ
browser/base/content/test/sanitize/SiteDataTestUtils.jsm
browser/components/preferences/in-content/tests/siteData/browser_siteData.js
browser/components/preferences/in-content/tests/siteData/browser_siteData2.js
browser/components/preferences/in-content/tests/siteData/browser_siteData3.js
browser/components/preferences/in-content/tests/siteData/browser_siteData_multi_select.js
browser/components/preferences/in-content/tests/siteData/head.js
--- a/browser/base/content/test/sanitize/SiteDataTestUtils.jsm
+++ b/browser/base/content/test/sanitize/SiteDataTestUtils.jsm
@@ -4,70 +4,85 @@ var EXPORTED_SYMBOLS = [
   "SiteDataTestUtils",
 ];
 
 ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
 ChromeUtils.import("resource://gre/modules/Services.jsm");
 ChromeUtils.import("resource://testing-common/ContentTask.jsm");
 ChromeUtils.import("resource://testing-common/BrowserTestUtils.jsm");
 
-const {Sanitizer} = ChromeUtils.import("resource:///modules/Sanitizer.jsm", {});
-
 XPCOMUtils.defineLazyServiceGetter(this, "swm",
                                    "@mozilla.org/serviceworkers/manager;1",
                                    "nsIServiceWorkerManager");
 
+XPCOMUtils.defineLazyGlobalGetters(this, ["Blob"]);
+
 /**
  * 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.
+   * Makes an origin have persistent data storage.
+   *
+   * @param {String} origin - the origin of the site to give persistent storage
+   *
+   * @returns a Promise that resolves when storage was persisted
+   */
+  persist(origin, value = Services.perms.ALLOW_ACTION) {
+    return new Promise(resolve => {
+      let principal = Services.scriptSecurityManager.createCodebasePrincipalFromOrigin(origin);
+      Services.perms.addFromPrincipal(principal, "persistent-storage", value);
+      Services.qms.persist(principal).callback = () => resolve();
+    });
+  },
+
+  /**
+   * Adds a new blob entry to a dummy indexedDB database for the specified origin.
    *
    * @param {String} origin - the origin of the site to add test data for
-   * @param {String} name [optional] - the entry key
-   * @param {String} value [optional] - the entry value
+   * @param {Number} size [optional] - the size of the entry in bytes
    *
    * @returns a Promise that resolves when the data was added successfully.
    */
-  addToIndexedDB(origin, key = "foo", value = "bar") {
+  addToIndexedDB(origin, size = 1024) {
     return new Promise(resolve => {
-      let uri = Services.io.newURI(origin);
-      let principal = Services.scriptSecurityManager.createCodebasePrincipal(uri, {});
+      let principal = Services.scriptSecurityManager.createCodebasePrincipalFromOrigin(origin);
       let request = indexedDB.openForPrincipal(principal, "TestDatabase", 1);
       request.onupgradeneeded = function(e) {
         let db = e.target.result;
-        db.createObjectStore("TestStore", { keyPath: "id" });
+        db.createObjectStore("TestStore");
       };
       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: key, description: value});
+        let buffer = new ArrayBuffer(size);
+        let blob = new Blob([buffer]);
+        store.add(blob, Cu.now());
       };
     });
   },
 
   /**
    * Adds a new cookie for the specified origin, with the specified contents.
    * The cookie will be valid for one day.
    *
    * @param {String} origin - the origin of the site to add test data for
    * @param {String} name [optional] - the cookie name
    * @param {String} value [optional] - the cookie value
    */
   addToCookies(origin, name = "foo", value = "bar") {
-    let uri = Services.io.newURI(origin);
-    Services.cookies.add(uri.host, uri.pathQueryRef, name, value,
+    let principal = Services.scriptSecurityManager.createCodebasePrincipalFromOrigin(origin);
+    Services.cookies.add(principal.URI.host, principal.URI.pathQueryRef, name, value,
       false, false, false, Date.now() + 24000 * 60 * 60);
   },
 
   /**
    * Adds a new serviceworker with the specified path. Note that this
    * method will open a new tab at the domain of the SW path to that effect.
    *
    * @param {String} path - the path to the service worker to add.
@@ -113,21 +128,28 @@ var SiteDataTestUtils = {
   /**
    * 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, {});
+      let principal = Services.scriptSecurityManager.createCodebasePrincipalFromOrigin(origin);
       Services.qms.getUsageForPrincipal(principal, request => resolve(request.result.usage));
     });
   },
 
   /**
    * Cleans up all site data.
    */
   clear() {
-    return Sanitizer.sanitize(["cookies", "cache", "siteSettings", "offlineApps"]);
+    return new Promise(function(resolve) {
+      Services.clearData.deleteData(
+        Ci.nsIClearDataService.CLEAR_COOKIES |
+        Ci.nsIClearDataService.CLEAR_DOM_STORAGES |
+        Ci.nsIClearDataService.CLEAR_SECURITY_SETTINGS |
+        Ci.nsIClearDataService.CLEAR_PLUGIN_DATA |
+        Ci.nsIClearDataService.CLEAR_PERMISSIONS |
+        Ci.nsIClearDataService.CLEAR_ALL_CACHES, resolve);
+    });
   },
 };
--- a/browser/components/preferences/in-content/tests/siteData/browser_siteData.js
+++ b/browser/components/preferences/in-content/tests/siteData/browser_siteData.js
@@ -47,62 +47,16 @@ add_task(async function() {
     let request = Services.qms.clearStoragesForPrincipal(principal, null, true);
     request.callback = resolve;
   });
 
   await SiteDataManager.removeAll();
   BrowserTestUtils.removeTab(gBrowser.selectedTab);
 }).skip(); // Bug 1414751
 
-// Test buttons are disabled and loading message shown while updating sites
-add_task(async function() {
-  let updatedPromise = promiseSiteDataManagerSitesUpdated();
-  await openPreferencesViaOpenPreferencesAPI("privacy", { leaveOpen: true });
-  await updatedPromise;
-  let cacheSize = await SiteDataManager.getCacheSize();
-
-  let doc = gBrowser.selectedBrowser.contentDocument;
-  let clearBtn = doc.getElementById("clearSiteDataButton");
-  let settingsButton = doc.getElementById("siteDataSettings");
-  let totalSiteDataSizeLabel = doc.getElementById("totalSiteDataSize");
-  is(clearBtn.disabled, false, "Should enable clear button after sites updated");
-  is(settingsButton.disabled, false, "Should enable settings button after sites updated");
-  await SiteDataManager.getTotalUsage()
-                       .then(usage => {
-                         let [value, unit] = DownloadUtils.convertByteUnits(usage + cacheSize);
-                         Assert.deepEqual(doc.l10n.getAttributes(totalSiteDataSizeLabel), {
-                           id: "sitedata-total-size",
-                           args: {value, unit}
-                         }, "Should show the right total site data size");
-                       });
-
-  Services.obs.notifyObservers(null, "sitedatamanager:updating-sites");
-  is(clearBtn.disabled, true, "Should disable clear button while updating sites");
-  is(settingsButton.disabled, true, "Should disable settings button while updating sites");
-  Assert.deepEqual(doc.l10n.getAttributes(totalSiteDataSizeLabel), {
-    id: "sitedata-total-size-calculating",
-    args: null
-  }, "Should show the loading message while updating");
-
-  Services.obs.notifyObservers(null, "sitedatamanager:sites-updated");
-  is(clearBtn.disabled, false, "Should enable clear button after sites updated");
-  is(settingsButton.disabled, false, "Should enable settings button after sites updated");
-  cacheSize = await SiteDataManager.getCacheSize();
-  await SiteDataManager.getTotalUsage()
-                       .then(usage => {
-                         let [value, unit] = DownloadUtils.convertByteUnits(usage + cacheSize);
-                         Assert.deepEqual(doc.l10n.getAttributes(totalSiteDataSizeLabel), {
-                           id: "sitedata-total-size",
-                           args: {value, unit}
-                         }, "Should show the right total site data size");
-                       });
-
-  BrowserTestUtils.removeTab(gBrowser.selectedTab);
-});
-
 // Test clearing service wroker through the settings panel
 add_task(async function() {
   // Register a test service worker
   await loadServiceWorkerTestPage(TEST_SERVICE_WORKER_URL);
   await openPreferencesViaOpenPreferencesAPI("privacy", { leaveOpen: true });
   // Test the initial states
   await promiseServiceWorkerRegisteredFor(TEST_SERVICE_WORKER_URL);
   // Open the Site Data Settings panel and remove the site
--- a/browser/components/preferences/in-content/tests/siteData/browser_siteData2.js
+++ b/browser/components/preferences/in-content/tests/siteData/browser_siteData2.js
@@ -7,115 +7,112 @@ function assertAllSitesNotListed(win) {
   let sitesList = frameDoc.getElementById("sitesList");
   let sites = sitesList.getElementsByTagName("richlistitem");
   is(sites.length, 0, "Should not list all sites");
   is(removeBtn.disabled, true, "Should disable the removeSelected button");
   is(removeAllBtn.disabled, true, "Should disable the removeAllBtn button");
 }
 
 // Test selecting and removing all sites one by one
-add_task(async function() {
-  mockSiteDataManager.register(SiteDataManager, [
+add_task(async function test_selectRemove() {
+  let hosts = await addTestData([
     {
       usage: 1024,
       origin: "https://account.xyz.com",
       persisted: true
     },
     {
       usage: 1024,
       origin: "https://shopping.xyz.com",
-      persisted: false
     },
     {
       usage: 1024,
       origin: "http://cinema.bar.com",
       persisted: true
     },
     {
       usage: 1024,
       origin: "http://email.bar.com",
-      persisted: false
     },
   ]);
-  let fakeHosts = mockSiteDataManager.fakeSites.map(site => site.principal.URI.host);
 
-  let updatePromise = promiseSiteDataManagerSitesUpdated();
+  await SiteDataManager.refresh();
+
   await openPreferencesViaOpenPreferencesAPI("privacy", { leaveOpen: true });
-  await updatePromise;
   await openSiteDataSettingsDialog();
 
   let win = gBrowser.selectedBrowser.contentWindow;
   let doc = gBrowser.selectedBrowser.contentDocument;
   let frameDoc = null;
   let saveBtn = null;
   let cancelBtn = null;
   let settingsDialogClosePromise = null;
 
   // Test the initial state
-  assertSitesListed(doc, fakeHosts);
+  assertSitesListed(doc, hosts);
 
   // Test the "Cancel" button
   settingsDialogClosePromise = promiseSettingsDialogClose();
   frameDoc = win.gSubDialog._topDialog._frame.contentDocument;
   cancelBtn = frameDoc.getElementById("cancel");
   removeAllSitesOneByOne();
   assertAllSitesNotListed(win);
   cancelBtn.doCommand();
   await settingsDialogClosePromise;
   await openSiteDataSettingsDialog();
-  assertSitesListed(doc, fakeHosts);
+  assertSitesListed(doc, hosts);
 
   // Test the "Save Changes" button but cancelling save
   let cancelPromise = BrowserTestUtils.promiseAlertDialogOpen("cancel");
   settingsDialogClosePromise = promiseSettingsDialogClose();
   frameDoc = win.gSubDialog._topDialog._frame.contentDocument;
   saveBtn = frameDoc.getElementById("save");
   cancelBtn = frameDoc.getElementById("cancel");
   removeAllSitesOneByOne();
   assertAllSitesNotListed(win);
   saveBtn.doCommand();
   await cancelPromise;
   cancelBtn.doCommand();
   await settingsDialogClosePromise;
   await openSiteDataSettingsDialog();
-  assertSitesListed(doc, fakeHosts);
+  assertSitesListed(doc, hosts);
 
   // Test the "Save Changes" button and accepting save
   let acceptPromise = BrowserTestUtils.promiseAlertDialogOpen("accept");
   settingsDialogClosePromise = promiseSettingsDialogClose();
-  updatePromise = promiseSiteDataManagerSitesUpdated();
+  let updatePromise = promiseSiteDataManagerSitesUpdated();
   frameDoc = win.gSubDialog._topDialog._frame.contentDocument;
   saveBtn = frameDoc.getElementById("save");
   removeAllSitesOneByOne();
   assertAllSitesNotListed(win);
   saveBtn.doCommand();
   await acceptPromise;
   await settingsDialogClosePromise;
   await updatePromise;
   await openSiteDataSettingsDialog();
   assertAllSitesNotListed(win);
 
-  await mockSiteDataManager.unregister();
+  await SiteDataTestUtils.clear();
   BrowserTestUtils.removeTab(gBrowser.selectedTab);
 
   function removeAllSitesOneByOne() {
     frameDoc = win.gSubDialog._topDialog._frame.contentDocument;
     let removeBtn = frameDoc.getElementById("removeSelected");
     let sitesList = frameDoc.getElementById("sitesList");
     let sites = sitesList.getElementsByTagName("richlistitem");
     for (let i = sites.length - 1; i >= 0; --i) {
       sites[i].click();
       removeBtn.doCommand();
     }
   }
 });
 
 // Test selecting and removing partial sites
-add_task(async function() {
-  mockSiteDataManager.register(SiteDataManager, [
+add_task(async function test_removePartialSites() {
+  let hosts = await addTestData([
     {
       usage: 1024,
       origin: "https://account.xyz.com",
       persisted: true
     },
     {
       usage: 1024,
       origin: "https://shopping.xyz.com",
@@ -136,105 +133,104 @@ add_task(async function() {
       origin: "https://s3-us-west-2.amazonaws.com",
       persisted: true
     },
     {
       usage: 1024,
       origin: "https://127.0.0.1",
       persisted: false
     },
-    {
-      usage: 1024,
-      origin: "https://[0:0:0:0:0:0:0:1]",
-      persisted: true
-    },
   ]);
-  let fakeHosts = mockSiteDataManager.fakeSites.map(site => site.principal.URI.host);
 
-  let updatePromise = promiseSiteDataManagerSitesUpdated();
+  await SiteDataManager.refresh();
+
   await openPreferencesViaOpenPreferencesAPI("privacy", { leaveOpen: true });
-  await updatePromise;
   await openSiteDataSettingsDialog();
 
   let win = gBrowser.selectedBrowser.contentWindow;
   let doc = gBrowser.selectedBrowser.contentDocument;
   let frameDoc = null;
   let saveBtn = null;
   let cancelBtn = null;
   let removeDialogOpenPromise = null;
   let settingsDialogClosePromise = null;
 
   // Test the initial state
-  assertSitesListed(doc, fakeHosts);
+  assertSitesListed(doc, hosts);
 
   // Test the "Cancel" button
   settingsDialogClosePromise = promiseSettingsDialogClose();
   frameDoc = win.gSubDialog._topDialog._frame.contentDocument;
   cancelBtn = frameDoc.getElementById("cancel");
-  removeSelectedSite(fakeHosts.slice(0, 2));
-  assertSitesListed(doc, fakeHosts.slice(2));
+  await removeSelectedSite(hosts.slice(0, 2));
+  assertSitesListed(doc, hosts.slice(2));
   cancelBtn.doCommand();
   await settingsDialogClosePromise;
   await openSiteDataSettingsDialog();
-  assertSitesListed(doc, fakeHosts);
+  assertSitesListed(doc, hosts);
 
   // Test the "Save Changes" button but canceling save
   removeDialogOpenPromise = BrowserTestUtils.promiseAlertDialogOpen("cancel", REMOVE_DIALOG_URL);
   settingsDialogClosePromise = promiseSettingsDialogClose();
   frameDoc = win.gSubDialog._topDialog._frame.contentDocument;
   saveBtn = frameDoc.getElementById("save");
   cancelBtn = frameDoc.getElementById("cancel");
-  removeSelectedSite(fakeHosts.slice(0, 2));
-  assertSitesListed(doc, fakeHosts.slice(2));
+  await removeSelectedSite(hosts.slice(0, 2));
+  assertSitesListed(doc, hosts.slice(2));
   saveBtn.doCommand();
   await removeDialogOpenPromise;
   cancelBtn.doCommand();
   await settingsDialogClosePromise;
   await openSiteDataSettingsDialog();
-  assertSitesListed(doc, fakeHosts);
+  assertSitesListed(doc, hosts);
 
   // Test the "Save Changes" button and accepting save
   removeDialogOpenPromise = BrowserTestUtils.promiseAlertDialogOpen("accept", REMOVE_DIALOG_URL);
   settingsDialogClosePromise = promiseSettingsDialogClose();
   frameDoc = win.gSubDialog._topDialog._frame.contentDocument;
   saveBtn = frameDoc.getElementById("save");
-  removeSelectedSite(fakeHosts.slice(0, 2));
-  assertSitesListed(doc, fakeHosts.slice(2));
+  await removeSelectedSite(hosts.slice(0, 2));
+  assertSitesListed(doc, hosts.slice(2));
   saveBtn.doCommand();
   await removeDialogOpenPromise;
   await settingsDialogClosePromise;
   await openSiteDataSettingsDialog();
-  assertSitesListed(doc, fakeHosts.slice(2));
+  assertSitesListed(doc, hosts.slice(2));
 
-  await mockSiteDataManager.unregister();
+  await SiteDataTestUtils.clear();
   BrowserTestUtils.removeTab(gBrowser.selectedTab);
 
-  function removeSelectedSite(hosts) {
+  function removeSelectedSite(removeHosts) {
     frameDoc = win.gSubDialog._topDialog._frame.contentDocument;
     let removeBtn = frameDoc.getElementById("removeSelected");
     is(removeBtn.disabled, true, "Should start with disabled removeSelected button");
     let sitesList = frameDoc.getElementById("sitesList");
-    hosts.forEach(host => {
+    removeHosts.forEach(host => {
       let site = sitesList.querySelector(`richlistitem[host="${host}"]`);
       if (site) {
         site.click();
         let currentSelectedIndex = sitesList.selectedIndex;
         is(removeBtn.disabled, false, "Should enable the removeSelected button");
         removeBtn.doCommand();
-        is(sitesList.selectedIndex, currentSelectedIndex);
+        let newSelectedIndex = sitesList.selectedIndex;
+        if (currentSelectedIndex >= sitesList.itemCount) {
+          is(newSelectedIndex, currentSelectedIndex - 1);
+        } else {
+          is(newSelectedIndex, currentSelectedIndex);
+        }
       } else {
         ok(false, `Should not select and remove inexistent site of ${host}`);
       }
     });
   }
 });
 
 // Test searching and then removing only visible sites
 add_task(async function() {
-  mockSiteDataManager.register(SiteDataManager, [
+  let hosts = await addTestData([
     {
       usage: 1024,
       origin: "https://account.xyz.com",
       persisted: true
     },
     {
       usage: 1024,
       origin: "https://shopping.xyz.com",
@@ -246,98 +242,97 @@ add_task(async function() {
       persisted: true
     },
     {
       usage: 1024,
       origin: "http://email.bar.com",
       persisted: false
     },
   ]);
-  let fakeHosts = mockSiteDataManager.fakeSites.map(site => site.principal.URI.host);
 
-  let updatePromise = promiseSiteDataManagerSitesUpdated();
+  await SiteDataManager.refresh();
+
   await openPreferencesViaOpenPreferencesAPI("privacy", { leaveOpen: true });
-  await updatePromise;
   await openSiteDataSettingsDialog();
 
   // Search "foo" to only list foo.com sites
   let win = gBrowser.selectedBrowser.contentWindow;
   let doc = gBrowser.selectedBrowser.contentDocument;
   let frameDoc = win.gSubDialog._topDialog._frame.contentDocument;
   let searchBox = frameDoc.getElementById("searchBox");
   searchBox.value = "xyz";
   searchBox.doCommand();
-  assertSitesListed(doc, fakeHosts.filter(host => host.includes("xyz")));
+  assertSitesListed(doc, hosts.filter(host => host.includes("xyz")));
 
   // Test only removing all visible sites listed
-  updatePromise = promiseSiteDataManagerSitesUpdated();
+  let updatePromise = promiseSiteDataManagerSitesUpdated();
   let acceptRemovePromise = BrowserTestUtils.promiseAlertDialogOpen("accept", REMOVE_DIALOG_URL);
   let settingsDialogClosePromise = promiseSettingsDialogClose();
   let removeAllBtn = frameDoc.getElementById("removeAll");
   let saveBtn = frameDoc.getElementById("save");
   removeAllBtn.doCommand();
   saveBtn.doCommand();
   await acceptRemovePromise;
   await settingsDialogClosePromise;
   await updatePromise;
   await openSiteDataSettingsDialog();
-  assertSitesListed(doc, fakeHosts.filter(host => !host.includes("xyz")));
+  assertSitesListed(doc, hosts.filter(host => !host.includes("xyz")));
 
-  await mockSiteDataManager.unregister();
+  await SiteDataTestUtils.clear();
   BrowserTestUtils.removeTab(gBrowser.selectedTab);
 });
 
 // Test dynamically clearing all site data
 add_task(async function() {
-  mockSiteDataManager.register(SiteDataManager, [
+  let hosts = await addTestData([
     {
       usage: 1024,
       origin: "https://account.xyz.com",
       persisted: true
     },
     {
       usage: 1024,
       origin: "https://shopping.xyz.com",
       persisted: false
     },
   ]);
-  let fakeHosts = mockSiteDataManager.fakeSites.map(site => site.principal.URI.host);
+
+  await SiteDataManager.refresh();
 
   // Test the initial state
-  let updatePromise = promiseSiteDataManagerSitesUpdated();
   await openPreferencesViaOpenPreferencesAPI("privacy", { leaveOpen: true });
-  await updatePromise;
   await openSiteDataSettingsDialog();
   let doc = gBrowser.selectedBrowser.contentDocument;
-  assertSitesListed(doc, fakeHosts);
+  assertSitesListed(doc, hosts);
 
-  // Add more sites dynamically
-  mockSiteDataManager.fakeSites.push({
-    usage: 1024,
-    principal: Services.scriptSecurityManager
-                       .createCodebasePrincipalFromOrigin("http://cinema.bar.com"),
-    persisted: true
-  }, {
-    usage: 1024,
-    principal: Services.scriptSecurityManager
-                       .createCodebasePrincipalFromOrigin("http://email.bar.com"),
-    persisted: false
-  });
+  await addTestData([
+    {
+      usage: 1024,
+      origin: "http://cinema.bar.com",
+      persisted: true
+    },
+    {
+      usage: 1024,
+      origin: "http://email.bar.com",
+      persisted: false
+    },
+  ]);
+  await SiteDataManager.refresh();
 
   // Test clearing all site data dynamically
   let win = gBrowser.selectedBrowser.contentWindow;
   let frameDoc = win.gSubDialog._topDialog._frame.contentDocument;
-  updatePromise = promiseSiteDataManagerSitesUpdated();
+  let updatePromise = promiseSiteDataManagerSitesUpdated();
   let acceptRemovePromise = BrowserTestUtils.promiseAlertDialogOpen("accept");
   let settingsDialogClosePromise = promiseSettingsDialogClose();
   let removeAllBtn = frameDoc.getElementById("removeAll");
   let saveBtn = frameDoc.getElementById("save");
   removeAllBtn.doCommand();
   saveBtn.doCommand();
   await acceptRemovePromise;
   await settingsDialogClosePromise;
   await updatePromise;
   await openSiteDataSettingsDialog();
   assertAllSitesNotListed(win);
 
-  await mockSiteDataManager.unregister();
+  await SiteDataTestUtils.clear();
   BrowserTestUtils.removeTab(gBrowser.selectedTab);
 });
--- a/browser/components/preferences/in-content/tests/siteData/browser_siteData3.js
+++ b/browser/components/preferences/in-content/tests/siteData/browser_siteData3.js
@@ -1,13 +1,13 @@
 "use strict";
 
 // Test not displaying sites which store 0 byte and don't have persistent storage.
-add_task(async function() {
-  mockSiteDataManager.register(SiteDataManager, [
+add_task(async function test_exclusions() {
+  let hosts = await addTestData([
     {
       usage: 0,
       origin: "https://account.xyz.com",
       persisted: true
     },
     {
       usage: 0,
       origin: "https://shopping.xyz.com",
@@ -25,33 +25,34 @@ add_task(async function() {
     },
     {
       usage: 0,
       origin: "http://cookies.bar.com",
       cookies: 5,
       persisted: false
     },
   ]);
-  let fakeHosts = mockSiteDataManager.fakeSites.map(site => site.principal.URI.host);
+
+  await SiteDataManager.refresh();
 
   let updatePromise = promiseSiteDataManagerSitesUpdated();
   let doc = gBrowser.selectedBrowser.contentDocument;
   await openPreferencesViaOpenPreferencesAPI("privacy", { leaveOpen: true });
   await updatePromise;
   await openSiteDataSettingsDialog();
-  assertSitesListed(doc, fakeHosts.filter(host => host != "shopping.xyz.com"));
+  assertSitesListed(doc, hosts.filter(host => host != "shopping.xyz.com"));
 
-  await mockSiteDataManager.unregister();
+  await SiteDataTestUtils.clear();
   BrowserTestUtils.removeTab(gBrowser.selectedTab);
 });
 
 // Test grouping and listing sites across scheme, port and origin attributes by host
-add_task(async function() {
-  const quotaUsage = 1024;
-  mockSiteDataManager.register(SiteDataManager, [
+add_task(async function test_grouping() {
+  let quotaUsage = 7000000;
+  await addTestData([
     {
       usage: quotaUsage,
       origin: "https://account.xyz.com^userContextId=1",
       cookies: 2,
       persisted: true
     },
     {
       usage: quotaUsage,
@@ -68,16 +69,18 @@ add_task(async function() {
     {
       usage: quotaUsage,
       origin: "http://account.xyz.com",
       cookies: 1,
       persisted: false
     },
   ]);
 
+  await SiteDataManager.refresh();
+
   let updatedPromise = promiseSiteDataManagerSitesUpdated();
   await openPreferencesViaOpenPreferencesAPI("privacy", { leaveOpen: true });
   await updatedPromise;
   await openSiteDataSettingsDialog();
   let win = gBrowser.selectedBrowser.contentWindow;
   let dialogFrame = win.gSubDialog._topDialog._frame;
   let frameDoc = dialogFrame.contentDocument;
 
@@ -86,60 +89,81 @@ add_task(async function() {
 
   let columns = siteItems[0].querySelectorAll(".item-box > label");
 
   let expected = "account.xyz.com";
   is(columns[0].value, expected, "Should group and list sites by host");
 
   is(columns[1].value, "5", "Should group cookies across scheme, port and origin attributes");
 
-  let [value, unit] = DownloadUtils.convertByteUnits(quotaUsage * mockSiteDataManager.fakeSites.length);
-  Assert.deepEqual(frameDoc.l10n.getAttributes(columns[2]), {
-    id: "site-usage-persistent",
-    args: { value, unit }
-  }, "Should sum up usages across scheme, port, origin attributes and persistent status");
+  let [value, unit] = DownloadUtils.convertByteUnits(quotaUsage * 4);
+  let l10nAttributes = frameDoc.l10n.getAttributes(columns[2]);
+  is(l10nAttributes.id, "site-usage-persistent",
+    "Should show the site as persistent if one origin is persistent.");
+  // The shown quota can be slightly larger than the raw data we put in (though it should
+  // never be smaller), but that doesn't really matter to us since we only want to test that
+  // the site data dialog accumulates this into a single column.
+  ok(parseFloat(l10nAttributes.args.value) >= parseFloat(value),
+    "Should show the correct accumulated quota size.");
+  is(l10nAttributes.args.unit, unit, "Should show the correct quota size unit.");
 
-  await mockSiteDataManager.unregister();
+  await SiteDataTestUtils.clear();
   BrowserTestUtils.removeTab(gBrowser.selectedTab);
 });
 
 // Test sorting
-add_task(async function() {
-  mockSiteDataManager.register(SiteDataManager, [
+add_task(async function test_sorting() {
+  let testData = [
     {
+      baseDomain: "xyz.com",
       usage: 1024,
       origin: "https://account.xyz.com",
       cookies: 6,
       persisted: true,
     },
     {
+      baseDomain: "foo.com",
       usage: 1024 * 2,
       origin: "https://books.foo.com",
       cookies: 0,
       persisted: false,
     },
     {
+      baseDomain: "bar.com",
       usage: 1024 * 3,
       origin: "http://cinema.bar.com",
       cookies: 3,
       persisted: true,
     },
-  ]);
+  ];
+
+  await addTestData(testData);
 
-  let updatePromise = promiseSiteDataManagerSitesUpdated();
+  // Add a bunch of cookies with slight delay to enable testing
+  // by last storage access.
+  for (let site of testData) {
+    /* eslint-disable-next-line mozilla/no-arbitrary-setTimeout */
+    await new Promise(r => setTimeout(r, 1000));
+    SiteDataTestUtils.addToCookies(site.origin, Cu.now());
+    site.cookies += 1;
+    site.lastAccessed = Cu.now();
+  }
+
+  await SiteDataManager.refresh();
+
   await openPreferencesViaOpenPreferencesAPI("privacy", { leaveOpen: true });
-  await updatePromise;
   await openSiteDataSettingsDialog();
 
   let dialog = content.gSubDialog._topDialog;
   let dialogFrame = dialog._frame;
   let frameDoc = dialogFrame.contentDocument;
   let hostCol = frameDoc.getElementById("hostCol");
   let usageCol = frameDoc.getElementById("usageCol");
   let cookiesCol = frameDoc.getElementById("cookiesCol");
+  let lastAccessedCol = frameDoc.getElementById("lastAccessedCol");
   let sitesList = frameDoc.getElementById("sitesList");
 
   // Test default sorting
   assertSortByUsage("descending");
 
   // Test sorting on the usage column
   usageCol.click();
   assertSortByUsage("ascending");
@@ -153,17 +177,23 @@ add_task(async function() {
   assertSortByBaseDomain("descending");
 
   // Test sorting on the cookies column
   cookiesCol.click();
   assertSortByCookies("ascending");
   cookiesCol.click();
   assertSortByCookies("descending");
 
-  await mockSiteDataManager.unregister();
+  // Test sorting on the date column
+  lastAccessedCol.click();
+  assertSortByDate("ascending");
+  lastAccessedCol.click();
+  assertSortByDate("descending");
+
+  await SiteDataTestUtils.clear();
   BrowserTestUtils.removeTab(gBrowser.selectedTab);
 
   function assertSortByBaseDomain(order) {
     let siteItems = sitesList.getElementsByTagName("richlistitem");
     for (let i = 0; i < siteItems.length - 1; ++i) {
       let aHost = siteItems[i].getAttribute("host");
       let bHost = siteItems[i + 1].getAttribute("host");
       let a = findSiteByHost(aHost);
@@ -204,65 +234,16 @@ add_task(async function() {
       if (order == "ascending") {
         Assert.lessOrEqual(result, 0, "Should sort sites in the ascending order by number of cookies");
       } else {
         Assert.greaterOrEqual(result, 0, "Should sort sites in the descending order by number of cookies");
       }
     }
   }
 
-  function findSiteByHost(host) {
-    return mockSiteDataManager.fakeSites.find(site => site.principal.URI.host == host);
-  }
-});
-
-// Test sorting based on access date (separate from cookies for simplicity,
-// since cookies access date affects this as well, but we don't mock our cookies)
-add_task(async function() {
-  mockSiteDataManager.register(SiteDataManager, [
-    {
-      usage: 1024,
-      origin: "https://account.xyz.com",
-      persisted: true,
-      lastAccessed: (Date.now() - 120 * 1000) * 1000,
-    },
-    {
-      usage: 1024 * 2,
-      origin: "https://books.foo.com",
-      persisted: false,
-      lastAccessed: (Date.now() - 240 * 1000) * 1000,
-    },
-    {
-      usage: 1024 * 3,
-      origin: "http://cinema.bar.com",
-      persisted: true,
-      lastAccessed: Date.now() * 1000,
-    },
-  ]);
-
-  let updatePromise = promiseSiteDataManagerSitesUpdated();
-  await openPreferencesViaOpenPreferencesAPI("privacy", { leaveOpen: true });
-  await updatePromise;
-  await openSiteDataSettingsDialog();
-
-  let dialog = content.gSubDialog._topDialog;
-  let dialogFrame = dialog._frame;
-  let frameDoc = dialogFrame.contentDocument;
-  let lastAccessedCol = frameDoc.getElementById("lastAccessedCol");
-  let sitesList = frameDoc.getElementById("sitesList");
-
-  // Test sorting on the date column
-  lastAccessedCol.click();
-  assertSortByDate("ascending");
-  lastAccessedCol.click();
-  assertSortByDate("descending");
-
-  await mockSiteDataManager.unregister();
-  BrowserTestUtils.removeTab(gBrowser.selectedTab);
-
   function assertSortByDate(order) {
     let siteItems = sitesList.getElementsByTagName("richlistitem");
     for (let i = 0; i < siteItems.length - 1; ++i) {
       let aHost = siteItems[i].getAttribute("host");
       let bHost = siteItems[i + 1].getAttribute("host");
       let a = findSiteByHost(aHost);
       let b = findSiteByHost(bHost);
       let result = a.lastAccessed - b.lastAccessed;
@@ -270,11 +251,11 @@ add_task(async function() {
         Assert.lessOrEqual(result, 0, "Should sort sites in the ascending order by date");
       } else {
         Assert.greaterOrEqual(result, 0, "Should sort sites in the descending order date");
       }
     }
   }
 
   function findSiteByHost(host) {
-    return mockSiteDataManager.fakeSites.find(site => site.principal.URI.host == host);
+    return testData.find(site => site.origin.includes(host));
   }
 });
--- a/browser/components/preferences/in-content/tests/siteData/browser_siteData_multi_select.js
+++ b/browser/components/preferences/in-content/tests/siteData/browser_siteData_multi_select.js
@@ -1,13 +1,13 @@
 "use strict";
 
 // Test selecting and removing partial sites
 add_task(async function() {
-  mockSiteDataManager.register(SiteDataManager, [
+  let hosts = await addTestData([
     {
       usage: 1024,
       origin: "https://account.xyz.com",
       persisted: true
     },
     {
       usage: 1024,
       origin: "https://shopping.xyz.com",
@@ -28,57 +28,52 @@ add_task(async function() {
       origin: "https://s3-us-west-2.amazonaws.com",
       persisted: true
     },
     {
       usage: 1024,
       origin: "https://127.0.0.1",
       persisted: false
     },
-    {
-      usage: 1024,
-      origin: "https://[0:0:0:0:0:0:0:1]",
-      persisted: true
-    },
   ]);
-  let fakeHosts = mockSiteDataManager.fakeSites.map(site => site.principal.URI.host);
+
+  await SiteDataManager.refresh();
 
   let updatePromise = promiseSiteDataManagerSitesUpdated();
   await openPreferencesViaOpenPreferencesAPI("privacy", { leaveOpen: true });
   await updatePromise;
   await openSiteDataSettingsDialog();
 
   let doc = gBrowser.selectedBrowser.contentDocument;
 
   // Test the initial state
-  assertSitesListed(doc, fakeHosts);
+  assertSitesListed(doc, hosts);
   let win = gBrowser.selectedBrowser.contentWindow;
   let frameDoc = win.gSubDialog._topDialog._frame.contentDocument;
   let removeBtn = frameDoc.getElementById("removeSelected");
   is(removeBtn.disabled, true, "Should start with disabled removeSelected button");
 
   let removeDialogOpenPromise = BrowserTestUtils.promiseAlertDialogOpen("accept", REMOVE_DIALOG_URL);
   let settingsDialogClosePromise = promiseSettingsDialogClose();
 
   // Select some sites to remove.
   let sitesList = frameDoc.getElementById("sitesList");
-  fakeHosts.slice(0, 2).forEach(host => {
+  hosts.slice(0, 2).forEach(host => {
     let site = sitesList.querySelector(`richlistitem[host="${host}"]`);
     sitesList.addItemToSelection(site);
   });
 
   is(removeBtn.disabled, false, "Should enable the removeSelected button");
   removeBtn.doCommand();
-  is(sitesList.selectedIndex, 0, "Should select next item");
 
   let saveBtn = frameDoc.getElementById("save");
-  assertSitesListed(doc, fakeHosts.slice(2));
+  assertSitesListed(doc, hosts.slice(2));
   saveBtn.doCommand();
 
   await removeDialogOpenPromise;
   await settingsDialogClosePromise;
   await openSiteDataSettingsDialog();
 
-  assertSitesListed(doc, fakeHosts.slice(2));
+  assertSitesListed(doc, hosts.slice(2));
 
-  await mockSiteDataManager.unregister();
+  await SiteDataTestUtils.clear();
   BrowserTestUtils.removeTab(gBrowser.selectedTab);
 });
--- a/browser/components/preferences/in-content/tests/siteData/head.js
+++ b/browser/components/preferences/in-content/tests/siteData/head.js
@@ -123,75 +123,39 @@ function assertSitesListed(doc, hosts) {
   is(totalSitesNumber, hosts.length, "Should list the right sites number");
   hosts.forEach(host => {
     let site = sitesList.querySelector(`richlistitem[host="${host}"]`);
     ok(site, `Should list the site of ${host}`);
   });
   is(removeAllBtn.disabled, false, "Should enable the removeAllBtn button");
 }
 
-const mockSiteDataManager = {
-
-  _SiteDataManager: null,
-  _originalQMS: null,
-  _originalRemoveQuotaUsage: null,
+async function addTestData(data) {
+  let hosts = [];
 
-  getUsage(onUsageResult) {
-    let result = this.fakeSites.map(site => ({
-      origin: site.principal.origin,
-      usage: site.usage,
-      persisted: site.persisted,
-      lastAccessed: site.lastAccessed,
-    }));
-    onUsageResult({ result, resultCode: Cr.NS_OK });
-  },
-
-  _removeQuotaUsage(site) {
-    var target = site.principals[0].URI.host;
-    this.fakeSites = this.fakeSites.filter(fakeSite => {
-      return fakeSite.principal.URI.host != target;
-    });
-  },
+  for (let site of data) {
+    is(typeof site.origin, "string", "Passed an origin string into addTestData.");
+    if (site.persisted) {
+      await SiteDataTestUtils.persist(site.origin);
+    }
 
-  register(siteDataManager, fakeSites) {
-    this._SiteDataManager = siteDataManager;
-    this._originalQMS = this._SiteDataManager._qms;
-    this._SiteDataManager._qms = this;
-    this._originalRemoveQuotaUsage = this._SiteDataManager._removeQuotaUsage;
-    this._SiteDataManager._removeQuotaUsage = this._removeQuotaUsage.bind(this);
-    // Add some fake data.
-    this.fakeSites = fakeSites;
-    for (let site of fakeSites) {
-      if (!site.principal) {
-        site.principal = Services.scriptSecurityManager
-          .createCodebasePrincipalFromOrigin(site.origin);
-      }
+    if (site.usage) {
+      await SiteDataTestUtils.addToIndexedDB(site.origin, site.usage);
+    }
 
-      let uri = site.principal.URI;
-      try {
-        site.baseDomain = Services.eTLD.getBaseDomainFromHost(uri.host);
-      } catch (e) {
-        site.baseDomain = uri.host;
-      }
+    for (let i = 0; i < (site.cookies || 0); i++) {
+      SiteDataTestUtils.addToCookies(site.origin, Cu.now());
+    }
 
-      // Add some cookies if needed.
-      for (let i = 0; i < (site.cookies || 0); i++) {
-        Services.cookies.add(uri.host, uri.pathQueryRef, Cu.now(), i,
-          false, false, false, Date.now() + 1000 * 60 * 60);
-      }
-    }
-  },
+    let principal = Services.scriptSecurityManager.createCodebasePrincipalFromOrigin(site.origin);
+    hosts.push(principal.URI.host);
+  }
 
-  async unregister() {
-    await this._SiteDataManager.removeAll();
-    this.fakeSites = null;
-    this._SiteDataManager._qms = this._originalQMS;
-    this._SiteDataManager._removeQuotaUsage = this._originalRemoveQuotaUsage;
-  }
-};
+  return hosts;
+}
 
 function promiseCookiesCleared() {
   return TestUtils.topicObserved("cookie-changed", (subj, data) => {
     return data === "cleared";
   });
 }
 
 async function loadServiceWorkerTestPage(url) {