Backed out 4 changesets (bug 1855068, bug 1856412) for causing failures in test_SiteDataManager.js CLOSED TREE

Backed out changeset dbaf2b0da226 (bug 1856412)
Backed out changeset 8d040fd73abf (bug 1856412)
Backed out changeset 645f7ed438fb (bug 1855068)
Backed out changeset be41f5296dec (bug 1855068)
This commit is contained in:
Noemi Erli 2024-01-11 03:20:27 +02:00
Родитель 096f34a11c
Коммит e0cc765727
13 изменённых файлов: 145 добавлений и 1523 удалений

Просмотреть файл

@ -15,11 +15,6 @@ const { XPCOMUtils } = ChromeUtils.importESModule(
const lazy = {}; const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
DownloadUtils: "resource://gre/modules/DownloadUtils.sys.mjs",
SiteDataManager: "resource:///modules/SiteDataManager.sys.mjs",
});
XPCOMUtils.defineLazyPreferenceGetter( XPCOMUtils.defineLazyPreferenceGetter(
lazy, lazy,
"USE_OLD_DIALOG", "USE_OLD_DIALOG",
@ -37,14 +32,6 @@ Preferences.addAll([
{ id: "privacy.cpd.offlineApps", type: "bool" }, { id: "privacy.cpd.offlineApps", type: "bool" },
{ id: "privacy.cpd.siteSettings", type: "bool" }, { id: "privacy.cpd.siteSettings", type: "bool" },
{ id: "privacy.sanitize.timeSpan", type: "int" }, { id: "privacy.sanitize.timeSpan", type: "int" },
{ id: "privacy.clearOnShutdown.history", type: "bool" },
{ id: "privacy.clearOnShutdown.formdata", type: "bool" },
{ id: "privacy.clearOnShutdown.downloads", type: "bool" },
{ id: "privacy.clearOnShutdown.cookies", type: "bool" },
{ id: "privacy.clearOnShutdown.cache", type: "bool" },
{ id: "privacy.clearOnShutdown.offlineApps", type: "bool" },
{ id: "privacy.clearOnShutdown.sessions", type: "bool" },
{ id: "privacy.clearOnShutdown.siteSettings", type: "bool" },
]); ]);
var gSanitizePromptDialog = { var gSanitizePromptDialog = {
@ -61,37 +48,7 @@ var gSanitizePromptDialog = {
// This is used by selectByTimespan() to determine if the window has loaded. // This is used by selectByTimespan() to determine if the window has loaded.
this._inited = true; this._inited = true;
this._dialog = document.querySelector("dialog"); this._dialog = document.querySelector("dialog");
/**
* Variables to store data sizes to display to user
* for different timespans
*/
this.siteDataSizes = {};
this.cacheSize = [];
this.downloadSizes = {};
if (!lazy.USE_OLD_DIALOG) {
this._cookiesAndSiteDataCheckbox = document.getElementById("cookies");
this._cacheCheckbox = document.getElementById("cache");
this._downloadHistoryCheckbox = document.getElementById("downloads");
}
let arg = window.arguments?.[0] || {}; let arg = window.arguments?.[0] || {};
// The updateUsageData variable allows callers of the dialog to indicate
// whether site usage data should be refreshed on init.
let updateUsageData = true;
if (!lazy.USE_OLD_DIALOG && arg.updateUsageData != undefined) {
updateUsageData = arg.updateUsageData || arg.inBrowserWindow;
}
// These variables decide which context the dialog has been opened in
this._inClearOnShutdownNewDialog = false;
this._inClearSiteDataNewDialog = false;
if (arg.mode && !lazy.USE_OLD_DIALOG) {
this._inClearOnShutdownNewDialog = arg.mode == "clearOnShutdown";
this._inClearSiteDataNewDialog = arg.mode == "clearSiteData";
}
if (arg.inBrowserWindow) { if (arg.inBrowserWindow) {
this._dialog.setAttribute("inbrowserwindow", "true"); this._dialog.setAttribute("inbrowserwindow", "true");
this._observeTitleForChanges(); this._observeTitleForChanges();
@ -104,72 +61,19 @@ var gSanitizePromptDialog = {
} }
} }
this.dataSizesFinishedUpdatingPromise =
this.getAndUpdateDataSizes(updateUsageData);
let OKButton = this._dialog.getButton("accept"); let OKButton = this._dialog.getButton("accept");
let clearOnShutdownGroupbox = document.getElementById( let okButtonLabel = lazy.USE_OLD_DIALOG
"clearOnShutdownGroupbox" ? "sanitize-button-ok"
); : "sanitize-button-ok2";
let clearPrivateDataGroupbox = document.getElementById( document.l10n.setAttributes(OKButton, okButtonLabel);
"clearPrivateDataGroupbox"
);
let okButtonl10nID = "sanitize-button-ok"; document.addEventListener("dialogaccept", function (e) {
if (this._inClearOnShutdownNewDialog) { gSanitizePromptDialog.sanitize(e);
okButtonl10nID = "sanitize-button-ok-on-shutdown";
this._dialog.setAttribute("inClearOnShutdown", "true");
// remove the clear private data groupbox element
clearPrivateDataGroupbox.remove();
} else if (!lazy.USE_OLD_DIALOG) {
okButtonl10nID = "sanitize-button-ok2";
// remove the clear on shutdown groupbox element
clearOnShutdownGroupbox.remove();
}
document.l10n.setAttributes(OKButton, okButtonl10nID);
// update initial checkbox values based on the context the dialog is opened
// from (history, site data). Categories are not remembered
// from the last time the dialog was used.
if (!lazy.USE_OLD_DIALOG && !this._inClearOnShutdownNewDialog) {
let checkboxes = document.querySelectorAll(
"#clearPrivateDataGroupbox .clearingItemCheckbox"
);
for (let checkbox of checkboxes) {
let pref = checkbox.getAttribute("data-l10n-id");
let value = true;
// Site settings is checked off by default for all contexts
if (pref == "item-site-prefs") {
value = false;
}
// Clear site data context doesnt have browsing history and downloads
// history checked by default
else if (
this._inClearSiteDataNewDialog &&
(pref == "item-browsing-and-search" ||
pref == "item-download-history")
) {
value = false;
}
checkbox.checked = value;
}
}
document.addEventListener("dialogaccept", e => {
if (this._inClearOnShutdownNewDialog) {
this.updatePrefs();
} else {
this.sanitize(e);
}
}); });
this.registerSyncFromPrefListeners(); this.registerSyncFromPrefListeners();
// we want to show the warning box for all cases except clear on shutdown if (this.selectedTimespan === Sanitizer.TIMESPAN_EVERYTHING) {
if (
this.selectedTimespan === Sanitizer.TIMESPAN_EVERYTHING &&
!arg.inClearOnShutdown
) {
this.prepareWarning(); this.prepareWarning();
this.warningBox.hidden = false; this.warningBox.hidden = false;
if (lazy.USE_OLD_DIALOG) { if (lazy.USE_OLD_DIALOG) {
@ -186,8 +90,6 @@ var gSanitizePromptDialog = {
} else { } else {
this.warningBox.hidden = true; this.warningBox.hidden = true;
} }
await this.dataSizesFinishedUpdatingPromise;
}, },
selectByTimespan() { selectByTimespan() {
@ -210,17 +112,13 @@ var gSanitizePromptDialog = {
window.resizeBy(0, diff); window.resizeBy(0, diff);
} }
// update title for the old dialog
if (lazy.USE_OLD_DIALOG) { if (lazy.USE_OLD_DIALOG) {
document.l10n.setAttributes( document.l10n.setAttributes(
document.documentElement, document.documentElement,
"sanitize-dialog-title-everything" "sanitize-dialog-title-everything"
); );
} }
// make sure the sizes are updated in the new dialog
else {
this.updateDataSizesInUI();
}
return; return;
} }
@ -236,11 +134,6 @@ var gSanitizePromptDialog = {
? "sanitize-dialog-title" ? "sanitize-dialog-title"
: "sanitize-dialog-title2"; : "sanitize-dialog-title2";
document.l10n.setAttributes(document.documentElement, datal1OnId); document.l10n.setAttributes(document.documentElement, datal1OnId);
if (!lazy.USE_OLD_DIALOG) {
// We only update data sizes to display on the new dialog
this.updateDataSizesInUI();
}
}, },
sanitize(event) { sanitize(event) {
@ -262,8 +155,7 @@ var gSanitizePromptDialog = {
ignoreTimespan: !range, ignoreTimespan: !range,
range, range,
}; };
let itemsToClear = this.getItemsToClear(); Sanitizer.sanitize(null, options)
Sanitizer.sanitize(itemsToClear, options)
.catch(console.error) .catch(console.error)
.then(() => window.close()) .then(() => window.close())
.catch(console.error); .catch(console.error);
@ -310,9 +202,9 @@ var gSanitizePromptDialog = {
*/ */
onReadGeneric() { onReadGeneric() {
// Find any other pref that's checked and enabled (except for // Find any other pref that's checked and enabled (except for
// privacy.sanitize.timeSpan, which doesn't affect the button's status. // privacy.sanitize.timeSpan, which doesn't affect the button's status
// and (in the old dialog) privacy.cpd.downloads which is not controlled // and privacy.cpd.downloads which is not controlled directly by a
// directly by a checkbox). // checkbox).
var found = this._getItemPrefs().some( var found = this._getItemPrefs().some(
pref => !!pref.value && !pref.disabled pref => !!pref.value && !pref.disabled
); );
@ -327,45 +219,6 @@ var gSanitizePromptDialog = {
return undefined; return undefined;
}, },
/**
* Gets the latest usage data and then updates the UI
*
* @param {boolean} doUpdateSites - if we need to trigger an
* updateSites() to get the latest usage data
* @returns {Promise} resolves when updating the UI is complete
*/
async getAndUpdateDataSizes(doUpdateSites) {
if (lazy.USE_OLD_DIALOG) {
return;
}
if (doUpdateSites) {
await lazy.SiteDataManager.updateSites();
}
// Current timespans used in the dialog box
const ALL_TIMESPANS = [
"TIMESPAN_HOUR",
"TIMESPAN_2HOURS",
"TIMESPAN_4HOURS",
"TIMESPAN_TODAY",
"TIMESPAN_EVERYTHING",
];
let [quotaUsage, cacheSize, downloadCount] = await Promise.all([
lazy.SiteDataManager.getQuotaUsageForTimeRanges(ALL_TIMESPANS),
lazy.SiteDataManager.getCacheSize(),
lazy.SiteDataManager.getDownloadCountForTimeRanges(ALL_TIMESPANS),
]);
// Convert sizes to [amount, unit]
for (const timespan in quotaUsage) {
this.siteDataSizes[timespan] = lazy.DownloadUtils.convertByteUnits(
quotaUsage[timespan]
);
}
this.cacheSize = lazy.DownloadUtils.convertByteUnits(cacheSize);
this.downloadSizes = downloadCount;
this.updateDataSizesInUI();
},
/** /**
* Sanitizer.prototype.sanitize() requires the prefs to be up-to-date. * Sanitizer.prototype.sanitize() requires the prefs to be up-to-date.
* Because the type of this prefwindow is "child" -- and that's needed because * Because the type of this prefwindow is "child" -- and that's needed because
@ -376,8 +229,9 @@ var gSanitizePromptDialog = {
updatePrefs() { updatePrefs() {
Services.prefs.setIntPref(Sanitizer.PREF_TIMESPAN, this.selectedTimespan); Services.prefs.setIntPref(Sanitizer.PREF_TIMESPAN, this.selectedTimespan);
let historyValue = Preferences.get("privacy.cpd.history").value;
if (lazy.USE_OLD_DIALOG) { if (lazy.USE_OLD_DIALOG) {
let historyValue = Preferences.get(`privacy.cpd.history`).value;
// Keep the pref for the download history in sync with the history pref. // Keep the pref for the download history in sync with the history pref.
Preferences.get("privacy.cpd.downloads").value = historyValue; Preferences.get("privacy.cpd.downloads").value = historyValue;
Services.prefs.setBoolPref("privacy.cpd.downloads", historyValue); Services.prefs.setBoolPref("privacy.cpd.downloads", historyValue);
@ -386,19 +240,13 @@ var gSanitizePromptDialog = {
// We intend to migrate these into new prefs and categories // We intend to migrate these into new prefs and categories
// sync the prefs for Form data, offline apps and sessions as they are merged // sync the prefs for Form data, offline apps and sessions as they are merged
// into history and cookies for the new clear history dialog // into history and cookies for the new clear history dialog
else if (gSanitizePromptDialog._inClearOnShutdownNewDialog) { else {
let historyValue = Preferences.get( Preferences.get("privacy.cpd.formdata").value = historyValue;
`privacy.clearOnShutdown.history`
).value;
Preferences.get(`privacy.clearOnShutdown.formdata`).value = historyValue;
let cookiesValue = Preferences.get( let cookiesValue = Preferences.get("privacy.cpd.cookies").value;
"privacy.clearOnShutdown.cookies"
).value;
// Keep the pref for the session history in sync with the cookies pref. // Keep the pref for the session history in sync with the cookies pref.
Preferences.get(`privacy.clearOnShutdown.sessions`).value = cookiesValue; Preferences.get("privacy.cpd.sessions").value = cookiesValue;
Preferences.get(`privacy.clearOnShutdown.offlineApps`).value = Preferences.get("privacy.cpd.offlineApps").value = cookiesValue;
cookiesValue;
} }
// Now manually set the prefs from their corresponding preference // Now manually set the prefs from their corresponding preference
@ -451,77 +299,6 @@ var gSanitizePromptDialog = {
attributeFilter: ["title"], attributeFilter: ["title"],
}); });
}, },
/**
* Updates data sizes displayed based on new selected timespan
*/
updateDataSizesInUI() {
const TIMESPAN_SELECTION_MAP = {
0: "TIMESPAN_EVERYTHING",
1: "TIMESPAN_HOUR",
2: "TIMESPAN_2HOURS",
3: "TIMESPAN_4HOURS",
4: "TIMESPAN_TODAY",
5: "TIMESPAN_5MINS",
6: "TIMESPAN_24HOURS",
};
let index = this.selectedTimespan;
let timeSpanSelected = TIMESPAN_SELECTION_MAP[index];
let [amount, unit] = this.siteDataSizes[timeSpanSelected];
document.l10n.setAttributes(
this._cookiesAndSiteDataCheckbox,
"item-cookies-site-data-with-size",
{ amount, unit }
);
[amount, unit] = this.cacheSize;
document.l10n.setAttributes(
this._cacheCheckbox,
"item-cached-content-with-size",
{ amount, unit }
);
const downloadcount = this.downloadSizes[timeSpanSelected];
document.l10n.setAttributes(
this._downloadHistoryCheckbox,
"item-download-history-with-size",
{ count: downloadcount }
);
},
/**
* Get all items to clear based on checked boxes
*
* @returns {string[]} array of items ["cache", "history"...]
*/
getItemsToClear() {
// the old dialog uses the preferences to decide what to clear
if (lazy.USE_OLD_DIALOG) {
return null;
}
let items = [];
let clearPrivateDataGroupbox = document.getElementById(
"clearPrivateDataGroupbox"
);
for (let cb of clearPrivateDataGroupbox.querySelectorAll("checkbox")) {
if (cb.checked) {
if (cb.id == "history") {
// formdata follows history
items.push("formdata");
} else if (cb.id == "cookies") {
// offlineApps and sessions follow cookies
items.push("offlineApps");
items.push("sessions");
}
items.push(cb.id);
}
}
return items;
},
}; };
// We need to give the dialog an opportunity to set up the DOM // We need to give the dialog an opportunity to set up the DOM

Просмотреть файл

@ -35,19 +35,12 @@
rel="stylesheet" rel="stylesheet"
href="chrome://browser/skin/sanitizeDialog_v2.css" href="chrome://browser/skin/sanitizeDialog_v2.css"
/> />
<html:link rel="localization" href="branding/brand.ftl" />
<html:link rel="localization" href="browser/sanitize.ftl" /> <html:link rel="localization" href="browser/sanitize.ftl" />
</linkset> </linkset>
<script src="chrome://global/content/preferencesBindings.js" /> <script src="chrome://global/content/preferencesBindings.js" />
<script src="chrome://browser/content/sanitizeDialog.js" /> <script src="chrome://browser/content/sanitizeDialog.js" />
<description
id="SanitizeOnShutdownDescription"
data-l10n-id="sanitize-on-shutdown-description"
></description>
<hbox id="SanitizeDurationBox" align="center"> <hbox id="SanitizeDurationBox" align="center">
<label <label
data-l10n-id="clear-time-duration-prefix2" data-l10n-id="clear-time-duration-prefix2"
@ -102,90 +95,21 @@
<spacer flex="1" /> <spacer flex="1" />
</vbox> </vbox>
<groupbox id="clearPrivateDataGroupbox"> <groupbox>
<hbox class="checkboxWithDescription"> <hbox class="checkboxWithDescription">
<vbox> <vbox>
<checkbox <checkbox
class="clearingItemCheckbox"
data-l10n-id="item-browsing-and-search" data-l10n-id="item-browsing-and-search"
id="history" preference="privacy.cpd.history"
/> />
</vbox> </vbox>
</hbox> </hbox>
<hbox class="checkboxWithDescription"> <hbox class="checkboxWithDescription">
<vbox> <vbox>
<checkbox <checkbox
class="clearingItemCheckbox"
data-l10n-id="item-cookies-site-data" data-l10n-id="item-cookies-site-data"
preference="privacy.cpd.cookies"
aria-describedby="cookies-site-data-description" aria-describedby="cookies-site-data-description"
id="cookies"
/>
<description
id="cookies-site-data-description"
data-l10n-id="item-cookies-site-data-description"
class="sanitizeCheckboxDescription text-deemphasized"
/>
</vbox>
</hbox>
<hbox class="checkboxWithDescription">
<vbox>
<checkbox
class="clearingItemCheckbox"
data-l10n-id="item-cached-content"
aria-describedby="cached-content-description"
id="cache"
/>
<description
id="cached-content-description"
data-l10n-id="item-cached-content-description"
class="sanitizeCheckboxDescription text-deemphasized"
/>
</vbox>
</hbox>
<hbox class="checkboxWithDescription">
<vbox>
<checkbox
class="clearingItemCheckbox"
data-l10n-id="item-site-prefs"
aria-describedby="site-prefs-description"
id="siteSettings"
/>
<description
id="site-prefs-description"
data-l10n-id="item-site-prefs-description"
class="sanitizeCheckboxDescription text-deemphasized"
/>
</vbox>
</hbox>
<hbox class="checkboxWithDescription">
<vbox>
<checkbox
class="clearingItemCheckbox"
data-l10n-id="item-download-history"
id="downloads"
/>
</vbox>
</hbox>
</groupbox>
<groupbox id="clearOnShutdownGroupbox">
<hbox class="checkboxWithDescription">
<vbox>
<checkbox
class="clearingItemCheckbox"
data-l10n-id="item-browsing-and-search"
preference="privacy.clearOnShutdown.history"
id="history"
/>
</vbox>
</hbox>
<hbox class="checkboxWithDescription">
<vbox>
<checkbox
class="clearingItemCheckbox"
data-l10n-id="item-cookies-site-data"
preference="privacy.clearOnShutdown.cookies"
aria-describedby="cookies-site-data-description"
id="cookies"
/> />
<description <description
class="sanitizeCheckboxDescription text-deemphasized" class="sanitizeCheckboxDescription text-deemphasized"
@ -197,11 +121,9 @@
<hbox class="checkboxWithDescription"> <hbox class="checkboxWithDescription">
<vbox> <vbox>
<checkbox <checkbox
class="clearingItemCheckbox"
data-l10n-id="item-cached-content" data-l10n-id="item-cached-content"
preference="privacy.clearOnShutdown.cache" preference="privacy.cpd.cache"
aria-describedby="cached-content-description" aria-describedby="cached-content-description"
id="cache"
/> />
<description <description
class="sanitizeCheckboxDescription text-deemphasized" class="sanitizeCheckboxDescription text-deemphasized"
@ -213,11 +135,9 @@
<hbox class="checkboxWithDescription"> <hbox class="checkboxWithDescription">
<vbox> <vbox>
<checkbox <checkbox
class="clearingItemCheckbox"
data-l10n-id="item-site-prefs" data-l10n-id="item-site-prefs"
preference="privacy.clearOnShutdown.siteSettings" preference="privacy.cpd.siteSettings"
aria-describedby="site-prefs-description" aria-describedby="site-prefs-description"
id="siteSettings"
/> />
<description <description
class="sanitizeCheckboxDescription text-deemphasized" class="sanitizeCheckboxDescription text-deemphasized"
@ -229,10 +149,8 @@
<hbox class="checkboxWithDescription"> <hbox class="checkboxWithDescription">
<vbox> <vbox>
<checkbox <checkbox
class="clearingItemCheckbox"
data-l10n-id="item-download-history" data-l10n-id="item-download-history"
preference="privacy.clearOnShutdown.downloads" preference="privacy.cpd.downloads"
id="downloads"
/> />
</vbox> </vbox>
</hbox> </hbox>

Просмотреть файл

@ -3,7 +3,6 @@ support-files = [
"head.js", "head.js",
"dummy.js", "dummy.js",
"dummy_page.html", "dummy_page.html",
"site_data_test.html",
] ]
["browser_cookiePermission.js"] ["browser_cookiePermission.js"]

Просмотреть файл

@ -43,6 +43,16 @@ function waitForUnregister(host) {
}); });
} }
async function createData(host) {
let origin = "https://" + host;
let dummySWURL =
getRootDirectory(gTestPath).replace("chrome://mochitests/content", origin) +
"dummy.js";
await SiteDataTestUtils.addToIndexedDB(origin);
await SiteDataTestUtils.addServiceWorker(dummySWURL);
}
function moveOriginInTime(principals, endDate, host) { function moveOriginInTime(principals, endDate, host) {
for (let i = 0; i < principals.length; ++i) { for (let i = 0; i < principals.length; ++i) {
let principal = principals.queryElementAt(i, Ci.nsIPrincipal); let principal = principals.queryElementAt(i, Ci.nsIPrincipal);
@ -79,8 +89,8 @@ add_task(async function testWithRange() {
info("sanitize: " + itemsToClear.join(", ")); info("sanitize: " + itemsToClear.join(", "));
await Sanitizer.sanitize(itemsToClear, { ignoreTimespan: false }); await Sanitizer.sanitize(itemsToClear, { ignoreTimespan: false });
await createDummyDataForHost("example.org"); await createData("example.org");
await createDummyDataForHost("example.com"); await createData("example.com");
endDate = Date.now() * 1000; endDate = Date.now() * 1000;
principals = sas.getActiveOrigins(endDate - oneHour, endDate); principals = sas.getActiveOrigins(endDate - oneHour, endDate);
@ -182,8 +192,8 @@ add_task(async function testWithRange() {
}); });
add_task(async function testExceptionsOnShutdown() { add_task(async function testExceptionsOnShutdown() {
await createDummyDataForHost("example.org"); await createData("example.org");
await createDummyDataForHost("example.com"); await createData("example.com");
// Set exception for example.org to not get cleaned // Set exception for example.org to not get cleaned
let originALLOW = "https://example.org"; let originALLOW = "https://example.org";

Просмотреть файл

@ -16,37 +16,19 @@
* Some of this code, especially the history creation parts, was taken from * Some of this code, especially the history creation parts, was taken from
* browser/base/content/test/sanitize/browser_sanitize-timespans.js. * browser/base/content/test/sanitize/browser_sanitize-timespans.js.
*/ */
ChromeUtils.defineESModuleGetters(this, { ChromeUtils.defineESModuleGetters(this, {
PlacesTestUtils: "resource://testing-common/PlacesTestUtils.sys.mjs", PlacesTestUtils: "resource://testing-common/PlacesTestUtils.sys.mjs",
Timer: "resource://gre/modules/Timer.sys.mjs", Timer: "resource://gre/modules/Timer.sys.mjs",
PermissionTestUtils: "resource://testing-common/PermissionTestUtils.sys.mjs",
FileTestUtils: "resource://testing-common/FileTestUtils.sys.mjs",
Downloads: "resource://gre/modules/Downloads.sys.mjs",
}); });
const kMsecPerMin = 60 * 1000; const kMsecPerMin = 60 * 1000;
const kUsecPerMin = 60 * 1000000; const kUsecPerMin = 60 * 1000000;
let today = Date.now() - new Date().setHours(0, 0, 0, 0); let nowMsec = Date.now();
let nowMSec = Date.now(); let nowUsec = nowMsec * 1000;
let nowUSec = nowMSec * 1000;
let fileURL;
const TEST_TARGET_FILE_NAME = "test-download.txt";
const TEST_QUOTA_USAGE_HOST = "example.com";
const TEST_QUOTA_USAGE_ORIGIN = "https://" + TEST_QUOTA_USAGE_HOST;
const TEST_QUOTA_USAGE_URL =
getRootDirectory(gTestPath).replace(
"chrome://mochitests/content",
TEST_QUOTA_USAGE_ORIGIN
) + "site_data_test.html";
const siteOrigins = [
"https://www.example.com",
"https://example.org",
"http://localhost:8000",
"http://localhost:3000",
];
const EXAMPLE_ORIGIN = "https://www.example.com";
const siteUsage = 4096;
/** /**
* Ensures that the specified URIs are either cleared or not. * Ensures that the specified URIs are either cleared or not.
* *
@ -131,7 +113,7 @@ function promiseAddFormEntryWithMinutesAgo(aMinutesAgo) {
let name = aMinutesAgo + "-minutes-ago"; let name = aMinutesAgo + "-minutes-ago";
// Artifically age the entry to the proper vintage. // Artifically age the entry to the proper vintage.
let timestamp = nowUSec - aMinutesAgo * kUsecPerMin; let timestamp = nowUsec - aMinutesAgo * kUsecPerMin;
return FormHistory.update({ return FormHistory.update({
op: "add", op: "add",
@ -155,7 +137,7 @@ async function addDownloadWithMinutesAgo(aExpectedPathList, aMinutesAgo) {
source: "https://bugzilla.mozilla.org/show_bug.cgi?id=480169", source: "https://bugzilla.mozilla.org/show_bug.cgi?id=480169",
target: name, target: name,
}); });
download.startTime = new Date(nowMSec - aMinutesAgo * kMsecPerMin); download.startTime = new Date(nowMsec - aMinutesAgo * kMsecPerMin);
download.canceled = true; download.canceled = true;
publicList.add(download); publicList.add(download);
@ -167,90 +149,6 @@ async function addDownloadWithMinutesAgo(aExpectedPathList, aMinutesAgo) {
aExpectedPathList.push(name); aExpectedPathList.push(name);
} }
/**
* Adds multiple downloads to the PUBLIC download list
*/
async function addToDownloadList() {
const url = createFileURL();
const downloadsList = await Downloads.getList(Downloads.PUBLIC);
let timeOptions = [1, 2, 4, 24, 128, 128];
let buffer = 100000;
for (let i = 0; i < timeOptions.length; i++) {
let timeDownloaded = 60 * kMsecPerMin * timeOptions[i];
if (timeOptions[i] === 24) {
timeDownloaded = today;
}
let download = await Downloads.createDownload({
source: { url: url.spec, isPrivate: false },
target: { path: FileTestUtils.getTempFile(TEST_TARGET_FILE_NAME).path },
startTime: {
getTime: _ => {
return nowMSec - timeDownloaded + buffer;
},
},
});
Assert.ok(!!download);
downloadsList.add(download);
}
let items = await downloadsList.getAll();
Assert.equal(items.length, 6, "Items were added to the list");
}
async function addToSiteUsage() {
// Fill indexedDB with test data.
// Don't wait for the page to load, to register the content event handler as quickly as possible.
// If this test goes intermittent, we might have to tell the page to wait longer before
// firing the event.
BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_QUOTA_USAGE_URL, false);
await BrowserTestUtils.waitForContentEvent(
gBrowser.selectedBrowser,
"test-indexedDB-done",
false,
null,
true
);
BrowserTestUtils.removeTab(gBrowser.selectedTab);
let siteLastAccessed = [1, 2, 4, 24];
let staticUsage = 4096 * 6;
// Add a time buffer so the site access falls within the time range
const buffer = 10000;
// Change lastAccessed of sites
for (let index = 0; index < siteLastAccessed.length; index++) {
let lastAccessedTime = 60 * kMsecPerMin * siteLastAccessed[index];
if (siteLastAccessed[index] === 24) {
lastAccessedTime = today;
}
let site = SiteDataManager._testInsertSite(siteOrigins[index], {
quotaUsage: staticUsage,
lastAccessed: (nowMSec - lastAccessedTime + buffer) * 1000,
});
Assert.ok(site, "Site added successfully");
}
}
/**
* Helper function to create file URL to open
*
* @returns {Object} a file URL
*/
function createFileURL() {
if (!fileURL) {
let file = Services.dirsvc.get("TmpD", Ci.nsIFile);
file.append("foo.txt");
file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o600);
fileURL = Services.io.newFileURI(file);
}
return fileURL;
}
add_setup(async function () { add_setup(async function () {
requestLongerTimeout(3); requestLongerTimeout(3);
await blankSlate(); await blankSlate();
@ -261,10 +159,6 @@ add_setup(async function () {
await SpecialPowers.pushPrefEnv({ await SpecialPowers.pushPrefEnv({
set: [["privacy.sanitize.useOldClearHistoryDialog", false]], set: [["privacy.sanitize.useOldClearHistoryDialog", false]],
}); });
// open preferences to trigger an updateSites()
await openPreferencesViaOpenPreferencesAPI("privacy", { leaveOpen: true });
BrowserTestUtils.removeTab(gBrowser.selectedTab);
}); });
/** /**
@ -289,15 +183,10 @@ async function blankSlate() {
* @param browserWin (optional) * @param browserWin (optional)
* The browser window that the dialog is expected to open in. If not * The browser window that the dialog is expected to open in. If not
* supplied, the initial browser window of the test run is used. * supplied, the initial browser window of the test run is used.
* @param mode (optional)
* Open in the clear on shutdown settings context or
* Open in the clear site data settings context
* null by default
*/ */
function DialogHelper(browserWin = window, mode = null) { function DialogHelper(browserWin = window) {
this._browserWin = browserWin; this._browserWin = browserWin;
this.win = null; this.win = null;
this._mode = mode;
this.promiseClosed = new Promise(resolve => { this.promiseClosed = new Promise(resolve => {
this._resolveClosed = resolve; this._resolveClosed = resolve;
}); });
@ -334,41 +223,25 @@ DialogHelper.prototype = {
* True if the checkbox should be checked, false otherwise * True if the checkbox should be checked, false otherwise
*/ */
checkPrefCheckbox(aPrefName, aCheckState) { checkPrefCheckbox(aPrefName, aCheckState) {
var pref = "privacy.cpd." + aPrefName;
var cb = this.win.document.querySelectorAll( var cb = this.win.document.querySelectorAll(
"checkbox[id='" + aPrefName + "']" "checkbox[preference='" + pref + "']"
); );
is(cb.length, 1, "found checkbox for " + aPrefName + " id"); is(cb.length, 1, "found checkbox for " + pref + " preference");
if (cb[0].checked != aCheckState) { if (cb[0].checked != aCheckState) {
cb[0].click(); cb[0].click();
} }
}, },
/**
* @param {String} aCheckboxId
* The checkbox id name
* @param {Boolean} aCheckState
* True if the checkbox should be checked, false otherwise
*/
validateCheckbox(aCheckboxId, aCheckState) {
let cb = this.win.document.querySelectorAll(
"checkbox[id='" + aCheckboxId + "']"
);
is(cb.length, 1, `found checkbox for id=${aCheckboxId}`);
is(
cb[0].checked,
aCheckState,
`checkbox for ${aCheckboxId} is ${aCheckState}`
);
},
/** /**
* Makes sure all the checkboxes are checked. * Makes sure all the checkboxes are checked.
*/ */
_checkAllCheckboxesCustom(check) { _checkAllCheckboxesCustom(check) {
var cb = this.win.document.querySelectorAll("checkbox[id]"); var cb = this.win.document.querySelectorAll("checkbox[preference]");
ok(cb.length, "found checkboxes for ids"); ok(cb.length > 1, "found checkboxes for preferences");
for (var i = 0; i < cb.length; ++i) { for (var i = 0; i < cb.length; ++i) {
if (cb[i].checked != check) { var pref = this.win.Preferences.get(cb[i].getAttribute("preference"));
if (!!pref.value ^ check) {
cb[i].click(); cb[i].click();
} }
} }
@ -382,10 +255,6 @@ DialogHelper.prototype = {
this._checkAllCheckboxesCustom(false); this._checkAllCheckboxesCustom(false);
}, },
setMode(value) {
this._mode = value;
},
/** /**
* @return The dialog's duration dropdown * @return The dialog's duration dropdown
*/ */
@ -426,7 +295,7 @@ DialogHelper.prototype = {
); );
executeSoon(() => { executeSoon(() => {
Sanitizer.showUI(this._browserWin, this._mode); Sanitizer.showUI(this._browserWin);
}); });
this.win = await dialogPromise; this.win = await dialogPromise;
@ -434,10 +303,7 @@ DialogHelper.prototype = {
"load", "load",
() => { () => {
// Run onload on next tick so that gSanitizePromptDialog.init can run first. // Run onload on next tick so that gSanitizePromptDialog.init can run first.
executeSoon(async () => { executeSoon(() => this.onload());
await this.win.gSanitizePromptDialog.dataSizesFinishedUpdatingPromise;
this.onload();
});
}, },
{ once: true } { once: true }
); );
@ -505,71 +371,13 @@ function intPrefIs(aPrefName, aExpectedVal, aMsg) {
* The visit will be visited this many minutes ago * The visit will be visited this many minutes ago
*/ */
function visitTimeForMinutesAgo(aMinutesAgo) { function visitTimeForMinutesAgo(aMinutesAgo) {
return nowUSec - aMinutesAgo * kUsecPerMin; return nowUsec - aMinutesAgo * kUsecPerMin;
} }
function promiseSanitizationComplete() { function promiseSanitizationComplete() {
return TestUtils.topicObserved("sanitizer-sanitization-complete"); return TestUtils.topicObserved("sanitizer-sanitization-complete");
} }
/**
* Helper function to validate the data sizes shown for each time selection
*
* @param {DialogHelper} dh - dialog object to access window and timespan
*/
async function validateDataSizes(dialogHelper) {
let timespans = [
"TIMESPAN_HOUR",
"TIMESPAN_2HOURS",
"TIMESPAN_4HOURS",
"TIMESPAN_TODAY",
"TIMESPAN_EVERYTHING",
];
// get current data sizes from siteDataManager
let cacheUsage = await SiteDataManager.getCacheSize();
let quotaUsage = await SiteDataManager.getQuotaUsageForTimeRanges(timespans);
let downloadUsage = await SiteDataManager.getDownloadCountForTimeRanges(
timespans
);
for (let i = 0; i < timespans.length; i++) {
// select timespan to check
dialogHelper.selectDuration(Sanitizer[timespans[i]]);
// get the elements
let clearCookiesAndSiteDataCheckbox =
dialogHelper.win.document.getElementById("cookies");
let clearCacheCheckbox = dialogHelper.win.document.getElementById("cache");
let clearDownloadsCheckbox =
dialogHelper.win.document.getElementById("downloads");
let [convertedQuotaUsage] = DownloadUtils.convertByteUnits(
quotaUsage[timespans[i]]
);
let [, convertedCacheUnit] = DownloadUtils.convertByteUnits(cacheUsage);
// Ensure l10n is finished before inspecting the category labels.
await dialogHelper.win.document.l10n.translateElements([
clearCookiesAndSiteDataCheckbox,
clearCacheCheckbox,
clearDownloadsCheckbox,
]);
ok(
clearCacheCheckbox.label.includes(convertedCacheUnit),
"Should show the cache usage"
);
ok(
clearCookiesAndSiteDataCheckbox.label.includes(convertedQuotaUsage),
`Should show the quota usage as ${convertedQuotaUsage}`
);
ok(
clearDownloadsCheckbox.label.includes(downloadUsage[timespans[i]]),
`Should show the downloads usage as ${downloadUsage[timespans[i]]}`
);
}
}
/** /**
* Initializes the dialog to its default state. * Initializes the dialog to its default state.
*/ */
@ -758,6 +566,18 @@ add_task(async function test_history_downloads_checked() {
"timeSpan pref should be hour after accepting dialog with " + "timeSpan pref should be hour after accepting dialog with " +
"hour selected" "hour selected"
); );
boolPrefIs(
"cpd.history",
true,
"history pref should be true after accepting dialog with " +
"history checkbox checked"
);
boolPrefIs(
"cpd.downloads",
true,
"downloads pref should be true after accepting dialog with " +
"history checkbox checked"
);
await promiseSanitized; await promiseSanitized;
@ -799,7 +619,9 @@ add_task(async function test_cannot_clear_history() {
let dh = new DialogHelper(); let dh = new DialogHelper();
dh.onload = function () { dh.onload = function () {
var cb = this.win.document.querySelectorAll("checkbox[id='history']"); var cb = this.win.document.querySelectorAll(
"checkbox[preference='privacy.cpd.history']"
);
ok( ok(
cb.length == 1 && !cb[0].disabled, cb.length == 1 && !cb[0].disabled,
"There is history, checkbox to clear history should be enabled." "There is history, checkbox to clear history should be enabled."
@ -824,7 +646,16 @@ add_task(async function test_no_formdata_history_to_clear() {
let promiseSanitized = promiseSanitizationComplete(); let promiseSanitized = promiseSanitizationComplete();
let dh = new DialogHelper(); let dh = new DialogHelper();
dh.onload = function () { dh.onload = function () {
var cb = this.win.document.querySelectorAll("checkbox[id='history']"); boolPrefIs(
"cpd.history",
true,
"history pref should be true after accepting dialog with " +
"history checkbox checked"
);
var cb = this.win.document.querySelectorAll(
"checkbox[preference='privacy.cpd.history']"
);
ok( ok(
cb.length == 1 && !cb[0].disabled && cb[0].checked, cb.length == 1 && !cb[0].disabled && cb[0].checked,
"There is no history, but history checkbox should always be enabled " + "There is no history, but history checkbox should always be enabled " +
@ -845,7 +676,9 @@ add_task(async function test_form_entries() {
let dh = new DialogHelper(); let dh = new DialogHelper();
dh.onload = function () { dh.onload = function () {
var cb = this.win.document.querySelectorAll("checkbox[id='history']"); var cb = this.win.document.querySelectorAll(
"checkbox[preference='privacy.cpd.history']"
);
is(cb.length, 1, "There is only one checkbox for history and form data"); is(cb.length, 1, "There is only one checkbox for history and form data");
ok(!cb[0].disabled, "The checkbox is enabled"); ok(!cb[0].disabled, "The checkbox is enabled");
ok(cb[0].checked, "The checkbox is checked"); ok(cb[0].checked, "The checkbox is checked");
@ -861,387 +694,54 @@ add_task(async function test_form_entries() {
await dh.promiseClosed; await dh.promiseClosed;
}); });
add_task(async function test_cookie_sizes() { add_task(async function test_history_formdata() {
await clearAndValidateDataSizes({
clearCookies: true,
clearCache: false,
clearDownloads: false,
timespan: Sanitizer.TIMESPAN_HOUR,
});
await clearAndValidateDataSizes({
clearCookies: true,
clearCache: false,
clearDownloads: false,
timespan: Sanitizer.TIMESPAN_4HOURS,
});
await clearAndValidateDataSizes({
clearCookies: true,
clearCache: false,
clearDownloads: false,
timespan: Sanitizer.TIMESPAN_EVERYTHING,
});
});
add_task(async function test_cache_sizes() {
await clearAndValidateDataSizes({
clearCookies: false,
clearCache: true,
clearDownloads: false,
timespan: Sanitizer.TIMESPAN_HOUR,
});
await clearAndValidateDataSizes({
clearCookies: false,
clearCache: true,
clearDownloads: false,
timespan: Sanitizer.TIMESPAN_4HOURS,
});
await clearAndValidateDataSizes({
clearCookies: false,
clearCache: true,
clearDownloads: false,
timespan: Sanitizer.TIMESPAN_EVERYTHING,
});
});
add_task(async function test_downloads_sizes() {
await clearAndValidateDataSizes({
clearCookies: false,
clearCache: false,
clearDownloads: true,
timespan: Sanitizer.TIMESPAN_HOUR,
});
await clearAndValidateDataSizes({
clearCookies: false,
clearCache: false,
clearDownloads: true,
timespan: Sanitizer.TIMESPAN_4HOURS,
});
await clearAndValidateDataSizes({
clearCookies: false,
clearCache: false,
clearDownloads: true,
timespan: Sanitizer.TIMESPAN_EVERYTHING,
});
});
add_task(async function test_all_data_sizes() {
await clearAndValidateDataSizes({
clearCookies: true,
clearCache: true,
clearDownloads: true,
timespan: Sanitizer.TIMESPAN_HOUR,
});
await clearAndValidateDataSizes({
clearCookies: true,
clearCache: true,
clearDownloads: true,
timespan: Sanitizer.TIMESPAN_4HOURS,
});
await clearAndValidateDataSizes({
clearCookies: true,
clearCache: true,
clearDownloads: true,
timespan: Sanitizer.TIMESPAN_EVERYTHING,
});
});
add_task(async function test_single_download() {
// add download
let downloadIDs = [];
await addDownloadWithMinutesAgo(downloadIDs, 100000000000);
let dh = new DialogHelper();
dh.onload = async function () {
this.uncheckAllCheckboxes();
this.checkPrefCheckbox("downloads", true);
this.selectDuration(Sanitizer.TIMESPAN_EVERYTHING);
let clearDownloadsCheckbox = dh.win.document.getElementById("downloads");
// Wait for the UI to update
await dh.win.document.l10n.translateElements([clearDownloadsCheckbox]);
ok(
clearDownloadsCheckbox.label.includes("1 file)"),
"Should show singular file"
);
this.acceptDialog();
};
dh.onunload = async function () {
await ensureDownloadsClearedState(downloadIDs, true);
};
dh.open();
await dh.promiseClosed;
blankSlate();
});
// test the case when we open the dialog through the clear on shutdown settings
add_task(async function test_clear_on_shutdown() {
await openPreferencesViaOpenPreferencesAPI("privacy", { leaveOpen: true });
await SpecialPowers.pushPrefEnv({
set: [["privacy.sanitize.sanitizeOnShutdown", true]],
});
let dh = new DialogHelper();
dh.setMode("clearOnShutdown");
dh.onload = async function () {
this.uncheckAllCheckboxes();
this.checkPrefCheckbox("history", true);
this.checkPrefCheckbox("cookies", true);
this.acceptDialog();
};
dh.open();
await dh.promiseClosed;
// Add downloads (within the past hour).
let downloadIDs = [];
for (let i = 0; i < 5; i++) {
await addDownloadWithMinutesAgo(downloadIDs, i);
}
// Add downloads (over an hour ago).
let olderDownloadIDs = [];
for (let i = 0; i < 5; i++) {
await addDownloadWithMinutesAgo(olderDownloadIDs, 61 + i);
}
boolPrefIs(
"clearOnShutdown.history",
true,
"clearOnShutdown history should be true "
);
boolPrefIs(
"clearOnShutdown.cookies",
true,
"clearOnShutdown cookies should be true"
);
boolPrefIs(
"clearOnShutdown.formdata",
true,
"clearOnShutdown formdata should be true"
);
boolPrefIs(
"clearOnShutdown.offlineApps",
true,
"clearOnShutdown offlineApps should be true"
);
boolPrefIs(
"clearOnShutdown.sessions",
true,
"clearOnShutdown sessions should be true"
);
boolPrefIs(
"clearOnShutdown.downloads",
false,
"clearOnShutdown downloads should be false"
);
boolPrefIs(
"clearOnShutdown.cache",
false,
"clearOnShutdown cache should be false"
);
await createDummyDataForHost("example.org");
await createDummyDataForHost("example.com");
ok(
await SiteDataTestUtils.hasIndexedDB("https://example.org"),
"We have indexedDB data for example.org"
);
ok(
await SiteDataTestUtils.hasIndexedDB("https://example.com"),
"We have indexedDB data for example.com"
);
// Cleaning up
await Sanitizer.runSanitizeOnShutdown();
// Data for example.org should be cleared
ok(
!(await SiteDataTestUtils.hasIndexedDB("https://example.org")),
"We don't have indexedDB data for example.org"
);
// Data for example.com should be cleared
ok(
!(await SiteDataTestUtils.hasIndexedDB("https://example.com")),
"We don't have indexedDB data for example.com"
);
// Downloads shouldn't have cleared
await ensureDownloadsClearedState(downloadIDs, false);
await ensureDownloadsClearedState(olderDownloadIDs, false);
dh = new DialogHelper();
dh.setMode("clearOnShutdown");
dh.onload = async function () {
this.uncheckAllCheckboxes();
this.checkPrefCheckbox("downloads", true);
this.acceptDialog();
};
dh.open();
await dh.promiseClosed;
boolPrefIs(
"clearOnShutdown.history",
false,
"clearOnShutdown history should be false"
);
boolPrefIs(
"clearOnShutdown.cookies",
false,
"clearOnShutdown cookies should be false"
);
boolPrefIs(
"clearOnShutdown.formdata",
false,
"clearOnShutdown formdata should be false"
);
boolPrefIs(
"clearOnShutdown.offlineApps",
false,
"clearOnShutdown offlineApps should be false"
);
boolPrefIs(
"clearOnShutdown.sessions",
false,
"clearOnShutdown sessions should be false"
);
boolPrefIs(
"clearOnShutdown.downloads",
true,
"clearOnShutdown downloads should be true"
);
boolPrefIs(
"clearOnShutdown.cache",
false,
"clearOnShutdown cache should be false"
);
ok(
await SiteDataTestUtils.hasIndexedDB("https://example.org"),
"We have indexedDB data for example.org"
);
ok(
await SiteDataTestUtils.hasIndexedDB("https://example.com"),
"We have indexedDB data for example.com"
);
// Cleaning up
await Sanitizer.runSanitizeOnShutdown();
// Data for example.org should not be cleared
ok(
await SiteDataTestUtils.hasIndexedDB("https://example.org"),
"We have indexedDB data for example.org"
);
// Data for example.com should not be cleared
ok(
await SiteDataTestUtils.hasIndexedDB("https://example.com"),
"We have indexedDB data for example.com"
);
// downloads should have cleared
await ensureDownloadsClearedState(downloadIDs, true);
await ensureDownloadsClearedState(olderDownloadIDs, true);
// Clean up
await SiteDataTestUtils.clear();
BrowserTestUtils.removeTab(gBrowser.selectedTab);
});
// test default prefs for entry points
add_task(async function test_defaults_prefs() {
let dh = new DialogHelper();
dh.setMode("clearSiteData");
dh.onload = function () {
// Default checked for clear site data
this.validateCheckbox("history", false);
this.validateCheckbox("cache", true);
this.validateCheckbox("cookies", true);
this.validateCheckbox("siteSettings", false);
this.validateCheckbox("downloads", false);
this.cancelDialog();
};
dh.open();
await dh.promiseClosed;
// We don't need to specify the mode again,
// as the default mode is taken (browser, clear history)
dh = new DialogHelper();
dh.onload = function () {
// Default checked for browser and clear history mode
this.validateCheckbox("history", true);
this.validateCheckbox("cache", true);
this.validateCheckbox("cookies", true);
this.validateCheckbox("siteSettings", false);
this.validateCheckbox("downloads", true);
this.cancelDialog();
};
dh.open();
await dh.promiseClosed;
});
/**
* Helper function to simulate switching timespan selections and
* validate data sizes before and after clearing
*
* @param {Object}
* clearCookies - boolean
* clearDownloads - boolean
* clearCaches - boolean
* timespan - one of Sanitizer.TIMESPAN_*
*/
async function clearAndValidateDataSizes({
clearCache,
clearDownloads,
clearCookies,
timespan,
}) {
await blankSlate();
await addToDownloadList();
await addToSiteUsage();
let promiseSanitized = promiseSanitizationComplete(); let promiseSanitized = promiseSanitizationComplete();
await openPreferencesViaOpenPreferencesAPI("privacy", { leaveOpen: true });
let dh = new DialogHelper(); let dh = new DialogHelper();
dh.onload = async function () { dh.onload = function () {
await validateDataSizes(this); this.uncheckAllCheckboxes();
this.checkPrefCheckbox("cache", clearCache); this.checkPrefCheckbox("history", true);
this.checkPrefCheckbox("cookies", clearCookies);
this.checkPrefCheckbox("downloads", clearDownloads);
this.selectDuration(timespan);
this.acceptDialog(); this.acceptDialog();
}; };
dh.onunload = async function () { dh.onunload = async function () {
await promiseSanitized; await promiseSanitized;
// Check if form data follows history
boolPrefIs("cpd.formdata", true, `form data pref follows history pref`);
boolPrefIs("cpd.sessions", false, `sessions pref follows cookies prefs`);
boolPrefIs(
"cpd.offlineApps",
false,
`offlineapps pref follows cookies prefs`
);
}; };
dh.open(); dh.open();
await dh.promiseClosed; await dh.promiseClosed;
});
let dh2 = new DialogHelper(); add_task(async function test_cookies_sessions_offlineApps() {
// Check if the newly cleared values are reflected let promiseSanitized = promiseSanitizationComplete();
dh2.onload = async function () {
await validateDataSizes(this); let dh = new DialogHelper();
dh.onload = function () {
this.uncheckAllCheckboxes();
this.checkPrefCheckbox("cookies", true);
this.acceptDialog(); this.acceptDialog();
}; };
dh2.open(); dh.onunload = async function () {
await dh2.promiseClosed; await promiseSanitized;
// Check if form data follows history
boolPrefIs("cpd.formdata", false, `form data pref follows history pref`);
await SiteDataTestUtils.clear(); boolPrefIs("cpd.sessions", true, `sessions pref follows cookies prefs`);
BrowserTestUtils.removeTab(gBrowser.selectedTab);
} boolPrefIs(
"cpd.offlineApps",
true,
`offlineapps pref follows cookies prefs`
);
};
dh.open();
await dh.promiseClosed;
});

Просмотреть файл

@ -327,45 +327,3 @@ function runAllCookiePermissionTests(originAttributes) {
}); });
}); });
} }
function openPreferencesViaOpenPreferencesAPI(aPane, aOptions) {
return new Promise(resolve => {
let finalPrefPaneLoaded = TestUtils.topicObserved(
"sync-pane-loaded",
() => true
);
gBrowser.selectedTab = BrowserTestUtils.addTab(gBrowser, "about:blank");
openPreferences(aPane);
let newTabBrowser = gBrowser.selectedBrowser;
newTabBrowser.addEventListener(
"Initialized",
function () {
newTabBrowser.contentWindow.addEventListener(
"load",
async function () {
let win = gBrowser.contentWindow;
let selectedPane = win.history.state;
await finalPrefPaneLoaded;
if (!aOptions || !aOptions.leaveOpen) {
gBrowser.removeCurrentTab();
}
resolve({ selectedPane });
},
{ once: true }
);
},
{ capture: true, once: true }
);
});
}
async function createDummyDataForHost(host) {
let origin = "https://" + host;
let dummySWURL =
getRootDirectory(gTestPath).replace("chrome://mochitests/content", origin) +
"dummy.js";
await SiteDataTestUtils.addToIndexedDB(origin);
await SiteDataTestUtils.addServiceWorker(dummySWURL);
}

Просмотреть файл

@ -1,29 +0,0 @@
<!DOCTYPE html>
<html manifest="manifest.appcache">
<head>
<meta charset="utf-8">
<meta http-equiv="Cache-Control" content="public" />
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
<title>Site Data Test</title>
</head>
<body>
<h1>Site Data Test</h1>
<script type="text/javascript">
let request = indexedDB.open("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");
store.put({ id: "test_id", description: "Site Data Test"});
tx.oncomplete = () => document.dispatchEvent(new CustomEvent("test-indexedDB-done", {bubbles: true, cancelable: false}));
};
</script>
</body>
</html>

Просмотреть файл

@ -338,12 +338,6 @@ function initTCPStandardSection() {
var gPrivacyPane = { var gPrivacyPane = {
_pane: null, _pane: null,
/**
* Variable that controls when we update sites for the new
* clear history dialog
*/
shouldUpdateSiteUsageDataForSanitizeDialog: false,
/** /**
* Whether the prompt to restart Firefox should appear when changing the autostart pref. * Whether the prompt to restart Firefox should appear when changing the autostart pref.
*/ */
@ -2031,24 +2025,10 @@ var gPrivacyPane = {
* Displays the Clear Private Data settings dialog. * Displays the Clear Private Data settings dialog.
*/ */
showClearPrivateDataSettings() { showClearPrivateDataSettings() {
let dialogFile = useOldClearHistoryDialog
? "chrome://browser/content/preferences/dialogs/sanitize.xhtml"
: "chrome://browser/content/sanitize_v2.xhtml";
gSubDialog.open( gSubDialog.open(
dialogFile, "chrome://browser/content/preferences/dialogs/sanitize.xhtml",
{ { features: "resizable=no" }
features: "resizable=no",
},
{
mode: "clearOnShutdown",
updateUsageData: this.shouldUpdateSiteUsageDataForSanitizeDialog,
}
); );
// Since we've opened this once we should
// update sites within the dialog everytime now
this.shouldUpdateSiteUsageDataForSanitizeDialog = true;
}, },
/** /**
@ -2068,27 +2048,17 @@ var gPrivacyPane = {
? "chrome://browser/content/sanitize.xhtml" ? "chrome://browser/content/sanitize.xhtml"
: "chrome://browser/content/sanitize_v2.xhtml"; : "chrome://browser/content/sanitize_v2.xhtml";
gSubDialog.open( gSubDialog.open(dialogFile, {
dialogFile, features: "resizable=no",
{ closingCallback: () => {
features: "resizable=no", // reset the timeSpan pref
closingCallback: () => { if (aClearEverything) {
// reset the timeSpan pref ts.value = timeSpanOrig;
if (aClearEverything) { }
ts.value = timeSpanOrig;
}
Services.obs.notifyObservers(null, "clear-private-data"); Services.obs.notifyObservers(null, "clear-private-data");
},
}, },
{ });
updateUsageData: this.shouldUpdateSiteUsageDataForSanitizeDialog,
}
);
// Since we've opened this once we should update sites within the
// dialog everytime now to show the most up to date data sizes
this.shouldUpdateSiteUsageDataForSanitizeDialog = true;
}, },
/* /*
@ -2504,25 +2474,9 @@ var gPrivacyPane = {
}, },
clearSiteData() { clearSiteData() {
// We have to use the full path name to avoid getting errors in
// browser/base/content/test/static/browser_all_files_referenced.js
let dialogFile = useOldClearHistoryDialog
? "chrome://browser/content/preferences/dialogs/clearSiteData.xhtml"
: "chrome://browser/content/sanitize_v2.xhtml";
gSubDialog.open( gSubDialog.open(
dialogFile, "chrome://browser/content/preferences/dialogs/clearSiteData.xhtml"
{
features: "resizable=no",
},
{
mode: "clearSiteData",
updateUsageData: this.shouldUpdateSiteUsageDataForSanitizeDialog,
}
); );
// Since we've opened this once we should
// update sites within the dialog everytime now
this.shouldUpdateSiteUsageDataForSanitizeDialog = true;
}, },
/** /**

Просмотреть файл

@ -25,8 +25,6 @@ sanitize-dialog-title-everything =
clear-data-settings-label = When closed, { -brand-short-name } should automatically clear all clear-data-settings-label = When closed, { -brand-short-name } should automatically clear all
sanitize-on-shutdown-description = Automatically clear all checked items when { -brand-short-name } closes.
## clear-time-duration-prefix is followed by a dropdown list, with ## clear-time-duration-prefix is followed by a dropdown list, with
## values localized using clear-time-duration-value-* messages. ## values localized using clear-time-duration-value-* messages.
## clear-time-duration-suffix is left empty in English, but can be ## clear-time-duration-suffix is left empty in English, but can be
@ -78,13 +76,6 @@ item-cookies =
.label = Cookies .label = Cookies
.accesskey = C .accesskey = C
# Variables:
# $amount (Number) - Amount of site data currently stored on disk
# $unit (String) - Abbreviation of the unit that $amount is in, e.g. "MB"
item-cookies-site-data-with-size =
.label = Cookies and site data ({ $amount } { $unit })
.accesskey = e
item-cookies-site-data = item-cookies-site-data =
.label = Cookies and site data .label = Cookies and site data
.accesskey = e .accesskey = e
@ -99,13 +90,6 @@ item-cache =
.label = Cache .label = Cache
.accesskey = a .accesskey = a
# Variables:
# $amount (Number) - Amount of cached data
# $unit (String) - Abbreviation of the unit that $amount is in, e.g. "MB"
item-cached-content-with-size =
.label = Temporary cached files and pages ({ $amount } { $unit })
.accesskey = f
item-cached-content = item-cached-content =
.label = Temporary cached files and pages .label = Temporary cached files and pages
.accesskey = f .accesskey = f
@ -122,15 +106,6 @@ item-site-prefs =
item-site-prefs-description = Resets your permissions and site preferences to original settings item-site-prefs-description = Resets your permissions and site preferences to original settings
# Variables:
# $count (Number) - Number of downloads recorded
item-download-history-with-size =
.label = { $count ->
[one] Downloaded files list ({ $count } file)
*[other] Downloaded files list ({ $count } files)
}
.accesskey = D
item-download-history = item-download-history =
.label = Downloaded files list .label = Downloaded files list
.accesskey = D .accesskey = D
@ -156,9 +131,6 @@ sanitize-button-ok =
sanitize-button-ok2 = sanitize-button-ok2 =
.label = Clear .label = Clear
sanitize-button-ok-on-shutdown =
.label = Save Changes
# The label for the default button between the user clicking it and the window # The label for the default button between the user clicking it and the window
# closing. Indicates the items are being cleared. # closing. Indicates the items are being cleared.
sanitize-button-clearing = sanitize-button-clearing =

Просмотреть файл

@ -85,21 +85,6 @@ export var Sanitizer = {
TIMESPAN_5MIN: 5, TIMESPAN_5MIN: 5,
TIMESPAN_24HOURS: 6, TIMESPAN_24HOURS: 6,
/**
* Mapping time span constants to get total time in ms from the selected
* time spans
*/
timeSpanMsMap: {
TIMESPAN_5MIN: 300000, // 5*60*1000
TIMESPAN_HOUR: 3600000, // 60*60*1000
TIMESPAN_2HOURS: 7200000, // 2*60*60*1000
TIMESPAN_4HOURS: 14400000, // 4*60*60*1000
TIMESPAN_24HOURS: 86400000, // 24*60*60*1000
get TIMESPAN_TODAY() {
return Date.now() - new Date().setHours(0, 0, 0, 0);
}, // time spent today
},
/** /**
* Whether we should sanitize on shutdown. * Whether we should sanitize on shutdown.
* When this is set, a pending sanitization should also be added and removed * When this is set, a pending sanitization should also be added and removed
@ -119,13 +104,9 @@ export var Sanitizer = {
* *
* @param parentWindow the browser window to use as parent for the created * @param parentWindow the browser window to use as parent for the created
* dialog. * dialog.
* @param {string} mode - flag to let the dialog know if it is opened
* using the clear on shutdown (clearOnShutdown) settings option
* in about:preferences or in a clear site data context (clearSiteData)
*
* @throws if parentWindow is undefined or doesn't have a gDialogBox. * @throws if parentWindow is undefined or doesn't have a gDialogBox.
*/ */
showUI(parentWindow, mode) { showUI(parentWindow) {
// Treat the hidden window as not being a parent window: // Treat the hidden window as not being a parent window:
if ( if (
parentWindow?.document.documentURI == parentWindow?.document.documentURI ==
@ -141,7 +122,6 @@ export var Sanitizer = {
if (parentWindow?.gDialogBox) { if (parentWindow?.gDialogBox) {
parentWindow.gDialogBox.open(`chrome://browser/content/${dialogFile}`, { parentWindow.gDialogBox.open(`chrome://browser/content/${dialogFile}`, {
inBrowserWindow: true, inBrowserWindow: true,
mode,
}); });
} else { } else {
Services.ww.openWindow( Services.ww.openWindow(
@ -149,7 +129,7 @@ export var Sanitizer = {
`chrome://browser/content/${dialogFile}`, `chrome://browser/content/${dialogFile}`,
"Sanitize", "Sanitize",
"chrome,titlebar,dialog,centerscreen,modal", "chrome,titlebar,dialog,centerscreen,modal",
{ needNativeUI: true, mode } { needNativeUI: true }
); );
} }
}, },

Просмотреть файл

@ -16,11 +16,6 @@ ChromeUtils.defineLazyGetter(lazy, "gBrandBundle", function () {
); );
}); });
ChromeUtils.defineESModuleGetters(lazy, {
DownloadHistory: "resource://gre/modules/DownloadHistory.sys.mjs",
Sanitizer: "resource:///modules/Sanitizer.sys.mjs",
});
export var SiteDataManager = { export var SiteDataManager = {
// A Map of sites and their disk usage according to Quota Manager. // A Map of sites and their disk usage according to Quota Manager.
// Key is base domain (group sites based on base domain across scheme, port, // Key is base domain (group sites based on base domain across scheme, port,
@ -112,37 +107,6 @@ export var SiteDataManager = {
return site; return site;
}, },
/**
* Insert site with specific params into the SiteDataManager
* Currently used for testing purposes
*
* @param {String} baseDomainOrHost
* @param {Object} Site info params
* @returns {Object} site object
*/
_testInsertSite(
baseDomainOrHost,
{
cookies = [],
persisted = false,
quotaUsage = 0,
lastAccessed = 0,
principals = [],
}
) {
let site = {
baseDomainOrHost,
cookies,
persisted,
quotaUsage,
lastAccessed,
principals,
};
this._sites.set(baseDomainOrHost, site);
return site;
},
_getOrInsertContainersData(site, userContextId) { _getOrInsertContainersData(site, userContextId) {
if (!site.containersData) { if (!site.containersData) {
site.containersData = new Map(); site.containersData = new Map();
@ -365,12 +329,6 @@ export var SiteDataManager = {
return false; return false;
}, },
/**
* Fetches total quota usage
* This method assumes that siteDataManager.updateSites has been called externally
*
* @returns total quota usage
*/
getTotalUsage() { getTotalUsage() {
return this._getQuotaUsagePromise.then(() => { return this._getQuotaUsagePromise.then(() => {
let usage = 0; let usage = 0;
@ -381,75 +339,6 @@ export var SiteDataManager = {
}); });
}, },
/**
*
* Fetch quota usage for all time ranges to display in the clear data dialog.
* This method assumes that SiteDataManager.updateSites has been called externally
*
* @param {string[]} timeSpanArr - Array of timespan options to get quota usage
* from Sanitizer, e.g. ["TIMESPAN_HOUR", "TIMESPAN_2HOURS"]
* @returns {Object} bytes used for each timespan
*/
async getQuotaUsageForTimeRanges(timeSpanArr) {
let usage = {};
await this._getQuotaUsagePromise;
for (let timespan of timeSpanArr) {
usage[timespan] = 0;
}
let timeNow = Date.now();
for (let site of this._sites.values()) {
let lastAccessed = new Date(site.lastAccessed / 1000);
for (let timeSpan of timeSpanArr) {
let compareTime = new Date(
timeNow - lazy.Sanitizer.timeSpanMsMap[timeSpan]
);
if (timeSpan === "TIMESPAN_EVERYTHING") {
usage[timeSpan] += site.quotaUsage;
} else if (lastAccessed >= compareTime) {
usage[timeSpan] += site.quotaUsage;
}
}
}
return usage;
},
/**
* Fetches number of downloads for all timespans in timeSpanArr
*
* @param {String[]} timeSpanArr - Array of timespan options to get downloads count
* from Sanitizer, e.g. ["TIMESPAN_HOUR", "TIMESPAN_2HOURS"]
* @returns {Object} downloads counted for each timespan
*/
async getDownloadCountForTimeRanges(timeSpanArr) {
let downloads = await lazy.DownloadHistory.getList();
let downloadSizes = {};
timeSpanArr.forEach(timespan => {
downloadSizes[timespan] = 0;
});
let timeNow = Date.now();
for (let download of downloads._downloads) {
let startTime = new Date(download.startTime);
for (let timeSpan of timeSpanArr) {
let compareTime = new Date(
timeNow - lazy.Sanitizer.timeSpanMsMap[timeSpan]
);
if (timeSpan === "TIMESPAN_EVERYTHING") {
downloadSizes[timeSpan] += 1;
} else if (startTime >= compareTime) {
downloadSizes[timeSpan] += 1;
}
}
}
return downloadSizes;
},
/** /**
* Gets all sites that are currently storing site data. Entries are grouped by * Gets all sites that are currently storing site data. Entries are grouped by
* parent base domain if applicable. For example "foo.example.com", * parent base domain if applicable. For example "foo.example.com",

Просмотреть файл

@ -3,37 +3,19 @@
*/ */
"use strict"; "use strict";
ChromeUtils.defineESModuleGetters(this, { const { SiteDataManager } = ChromeUtils.importESModule(
SiteDataManager: "resource:///modules/SiteDataManager.sys.mjs", "resource:///modules/SiteDataManager.sys.mjs"
SiteDataTestUtils: "resource://testing-common/SiteDataTestUtils.sys.mjs", );
PermissionTestUtils: "resource://testing-common/PermissionTestUtils.sys.mjs", const { SiteDataTestUtils } = ChromeUtils.importESModule(
Downloads: "resource://gre/modules/Downloads.sys.mjs", "resource://testing-common/SiteDataTestUtils.sys.mjs"
FileTestUtils: "resource://testing-common/FileTestUtils.sys.mjs", );
Sanitizer: "resource:///modules/Sanitizer.sys.mjs", const { PermissionTestUtils } = ChromeUtils.importESModule(
}); "resource://testing-common/PermissionTestUtils.sys.mjs"
);
const TEST_DOWNLOAD_FILE_NAME = "test-download.txt";
let fileURL;
let downloadList;
var nowMs = Date.now();
const hoursTodayInMs = new Date() - new Date(new Date().setHours(0, 0, 0, 0));
const EXAMPLE_ORIGIN = "https://www.example.com"; const EXAMPLE_ORIGIN = "https://www.example.com";
const EXAMPLE_ORIGIN_2 = "https://example.org"; const EXAMPLE_ORIGIN_2 = "https://example.org";
const EXAMPLE_ORIGIN_3 = "http://localhost:8000"; const EXAMPLE_ORIGIN_3 = "http://localhost:8000";
const EXAMPLE_ORIGIN_4 = "http://localhost:3000";
const EXAMPLE_ORIGIN_5 = "http://example.net";
const TIMESPANS = [
"TIMESPAN_HOUR",
"TIMESPAN_2HOURS",
"TIMESPAN_4HOURS",
"TIMESPAN_TODAY",
"TIMESPAN_EVERYTHING",
];
let oneHourInMs = 60 * 60 * 1000;
let today = nowMs - new Date().setHours(0, 0, 0, 0);
let p = let p =
Services.scriptSecurityManager.createContentPrincipalFromOrigin( Services.scriptSecurityManager.createContentPrincipalFromOrigin(
@ -48,104 +30,6 @@ let EXAMPLE_ORIGIN_2_PARTITIONED =
} }
).origin; ).origin;
/**
* Created a temporary file URL to add to downloads
*
* @returns {Object} file URL
*/
function createDownloadFileURL() {
if (!fileURL) {
let file = Services.dirsvc.get("TmpD", Ci.nsIFile);
file.append("foo.txt");
file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o600);
fileURL = Services.io.newFileURI(file);
}
return fileURL;
}
/**
* Creates a new download list to populate
*
* @returns download list to update
*/
async function createDownloadList() {
if (!downloadList) {
Downloads._promiseListsInitialized = null;
Downloads._lists = {};
Downloads._summaries = {};
downloadList = await Downloads.getList(Downloads.ALL);
}
return downloadList;
}
/**
* Add sites through the site data manager based on the site last accessed array
*
* @param {number[]} siteLastAccessedArr - array of time's when the site was last accessed
* e.g. [2, 2, 4, 24 ...]
* We currently do not have a 24 hour option in the dialog, so we convert 24 to today
* @param {Object} testSiteUsageDataObj - Object to populate and update
* @returns testSiteUsageData Object with the quota usage for each timespan
*/
async function addSitesWithLastAccessed(
siteLastAccessedArr,
testSiteUsageDataObj
) {
let SITE_ORIGINS = [
EXAMPLE_ORIGIN,
EXAMPLE_ORIGIN_2,
EXAMPLE_ORIGIN_5,
EXAMPLE_ORIGIN_3,
EXAMPLE_ORIGIN_4,
EXAMPLE_ORIGIN_2_PARTITIONED,
];
let staticUsage = 4096;
// Add a time buffer so the site access falls within the time range
const buffer = 100000;
// Change lastAccessed of sites
for (let index = 0; index < siteLastAccessedArr.length; index++) {
testSiteUsageDataObj[siteLastAccessedArr[index]] += staticUsage;
// subtract 1 to make sure the added site is within the time range
let lastAccessedTime = Sanitizer.timeSpanMsMap[siteLastAccessedArr[index]];
let site = SiteDataManager._testInsertSite(SITE_ORIGINS[index], {
quotaUsage: staticUsage,
lastAccessed: (nowMs - lastAccessedTime + buffer) * 1000,
});
Assert.ok(
site,
`Site added successfully with last accessed ${new Date(
site.lastAccessed
)}`
);
}
let cumulativeSum = 0;
for (let key in testSiteUsageDataObj) {
cumulativeSum += testSiteUsageDataObj[key];
testSiteUsageDataObj[key] = cumulativeSum;
}
// account for items being added within today that overlap other time ranges
// this is to account for edge cases for when this test might be run near after midnight
// We only care about the timespans until TIMESPAN_TODAY (i<3)
if (hoursTodayInMs < Sanitizer.timeSpanMsMap.TIMESPAN_HOUR) {
testSiteUsageDataObj.TIMESPAN_HOUR += testSiteUsageDataObj.TIMESPAN_TODAY;
}
if (hoursTodayInMs < Sanitizer.timeSpanMsMap.TIMESPAN_2HOURS) {
testSiteUsageDataObj.TIMESPAN_2HOURS += testSiteUsageDataObj.TIMESPAN_TODAY;
}
if (hoursTodayInMs < Sanitizer.timeSpanMsMap.TIMESPAN_4HOURS) {
testSiteUsageDataObj.TIMESPAN_4HOURS += testSiteUsageDataObj.TIMESPAN_TODAY;
}
return testSiteUsageDataObj;
}
add_task(function setup() { add_task(function setup() {
do_get_profile(); do_get_profile();
}); });
@ -391,181 +275,3 @@ add_task(async function testRemoveSiteData() {
PermissionTestUtils.remove(uri, "camera"); PermissionTestUtils.remove(uri, "camera");
}); });
add_task(async function testDownloadDataSizeByRange() {
Services.prefs.setBoolPref("privacy.cpd.downloads", true);
let url = createDownloadFileURL();
let list = await createDownloadList();
let testSizes = [3, 1, 2, 2, 2];
let timeMultiplier = [0.5, 2, 4, 24, 56];
// Add a time buffer so the download falls within the time range
let buffer = 100000;
let totalItems = 0;
for (let i = 0; i < testSizes.length; i++) {
totalItems += testSizes[i];
let setTime = nowMs - oneHourInMs * timeMultiplier[i] + buffer;
if (timeMultiplier[i] === 24) {
setTime = nowMs - today + buffer;
}
// Add downloads to downloads list
for (let j = 0; j < testSizes[i]; j++) {
let download = await Downloads.createDownload({
source: { url: url.spec, isPrivate: false },
target: {
path: FileTestUtils.getTempFile(TEST_DOWNLOAD_FILE_NAME).path,
},
startTime: {
getTime: _ => {
return setTime;
},
},
});
Assert.ok(
!!download,
`The download for ${timeMultiplier[i]} was created successfully!`
);
list.add(download);
}
}
let items = await list.getAll();
Assert.equal(items.length, totalItems, "Items were added to the list");
let rangedSize = await SiteDataManager.getDownloadCountForTimeRanges(
TIMESPANS
);
let compareSizes = [0, 0, 0, 0, 0];
// account for items being added within today that overlap other time ranges
// this is to account for edge cases for when this test might be run near after midnight
// we only care about i = 3 since that is the index where TIMESPAN_TODAY lives
if (hoursTodayInMs < Sanitizer.timeSpanMsMap.TIMESPAN_HOUR) {
compareSizes[0] += testSizes[3];
}
if (hoursTodayInMs < Sanitizer.timeSpanMsMap.TIMESPAN_2HOURS) {
compareSizes[1] += testSizes[3];
}
if (hoursTodayInMs < Sanitizer.timeSpanMsMap.TIMESPAN_4HOURS) {
compareSizes[2] += testSizes[3];
}
// add all the sizes to reflect total size for a range
for (let max = 0; max < testSizes.length; max++) {
for (let i = 0; i <= max; i++) {
compareSizes[max] += testSizes[i];
}
}
// check the timerange array against the expected sizes
// we use TIMESPANS[] to get the key for rangedSize we are comparing
for (let i = 0; i < testSizes.length; i++) {
Assert.equal(
compareSizes[i],
rangedSize[TIMESPANS[i]],
"Checking time range array"
);
}
// Clear last 4 hours
Services.prefs.setIntPref(Sanitizer.PREF_TIMESPAN, Sanitizer.TIMESPAN_4HOURS);
await Sanitizer.sanitize(null, { ignoreTimespan: false });
// reset testsizes
testSizes[0] = 0;
testSizes[1] = 0;
testSizes[2] = 0;
rangedSize = await SiteDataManager.getDownloadCountForTimeRanges(TIMESPANS);
compareSizes = [0, 0, 0, 0, 0];
// account for items being added within today that overlap other time ranges
// this is to account for edge cases for when this test might be run near after midnight
// we only care about i = 3 since that is the index where TIMESPAN_TODAY lives
if (hoursTodayInMs < Sanitizer.timeSpanMsMap.TIMESPAN_HOUR) {
compareSizes[0] += testSizes[3];
}
if (hoursTodayInMs < Sanitizer.timeSpanMsMap.TIMESPAN_2HOURS) {
compareSizes[1] += testSizes[3];
}
if (hoursTodayInMs < Sanitizer.timeSpanMsMap.TIMESPAN_4HOURS) {
compareSizes[2] += testSizes[3];
}
// add all the sizes to reflect total size for a range
for (let max = 0; max < testSizes.length; max++) {
for (let i = 0; i <= max; i++) {
compareSizes[max] += testSizes[i];
}
}
// check the timerange array against the expected sizes
// we use TIMESPANS[] to get the key for rangedSize we are comparing
for (let i = 0; i < testSizes.length; i++) {
Assert.equal(
compareSizes[i],
rangedSize[TIMESPANS[i]],
"Checking time range array"
);
}
// Clear all downloads
await new Promise(resolve => {
Services.clearData.deleteData(
Ci.nsIClearDataService.CLEAR_DOWNLOADS,
value => {
Assert.equal(value, 0);
resolve();
}
);
});
items = await list.getAll();
Assert.equal(items.length, 0, "Delete all downloaded items for test");
});
add_task(async function testGetQuotaUsageByRange() {
await SiteDataManager.updateSites();
let sites = await SiteDataManager.getSites();
Assert.equal(sites.length, 0, "SiteDataManager is empty");
let testSiteUsageData = {
TIMESPAN_HOUR: 0,
TIMESPAN_2HOURS: 0,
TIMESPAN_4HOURS: 0,
TIMESPAN_TODAY: 0,
TIMESPAN_EVERYTHING: 0,
};
testSiteUsageData = await addSitesWithLastAccessed(
[
"TIMESPAN_HOUR",
"TIMESPAN_2HOURS",
"TIMESPAN_2HOURS",
"TIMESPAN_4HOURS",
"TIMESPAN_TODAY",
"TIMESPAN_EVERYTHING",
],
testSiteUsageData
);
let usageObj = await SiteDataManager.getQuotaUsageForTimeRanges(TIMESPANS);
let index = 0;
for (let key in testSiteUsageData) {
Assert.equal(
usageObj[TIMESPANS[index]],
testSiteUsageData[key],
`Usage data is correct for ${key} hrs`
);
index++;
}
await SiteDataTestUtils.clear();
});

Просмотреть файл

@ -58,18 +58,6 @@
margin-inline-end: 0; margin-inline-end: 0;
} }
dialog:not([inClearOnShutdown]) #SanitizeOnShutdownDescription {
display: none;
}
dialog[inClearOnShutdown] #SanitizeDurationBox {
display: none;
}
dialog[inClearOnShutdown] #SanitizeOnShutdownDescription {
display: block;
}
dialog:not([inbrowserwindow]) #titleText { dialog:not([inbrowserwindow]) #titleText {
display: none; display: none;
} }