Bug 1386684 - Enable ESLint for toolkit/components/url-classifier (automatic fixes). r=hchang

MozReview-Commit-ID: F0Z8dRaYOku

--HG--
extra : rebase_source : 3ebc9ab6ea9f1741d8a986c9217575644411e2a1
This commit is contained in:
Dan Banner 2017-08-02 16:12:07 +01:00
parent 414b33cce2
commit 436f06fda4
46 changed files with 658 additions and 721 deletions

View file

@ -340,9 +340,6 @@ toolkit/components/workerloader/tests/moduleF-syntax-error.js
# Tests old non-star function generators
toolkit/modules/tests/xpcshell/test_task.js
# Not yet updated
toolkit/components/url-classifier/**
# External code:
toolkit/components/microformats/test/**
toolkit/components/microformats/microformat-shiv.js

View file

@ -55,7 +55,7 @@ const tablePreferences = [
this.SafeBrowsing = {
init: function() {
init() {
if (this.initialized) {
log("Already initialized");
return;
@ -75,7 +75,7 @@ this.SafeBrowsing = {
log("init() finished");
},
registerTableWithURLs: function(listname) {
registerTableWithURLs(listname) {
let listManager = Cc["@mozilla.org/url-classifier/listmanager;1"].
getService(Ci.nsIUrlListManager);
@ -96,7 +96,7 @@ this.SafeBrowsing = {
listManager.registerTable(listname, providerName, provider.updateURL, provider.gethashURL);
},
registerTables: function() {
registerTables() {
for (let i = 0; i < this.phishingLists.length; ++i) {
this.registerTableWithURLs(this.phishingLists[i]);
}
@ -151,7 +151,7 @@ this.SafeBrowsing = {
reportURL: null,
getReportURL: function(kind, info) {
getReportURL(kind, info) {
let pref;
switch (kind) {
case "Phish":
@ -187,7 +187,7 @@ this.SafeBrowsing = {
return reportUrl;
},
observe: function(aSubject, aTopic, aData) {
observe(aSubject, aTopic, aData) {
// skip nextupdatetime and lastupdatetime
if (aData.indexOf("lastupdatetime") >= 0 || aData.indexOf("nextupdatetime") >= 0) {
return;
@ -201,7 +201,7 @@ this.SafeBrowsing = {
this.readPrefs();
},
readPrefs: function() {
readPrefs() {
loggingEnabled = Services.prefs.getBoolPref(PREF_DEBUG_ENABLED);
log("reading prefs");
@ -249,7 +249,7 @@ this.SafeBrowsing = {
},
updateProviderURLs: function() {
updateProviderURLs() {
try {
var clientID = Services.prefs.getCharPref("browser.safebrowsing.id");
} catch (e) {
@ -318,7 +318,7 @@ this.SafeBrowsing = {
}, this);
},
controlUpdateChecking: function() {
controlUpdateChecking() {
log("phishingEnabled:", this.phishingEnabled, "malwareEnabled:",
this.malwareEnabled, "trackingEnabled:", this.trackingEnabled,
"blockedEnabled:", this.blockedEnabled, "trackingAnnotations",
@ -395,7 +395,7 @@ this.SafeBrowsing = {
},
addMozEntries: function() {
addMozEntries() {
// Add test entries to the DB.
// XXX bug 779008 - this could be done by DB itself?
const phishURL = "itisatrap.org/firefox/its-a-trap.html";
@ -440,14 +440,14 @@ this.SafeBrowsing = {
// nsIUrlClassifierUpdateObserver
let dummyListener = {
updateUrlRequested: function() { },
streamFinished: function() { },
updateUrlRequested() { },
streamFinished() { },
// We notify observers when we're done in order to be able to make perf
// test results more consistent
updateError: function() {
updateError() {
Services.obs.notifyObservers(db, "mozentries-update-finished", "error");
},
updateSuccess: function() {
updateSuccess() {
Services.obs.notifyObservers(db, "mozentries-update-finished", "success");
}
};

View file

@ -21,13 +21,13 @@ Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/NetUtil.jsm");
XPCOMUtils.defineLazyServiceGetter(this, 'gDbService',
'@mozilla.org/url-classifier/dbservice;1',
'nsIUrlClassifierDBService');
XPCOMUtils.defineLazyServiceGetter(this, "gDbService",
"@mozilla.org/url-classifier/dbservice;1",
"nsIUrlClassifierDBService");
XPCOMUtils.defineLazyServiceGetter(this, 'gUrlUtil',
'@mozilla.org/url-classifier/utils;1',
'nsIUrlClassifierUtils');
XPCOMUtils.defineLazyServiceGetter(this, "gUrlUtil",
"@mozilla.org/url-classifier/utils;1",
"nsIUrlClassifierUtils");
let loggingEnabled = false;
@ -147,7 +147,7 @@ function httpStatusToBucket(httpStatus) {
break;
default:
statusBucket = 15;
};
}
return statusBucket;
}
@ -240,7 +240,7 @@ HashCompleter.prototype = {
// This is called after several calls to |complete|, or after the
// currentRequest has finished. It starts off the HTTP request by making a
// |begin| call to the HashCompleterRequest.
run: function() {
run() {
// Clear everything on shutdown
if (this._shuttingDown) {
this._currentRequest = null;
@ -273,13 +273,13 @@ HashCompleter.prototype = {
// Pass the server response status to the RequestBackoff for the given
// gethashUrl and fetch the next pending request, if there is one.
finishRequest: function(url, aStatus) {
finishRequest(url, aStatus) {
this._backoffs[url].noteServerResponse(aStatus);
Services.tm.dispatchToMainThread(this);
},
// Returns true if we can make a request from the given url, false otherwise.
canMakeRequest: function(aGethashUrl) {
canMakeRequest(aGethashUrl) {
return this._backoffs[aGethashUrl].canMakeRequest() &&
Date.now() >= this._nextGethashTimeMs[aGethashUrl];
},
@ -287,7 +287,7 @@ HashCompleter.prototype = {
// Notifies the RequestBackoff of a new request so we can throttle based on
// max requests/time period. This must be called before a channel is opened,
// and finishRequest must be called once the response is received.
noteRequest: function(aGethashUrl) {
noteRequest(aGethashUrl) {
return this._backoffs[aGethashUrl].noteRequest();
},
@ -343,13 +343,13 @@ HashCompleterRequest.prototype = {
});
if (aTableName) {
let isTableNameV4 = aTableName.endsWith('-proto');
let isTableNameV4 = aTableName.endsWith("-proto");
if (0 === this.tableNames.size) {
// Decide if this request is v4 by the first added partial hash.
this.isV4 = isTableNameV4;
} else if (this.isV4 !== isTableNameV4) {
log('ERROR: Cannot mix "proto" tables with other types within ' +
'the same gethash URL.');
"the same gethash URL.");
}
this.tableNames.set(aTableName);
@ -403,8 +403,7 @@ HashCompleterRequest.prototype = {
// Notify the RequestBackoff if opening the channel succeeded. At this
// point, finishRequest must be called.
this._completer.noteRequest(this.gethashUrl);
}
catch (err) {
} catch (err) {
this.notifyFailure(err);
throw err;
}
@ -490,8 +489,8 @@ HashCompleterRequest.prototype = {
this._requests.forEach(r => prefixSet.add(btoa(r.partialHash)));
let prefixArray = Array.from(prefixSet).sort();
log("Build v4 gethash request with " + JSON.stringify(tableNameArray) + ', '
+ JSON.stringify(stateArray) + ', '
log("Build v4 gethash request with " + JSON.stringify(tableNameArray) + ", "
+ JSON.stringify(stateArray) + ", "
+ JSON.stringify(prefixArray));
return gUrlUtil.makeFindFullHashRequestV4(tableNameArray,
@ -522,7 +521,7 @@ HashCompleterRequest.prototype = {
body = PARTIAL_LENGTH + ":" + (PARTIAL_LENGTH * prefixes.length) +
"\n" + prefixes.join("");
log('Requesting completions for ' + prefixes.length + ' ' + PARTIAL_LENGTH + '-byte prefixes: ' + body);
log("Requesting completions for " + prefixes.length + " " + PARTIAL_LENGTH + "-byte prefixes: " + body);
return body;
},
@ -644,7 +643,7 @@ HashCompleterRequest.prototype = {
let addChunk = parseInt(entries[1]);
let dataLength = parseInt(entries[2]);
log('Response includes add chunks for ' + list + ': ' + addChunk);
log("Response includes add chunks for " + list + ": " + addChunk);
if (dataLength % COMPLETE_LENGTH != 0 ||
dataLength == 0 ||
dataLength > body.length - (newlineIndex + 1)) {
@ -761,7 +760,7 @@ HashCompleterRequest.prototype = {
}
}
let success = Components.isSuccessCode(aStatusCode);
log('Received a ' + httpStatus + ' status code from the gethash server (success=' + success + ').');
log("Received a " + httpStatus + " status code from the gethash server (success=" + success + ").");
Services.telemetry.getKeyedHistogramById("URLCLASSIFIER_COMPLETE_REMOTE_STATUS2").
add(this.telemetryProvider, httpStatusToBucket(httpStatus));
@ -779,8 +778,7 @@ HashCompleterRequest.prototype = {
if (success) {
try {
this.handleResponse();
}
catch (err) {
} catch (err) {
log(err.stack);
aStatusCode = err.value;
success = false;

View file

@ -213,8 +213,7 @@ PROT_ListManager.prototype.requireTableUpdates = function() {
* Set timer to check update after delay
*/
PROT_ListManager.prototype.setUpdateCheckTimer = function(updateUrl,
delay)
{
delay) {
this.updateCheckers_[updateUrl] = Cc["@mozilla.org/timer;1"]
.createInstance(Ci.nsITimer);
this.updateCheckers_[updateUrl].initWithCallback(() => {
@ -225,8 +224,7 @@ PROT_ListManager.prototype.setUpdateCheckTimer = function (updateUrl,
/**
* Acts as a nsIUrlClassifierCallback for getTables.
*/
PROT_ListManager.prototype.kickoffUpdate_ = function (onDiskTableData)
{
PROT_ListManager.prototype.kickoffUpdate_ = function(onDiskTableData) {
this.startingUpdate_ = false;
var initialUpdateDelay = 3000;
// Add a fuzz of 0-1 minutes for both v2 and v4 according to Bug 1305478.
@ -371,13 +369,13 @@ PROT_ListManager.prototype.makeUpdateRequest_ = function(updateUrl, tableData) {
// Check if |updateURL| is for 'proto'. (only v4 uses protobuf for now.)
// We use the table name 'goog-*-proto' and an additional provider "google4"
// to describe the v4 settings.
let isCurTableProto = tableName.endsWith('-proto');
let isCurTableProto = tableName.endsWith("-proto");
if (!onceThru) {
useProtobuf = isCurTableProto;
onceThru = true;
} else if (useProtobuf !== isCurTableProto) {
log('ERROR: Cannot mix "proto" tables with other types ' +
'within the same provider.');
"within the same provider.");
}
if (this.needsUpdate_[this.tablesData[tableName].updateUrl][tableName]) {
@ -648,13 +646,12 @@ function Init() {
modScope.Init = function() {};
}
function RegistrationData()
{
function RegistrationData() {
}
RegistrationData.prototype = {
classID: Components.ID("{ca168834-cc00-48f9-b83c-fd018e58cae3}"),
_xpcom_factory: {
createInstance: function(outer, iid) {
createInstance(outer, iid) {
if (outer != null)
throw Components.results.NS_ERROR_NO_AGGREGATION;
Init();

View file

@ -97,7 +97,7 @@ this.UrlClassifierTestUtils = {
updateUrlRequested: url => { },
streamFinished: status => { },
updateError: errorCode => {
reject('Got updateError when updating ' + table.name);
reject("Got updateError when updating " + table.name);
},
updateSuccess: requestedTimeout => {
resolve();
@ -111,7 +111,7 @@ this.UrlClassifierTestUtils = {
dbService.finishStream();
dbService.finishUpdate();
} catch (e) {
reject('Failed to update with dbService: ' + table.name);
reject("Failed to update with dbService: " + table.name);
}
});
},

View file

@ -53,16 +53,14 @@ classifierHelper.waitForInit = function() {
}, "mozentries-update-finished");
let listener = {
QueryInterface: function(iid)
{
QueryInterface(iid) {
if (iid.equals(Ci.nsISupports) ||
iid.equals(Ci.nsIUrlClassifierUpdateObserver))
return this;
throw Cr.NS_ERROR_NO_INTERFACE;
},
handleEvent: function(value)
{
handleEvent(value) {
if (value === table) {
resolve();
}
@ -146,20 +144,19 @@ classifierHelper._update = function(update) {
try {
await new Promise((resolve, reject) => {
let listener = {
QueryInterface: function(iid)
{
QueryInterface(iid) {
if (iid.equals(Ci.nsISupports) ||
iid.equals(Ci.nsIUrlClassifierUpdateObserver))
return this;
throw Cr.NS_ERROR_NO_INTERFACE;
},
updateUrlRequested: function(url) { },
streamFinished: function(status) { },
updateError: function(errorCode) {
updateUrlRequested(url) { },
streamFinished(status) { },
updateError(errorCode) {
reject(errorCode);
},
updateSuccess: function(requestedTimeout) {
updateSuccess(requestedTimeout) {
resolve();
}
};

View file

@ -48,7 +48,7 @@ var classifierTester = {
}
],
setPrefs: function ({setDBs = true, flashBlockEnable = true, flashSetting = classifierTester.ALWAYS_ACTIVATE_PREF_VALUE} = {}) {
setPrefs({setDBs = true, flashBlockEnable = true, flashSetting = classifierTester.ALWAYS_ACTIVATE_PREF_VALUE} = {}) {
if (setDBs) {
let DBs = [];
@ -69,7 +69,7 @@ var classifierTester = {
Services.prefs.setBoolPref(classifierTester.ALLOW_CTA_PREF, true);
},
unsetPrefs: function () {
unsetPrefs() {
for (let dbData of classifierTester.dbUrls) {
Services.prefs.clearUserPref(dbData.pref);
}
@ -184,7 +184,7 @@ var classifierTester = {
// Returns null if this value should not be verified given the combination
// of inputs
expectedPluginFallbackType: function (classification, flashSetting) {
expectedPluginFallbackType(classification, flashSetting) {
switch (classification) {
case "unknown":
if (flashSetting == classifierTester.ALWAYS_ACTIVATE_PREF_VALUE) {
@ -208,7 +208,7 @@ var classifierTester = {
// Returns null if this value should not be verified given the combination
// of inputs
expectedActivated: function (classification, flashSetting) {
expectedActivated(classification, flashSetting) {
switch (classification) {
case "unknown":
return (flashSetting == classifierTester.ALWAYS_ACTIVATE_PREF_VALUE);
@ -222,7 +222,7 @@ var classifierTester = {
// Returns null if this value should not be verified given the combination
// of inputs
expectedHasRunningPlugin: function (classification, flashSetting) {
expectedHasRunningPlugin(classification, flashSetting) {
switch (classification) {
case "unknown":
return (flashSetting == classifierTester.ALWAYS_ACTIVATE_PREF_VALUE);
@ -236,9 +236,9 @@ var classifierTester = {
// Returns null if this value should not be verified given the combination
// of inputs
expectedPluginListed: function (classification, flashSetting) {
expectedPluginListed(classification, flashSetting) {
if (flashSetting == classifierTester.ASK_TO_ACTIVATE_PREF_VALUE &&
Services.prefs.getCharPref('plugins.navigator.hidden_ctp_plugin') == "Shockwave Flash") {
Services.prefs.getCharPref("plugins.navigator.hidden_ctp_plugin") == "Shockwave Flash") {
return false;
}
switch (classification) {
@ -251,7 +251,7 @@ var classifierTester = {
throw new Error("Invalid classification or flash setting");
},
buildTestCaseInNewTab: function (browser, testCase) {
buildTestCaseInNewTab(browser, testCase) {
return (async function() {
let iframeDomains = testCase.domains.slice();
let pageDomain = iframeDomains.shift();
@ -265,7 +265,7 @@ var classifierTester = {
let url = domain + classifierTester.URL_PATH + "?date=" + Date.now() + "rand=" + Math.random();
let domainLoaded = BrowserTestUtils.browserLoaded(tab.linkedBrowser, true, url);
ContentTask.spawn(tab.linkedBrowser, {iframeId: classifierTester.IFRAME_ID, url: url, depth: depth},
ContentTask.spawn(tab.linkedBrowser, {iframeId: classifierTester.IFRAME_ID, url, depth},
async function({iframeId, url, depth}) {
let doc = content.document;
for (let i = 0; i < depth; ++i) {
@ -281,9 +281,9 @@ var classifierTester = {
})();
},
getPluginInfo: function (browser, depth) {
getPluginInfo(browser, depth) {
return ContentTask.spawn(browser,
{iframeId: classifierTester.IFRAME_ID, depth: depth},
{iframeId: classifierTester.IFRAME_ID, depth},
async function({iframeId, depth}) {
let doc = content.document;
let win = content.window;
@ -307,7 +307,7 @@ var classifierTester = {
});
},
checkPluginInfo: function (pluginInfo, expectedClassification, flashSetting) {
checkPluginInfo(pluginInfo, expectedClassification, flashSetting) {
is(pluginInfo.flashClassification, expectedClassification,
"Page's classification should match expected");

View file

@ -88,21 +88,21 @@ v.addEventListener("error", function() {
var newScript = document.createElement("script");
newScript.id = "badscript2";
newScript.src = "http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/evil.js";
newScript.addEventListener("load", function onload() {scriptItem2 = 'spoiled';});
newScript.addEventListener("load", function onload() { scriptItem2 = "spoiled"; });
document.body.appendChild(newScript);
// / Try loading from a tracking image URI (2)
var newImage = document.createElement("img");
newImage.id = "badimage2";
newImage.src = "http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/raptor.jpg";
newImage.addEventListener("load", function onload() {imageItem2 = 'spoiled'});
newImage.addEventListener("load", function onload() { imageItem2 = "spoiled" });
document.body.appendChild(newImage);
// Try loading from a tracking iframe URI (2)
var newFrame = document.createElement("iframe");
newFrame.id = "badframe2";
newFrame.src = "http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/track.html"
newFrame.addEventListener("load", function onload() {frameItem2 = 'spoiled'});
newFrame.addEventListener("load", function onload() { frameItem2 = "spoiled" });
document.body.appendChild(newFrame);
// Try doing an XHR against a tracking domain (bug 1216793)

View file

@ -157,18 +157,18 @@ newScript.src = "http://tracking.example.com/tests/toolkit/components/url-classi
newScript.addEventListener("load", function() { scriptItem2 = scriptItem; });
document.body.appendChild(newScript);
/// Try loading from a tracking image URI (2)
// Try loading from a tracking image URI (2)
var newImage = document.createElement("img");
newImage.id = "badimage2";
newImage.src = "http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/raptor.jpg?reload=true";
newImage.addEventListener("load", function() {imageItem2 = 'spoiled'});
newImage.addEventListener("load", function() { imageItem2 = "spoiled" });
document.body.appendChild(newImage);
// Try loading from a tracking iframe URI (2)
var newFrame = document.createElement("iframe");
newFrame.id = "badframe2";
newFrame.src = "http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/track.html"
newFrame.addEventListener("load", function() {frameItem2 = 'spoiled'});
newFrame.addEventListener("load", function() { frameItem2 = "spoiled" });
document.body.appendChild(newFrame);
// Try doing an XHR against a tracking domain (bug 1216793)

View file

@ -16,20 +16,19 @@ function setTimeout(callback, delay) {
function doUpdate(update) {
let listener = {
QueryInterface: function(iid)
{
QueryInterface(iid) {
if (iid.equals(Ci.nsISupports) ||
iid.equals(Ci.nsIUrlClassifierUpdateObserver))
return this;
throw Cr.NS_ERROR_NO_INTERFACE;
},
updateUrlRequested: function(url) { },
streamFinished: function(status) { },
updateError: function(errorCode) {
updateUrlRequested(url) { },
streamFinished(status) { },
updateError(errorCode) {
sendAsyncMessage("updateError", errorCode);
},
updateSuccess: function(requestedTimeout) {
updateSuccess(requestedTimeout) {
sendAsyncMessage("updateSuccess");
}
};
@ -84,16 +83,14 @@ function waitForInit() {
iosvc.newURI(url), {});
let listener = {
QueryInterface: function(iid)
{
QueryInterface(iid) {
if (iid.equals(Ci.nsISupports) ||
iid.equals(Ci.nsIUrlClassifierUpdateObserver))
return this;
throw Cr.NS_ERROR_NO_INTERFACE;
},
handleEvent: function(value)
{
handleEvent(value) {
if (value === table) {
sendAsyncMessage("safeBrowsingInited");
}

View file

@ -109,7 +109,7 @@ classifierHelper.resetDatabase = function() {
classifierHelper.reloadDatabase = function() {
return new Promise(function(resolve, reject) {
gScript.addMessageListener("reloadSuccess", function handler() {
gScript.removeMessageListener('reloadSuccess', handler);
gScript.removeMessageListener("reloadSuccess", handler);
resolve();
});

View file

@ -6,7 +6,7 @@
function makeXHR(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.open("GET", url, true);
xhr.onload = function() {
callback(xhr.response);
};

View file

@ -139,10 +139,12 @@ function testGethash() {
.then(addPrefixToDB)
.then(loadTestFrame)
.then(() => {
ok(gCurGethashCounter > gPreGethashCounter, "Gethash request is triggered."); })
ok(gCurGethashCounter > gPreGethashCounter, "Gethash request is triggered.");
})
.then(loadTestFrame)
.then(() => {
ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is not triggered."); })
ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is not triggered.");
})
.then(reset);
}
@ -155,7 +157,8 @@ function testUpdate() {
.then(addCompletionToDB)
.then(loadTestFrame)
.then(() => {
ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is not triggered."); })
ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is not triggered.");
})
.then(reset);
}
@ -170,11 +173,13 @@ function testUpdateNotClearCompletions() {
.then(addCompletionToDB)
.then(loadTestFrame)
.then(() => {
ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is not triggered."); })
ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is not triggered.");
})
.then(updateUnusedUrl)
.then(loadTestFrame)
.then(() => {
ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is not triggered."); })
ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is not triggered.");
})
.then(reset);
}
@ -189,7 +194,8 @@ function testUpdateCompletionsAfterReload() {
.then(classifierHelper.reloadDatabase)
.then(loadTestFrame)
.then(() => {
ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is not triggered."); })
ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is not triggered.");
})
.then(reset);
}
@ -205,14 +211,17 @@ function testGethashCompletionsAfterReload() {
.then(addPrefixToDB)
.then(loadTestFrame)
.then(() => {
ok(gCurGethashCounter > gPreGethashCounter, "Gethash request is triggered."); })
ok(gCurGethashCounter > gPreGethashCounter, "Gethash request is triggered.");
})
.then(loadTestFrame)
.then(() => {
ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is not triggered."); })
ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is not triggered.");
})
.then(classifierHelper.reloadDatabase)
.then(loadTestFrame)
.then(() => {
ok(gCurGethashCounter > gPreGethashCounter, "Gethash request is triggered."); })
ok(gCurGethashCounter > gPreGethashCounter, "Gethash request is triggered.");
})
.then(reset);
}

View file

@ -61,7 +61,7 @@ function getGethashCounter() {
// add 4-bytes prefixes to local database, so when we access the url,
// it will trigger gethash request.
function addPrefixToDB(list, url) {
var testData = [{ db: list, url: url, len: 4 }];
var testData = [{ db: list, url, len: 4 }];
return classifierHelper.addUrlToDB(testData)
.catch(function(err) {
@ -96,11 +96,13 @@ function testNegativeCache() {
.then(setup)
.then(() => loadTestFrame())
.then(() => {
ok(gCurGethashCounter > gPreGethashCounter, "Gethash request is triggered."); })
ok(gCurGethashCounter > gPreGethashCounter, "Gethash request is triggered.");
})
// Second load should not trigger gethash request because cache.
.then(() => loadTestFrame())
.then(() => {
ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is nottriggered."); })
ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is nottriggered.");
})
.then(reset);
}
@ -122,11 +124,13 @@ function testPositiveCache() {
.then(setup)
.then(() => loadTestFrame())
.then(() => {
ok(gCurGethashCounter > gPreGethashCounter, "Gethash request is triggered."); })
ok(gCurGethashCounter > gPreGethashCounter, "Gethash request is triggered.");
})
// Second load should not trigger gethash request because cache.
.then(() => loadTestFrame())
.then(() => {
ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is nottriggered."); })
ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is nottriggered.");
})
.then(reset);
}

View file

@ -29,9 +29,8 @@ function loadTestFrame() {
"http://example.com/tests/toolkit/components/url-classifier/tests/mochitest/workerFrame.html";
}
function onmessage(event)
{
var pieces = event.data.split(':');
function onmessage(event) {
var pieces = event.data.split(":");
if (pieces[0] == "finish") {
SimpleTest.finish();
return;
@ -50,7 +49,7 @@ function updateError(errorCode) {
ok(false, "Couldn't update classifier. Error code: " + errorCode);
// Abort test.
SimpleTest.finish();
};
}
SpecialPowers.pushPrefEnv(
{"set": [["urlclassifier.malwareTable", "test-malware-simple,test-unwanted-simple"],

View file

@ -74,8 +74,8 @@
function ping(id, host) {
var elm = document.createElement("a");
elm.setAttribute('ping', host + path_ping + "?id=" + id);
elm.setAttribute('href', "#");
elm.setAttribute("ping", host + path_ping + "?id=" + id);
elm.setAttribute("href", "#");
document.body.appendChild(elm);
// Trigger ping.
@ -87,7 +87,7 @@
function isPingedWithRetry(id, expected, msg, callback, retryCnt) {
var url = "http://mochi.test:8888/" + path_ping;
var xhr = new XMLHttpRequest();
xhr.open('GET', url + "?id=" + id);
xhr.open("GET", url + "?id=" + id);
xhr.onload = function() {
var isPinged = xhr.response === "ping";
let success = isPinged === expected;

View file

@ -66,9 +66,9 @@ const tests = [
},
]
const DNT_PREF = 'privacy.donottrackheader.enabled';
const TP_PREF = 'privacy.trackingprotection.enabled';
const TP_PB_PREF = 'privacy.trackingprotection.pbmode.enabled';
const DNT_PREF = "privacy.donottrackheader.enabled";
const TP_PREF = "privacy.trackingprotection.enabled";
const TP_PB_PREF = "privacy.trackingprotection.pbmode.enabled";
const contentPage =
"http://mochi.test:8888/tests/toolkit/components/url-classifier/tests/mochitest/dnt.html";
@ -104,7 +104,7 @@ function executeTest(test) {
win.removeEventListener("DOMContentLoaded", onInnerLoad, true);
win.content.addEventListener('message', function (event) {
win.content.addEventListener("message", function(event) {
let [key, value] = event.data.split("=");
if (key == "finish") {
win.close();

View file

@ -47,7 +47,7 @@ function loadTestFrame(id) {
// add 4-bytes prefixes to local database, so when we access the url,
// it will trigger gethash request.
function addPrefixToDB(list, url) {
var testData = [{ db: list, url: url, len: 4 }];
var testData = [{ db: list, url, len: 4 }];
return classifierHelper.addUrlToDB(testData)
.catch(function(err) {

View file

@ -50,8 +50,8 @@ function testOnWindow(aPrivate, aCallback) {
}
win.removeEventListener("DOMContentLoaded", onInnerLoad, true);
win.content.addEventListener('load', function innerLoad2() {
win.content.removeEventListener('load', innerLoad2);
win.content.addEventListener("load", function innerLoad2() {
win.content.removeEventListener("load", innerLoad2);
SimpleTest.executeSoon(function() { aCallback(win); });
}, false, true);
}, true);

View file

@ -116,16 +116,16 @@ var createBlockedIframe = function(aWindow, aBrowser, aTopUrl, aUrl) {
await ContentTask.spawn(aBrowser, aUrl, async function(aUrl) {
return new Promise(resolve => {
let listener = e => {
removeEventListener('AboutBlockedLoaded', listener, false, true);
removeEventListener("AboutBlockedLoaded", listener, false, true);
resolve();
};
addEventListener('AboutBlockedLoaded', listener, false, true);
addEventListener("AboutBlockedLoaded", listener, false, true);
let frame = content.document.getElementById("phishingFrame");
frame.setAttribute('src', "http://" + aUrl);
frame.setAttribute("src", "http://" + aUrl);
});
});
let doc = aWindow.gBrowser.contentDocument.getElementsByTagName('iframe')[0].contentDocument;
let doc = aWindow.gBrowser.contentDocument.getElementsByTagName("iframe")[0].contentDocument;
let ignoreButton = doc.getElementById("ignoreWarningButton");
ok(ignoreButton, "ignoreWarningButton should exist");
ignoreButton.click();

View file

@ -50,8 +50,8 @@ function testOnWindow(aCallback) {
}
win.removeEventListener("DOMContentLoaded", onInnerLoad, true);
win.content.addEventListener('load', function innerLoad2() {
win.content.removeEventListener('load', innerLoad2);
win.content.addEventListener("load", function innerLoad2() {
win.content.removeEventListener("load", innerLoad2);
SimpleTest.executeSoon(function() { aCallback(win); });
}, false, true);
}, true);

View file

@ -50,8 +50,8 @@ function testOnWindow(aPrivate, aCallback) {
}
win.removeEventListener("DOMContentLoaded", onInnerLoad, true);
win.content.addEventListener('load', function innerLoad2() {
win.content.removeEventListener('load', innerLoad2);
win.content.addEventListener("load", function innerLoad2() {
win.content.removeEventListener("load", innerLoad2);
SimpleTest.executeSoon(function() { aCallback(win); });
}, false, true);
}, true);

View file

@ -51,8 +51,8 @@ function testOnWindow(contentPage, aCallback) {
}
win.removeEventListener("DOMContentLoaded", onInnerLoad, true);
win.content.addEventListener('load', function innerLoad2() {
win.content.removeEventListener('load', innerLoad2);
win.content.addEventListener("load", function innerLoad2() {
win.content.removeEventListener("load", innerLoad2);
SimpleTest.executeSoon(function() { aCallback(win); });
}, false, true);
}, true);

View file

@ -4,8 +4,7 @@ window.addEventListener("message", function onMessage(evt) {
var request = new XMLHttpRequest();
request.open("GET", evt.data.url, true);
request.send(null);
}
else if (evt.data.type === "doFetch") {
} else if (evt.data.type === "doFetch") {
fetch(evt.data.url);
}
});

View file

@ -41,7 +41,7 @@ prefBranch.setIntPref("urlclassifier.gethash.timeout_ms", 5000);
function delFile(name) {
try {
// Delete a previously created sqlite file
var file = dirSvc.get('ProfLD', Ci.nsIFile);
var file = dirSvc.get("ProfLD", Ci.nsIFile);
file.append(name);
if (file.exists())
file.remove(false);
@ -103,9 +103,9 @@ function buildUpdate(update, hashSize) {
var chunks = update[tableName];
for (var j = 0; j < chunks.length; j++) {
var chunk = chunks[j];
var chunkType = chunk.chunkType ? chunk.chunkType : 'a';
var chunkType = chunk.chunkType ? chunk.chunkType : "a";
var chunkNum = chunk.chunkNum ? chunk.chunkNum : j;
updateStr += chunkType + ':' + chunkNum + ':' + hashSize;
updateStr += chunkType + ":" + chunkNum + ":" + hashSize;
if (chunk.urls) {
var chunkData = chunk.urls.join("\n");
@ -148,18 +148,17 @@ function buildBareUpdate(chunks, hashSize) {
*/
function doSimpleUpdate(updateText, success, failure) {
var listener = {
QueryInterface: function(iid)
{
QueryInterface(iid) {
if (iid.equals(Ci.nsISupports) ||
iid.equals(Ci.nsIUrlClassifierUpdateObserver))
return this;
throw Cr.NS_ERROR_NO_INTERFACE;
},
updateUrlRequested: function(url) { },
streamFinished: function(status) { },
updateError: function(errorCode) { failure(errorCode); },
updateSuccess: function(requestedTimeout) { success(requestedTimeout); }
updateUrlRequested(url) { },
streamFinished(status) { },
updateError(errorCode) { failure(errorCode); },
updateSuccess(requestedTimeout) { success(requestedTimeout); }
};
dbservice.beginUpdate(listener, allTables);
@ -174,18 +173,17 @@ function doSimpleUpdate(updateText, success, failure) {
*/
function doErrorUpdate(tables, success, failure) {
var listener = {
QueryInterface: function(iid)
{
QueryInterface(iid) {
if (iid.equals(Ci.nsISupports) ||
iid.equals(Ci.nsIUrlClassifierUpdateObserver))
return this;
throw Cr.NS_ERROR_NO_INTERFACE;
},
updateUrlRequested: function(url) { },
streamFinished: function(status) { },
updateError: function(errorCode) { success(errorCode); },
updateSuccess: function(requestedTimeout) { failure(requestedTimeout); }
updateUrlRequested(url) { },
streamFinished(status) { },
updateError(errorCode) { success(errorCode); },
updateSuccess(requestedTimeout) { failure(requestedTimeout); }
};
dbservice.beginUpdate(listener, tables, null);
@ -210,12 +208,11 @@ function doStreamUpdate(updateText, success, failure, downloadFailure) {
var gAssertions = {
tableData : function(expectedTables, cb)
{
tableData(expectedTables, cb) {
dbservice.getTables(function(tables) {
// rebuild the tables in a predictable order.
var parts = tables.split("\n");
while (parts[parts.length - 1] == '') {
while (parts[parts.length - 1] == "") {
parts.pop();
}
parts.sort();
@ -226,8 +223,7 @@ tableData : function(expectedTables, cb)
});
},
checkUrls: function(urls, expected, cb, useMoz = false)
{
checkUrls(urls, expected, cb, useMoz = false) {
// work with a copy of the list.
urls = urls.slice(0);
var doLookup = function() {
@ -247,13 +243,12 @@ checkUrls: function(urls, expected, cb, useMoz = false)
doLookup();
},
checkTables: function(url, expected, cb)
{
checkTables(url, expected, cb) {
var principal = secMan.createCodebasePrincipal(iosvc.newURI("http://" + url), {});
dbservice.lookup(principal, allTables, function(tables) {
// Rebuild tables in a predictable order.
var parts = tables.split(",");
while (parts[parts.length - 1] == '') {
while (parts[parts.length - 1] == "") {
parts.pop();
}
parts.sort();
@ -263,51 +258,42 @@ checkTables: function(url, expected, cb)
}, true);
},
urlsDontExist: function(urls, cb)
{
this.checkUrls(urls, '', cb);
urlsDontExist(urls, cb) {
this.checkUrls(urls, "", cb);
},
urlsExist: function(urls, cb)
{
this.checkUrls(urls, 'test-phish-simple', cb);
urlsExist(urls, cb) {
this.checkUrls(urls, "test-phish-simple", cb);
},
malwareUrlsExist: function(urls, cb)
{
this.checkUrls(urls, 'test-malware-simple', cb);
malwareUrlsExist(urls, cb) {
this.checkUrls(urls, "test-malware-simple", cb);
},
unwantedUrlsExist: function(urls, cb)
{
this.checkUrls(urls, 'test-unwanted-simple', cb);
unwantedUrlsExist(urls, cb) {
this.checkUrls(urls, "test-unwanted-simple", cb);
},
blockedUrlsExist: function(urls, cb)
{
this.checkUrls(urls, 'test-block-simple', cb);
blockedUrlsExist(urls, cb) {
this.checkUrls(urls, "test-block-simple", cb);
},
mozPhishingUrlsExist: function(urls, cb)
{
this.checkUrls(urls, 'moz-phish-simple', cb, true);
mozPhishingUrlsExist(urls, cb) {
this.checkUrls(urls, "moz-phish-simple", cb, true);
},
subsDontExist: function(urls, cb)
{
subsDontExist(urls, cb) {
// XXX: there's no interface for checking items in the subs table
cb();
},
subsExist: function(urls, cb)
{
subsExist(urls, cb) {
// XXX: there's no interface for checking items in the subs table
cb();
},
urlExistInMultipleTables: function(data, cb)
{
this.checkTables(data["url"], data["tables"], cb);
urlExistInMultipleTables(data, cb) {
this.checkTables(data.url, data.tables, cb);
}
};
@ -315,8 +301,7 @@ urlExistInMultipleTables: function(data, cb)
/**
* Check a set of assertions against the gAssertions table.
*/
function checkAssertions(assertions, doneCallback)
{
function checkAssertions(assertions, doneCallback) {
var checkAssertion = function() {
for (var i in assertions) {
var data = assertions[i];
@ -331,8 +316,7 @@ function checkAssertions(assertions, doneCallback)
checkAssertion();
}
function updateError(arg)
{
function updateError(arg) {
do_throw(arg);
}
@ -357,23 +341,21 @@ function doUpdateTest(updates, assertions, successCallback, errorCallback) {
var gTests;
var gNextTest = 0;
function runNextTest()
{
function runNextTest() {
if (gNextTest >= gTests.length) {
do_test_finished();
return;
}
dbservice.resetDatabase();
dbservice.setHashCompleter('test-phish-simple', null);
dbservice.setHashCompleter("test-phish-simple", null);
let test = gTests[gNextTest++];
dump("running " + test.name + "\n");
test();
}
function runTests(tests)
{
function runTests(tests) {
gTests = tests;
runNextTest();
}
@ -388,13 +370,13 @@ function Timer(delay, cb) {
}
Timer.prototype = {
QueryInterface: function(iid) {
QueryInterface(iid) {
if (!iid.equals(Ci.nsISupports) && !iid.equals(Ci.nsITimerCallback)) {
throw Cr.NS_ERROR_NO_INTERFACE;
}
return this;
},
notify: function(timer) {
notify(timer) {
this.cb();
}
}
@ -414,7 +396,7 @@ function LFSRgenerator(seed) {
}
LFSRgenerator.prototype = {
// nextNum returns a random unsigned integer of in the range [0,2^|bits|].
nextNum: function(bits) {
nextNum(bits) {
if (!bits)
bits = 32;
@ -446,13 +428,13 @@ function waitUntilMetaDataSaved(expectedState, expectedChecksum, callback) {
let stateBase64 = metadata[0];
let checksumBase64 = metadata[1];
if (tableName !== 'test-phish-proto') {
if (tableName !== "test-phish-proto") {
return false; // continue.
}
if (stateBase64 === btoa(expectedState) &&
checksumBase64 === btoa(expectedChecksum)) {
do_print('State has been saved to disk!');
do_print("State has been saved to disk!");
// We slightly defer the callback to see if the in-memory
// |getTables| caching works correctly.

View file

@ -1,6 +1,5 @@
function doTest(updates, assertions)
{
function doTest(updates, assertions) {
doUpdateTest(updates, assertions, runNextTest, updateError);
}
@ -41,8 +40,7 @@ function testMultipleAdds() {
}
// Test that a sub will remove an existing add
function testSimpleSub()
{
function testSimpleSub() {
var addUrls = ["foo.com/a", "bar.com/b"];
var subUrls = ["1:foo.com/a"];
@ -68,8 +66,7 @@ function testSimpleSub()
}
// Same as testSimpleSub(), but the sub comes in before the add.
function testSubEmptiesAdd()
{
function testSubEmptiesAdd() {
var subUrls = ["1:foo.com/a"];
var addUrls = ["foo.com/a", "bar.com/b"];
@ -94,8 +91,7 @@ function testSubEmptiesAdd()
// Very similar to testSubEmptiesAdd, except that the domain entry will
// still have an item left over that needs to be synced.
function testSubPartiallyEmptiesAdd()
{
function testSubPartiallyEmptiesAdd() {
var subUrls = ["1:foo.com/a"];
var addUrls = ["foo.com/a", "foo.com/b", "bar.com/b"];
@ -122,8 +118,7 @@ function testSubPartiallyEmptiesAdd()
// subsDontExist assertions. Since we don't have a good interface for getting
// at sub entries, we'll verify it by side-effect. Subbing a url once
// then adding it twice should leave the url intact.
function testPendingSubRemoved()
{
function testPendingSubRemoved() {
var subUrls = ["1:foo.com/a", "2:foo.com/b"];
var addUrls = ["foo.com/a", "foo.com/b"];
@ -150,8 +145,7 @@ function testPendingSubRemoved()
}
// Make sure that a saved sub is removed when the sub chunk is expired.
function testPendingSubExpire()
{
function testPendingSubExpire() {
var subUrls = ["1:foo.com/a", "1:foo.com/b"];
var addUrls = ["foo.com/a", "foo.com/b"];
@ -178,8 +172,7 @@ function testPendingSubExpire()
}
// Make sure that the sub url removes from only the chunk that it specifies
function testDuplicateAdds()
{
function testDuplicateAdds() {
var urls = ["foo.com/a"];
var addUpdate1 = buildPhishingUpdate(
@ -203,8 +196,7 @@ function testDuplicateAdds()
}
// Tests a sub which matches some existing adds but leaves others.
function testSubPartiallyMatches()
{
function testSubPartiallyMatches() {
var subUrls = ["foo.com/a"];
var addUrls = ["1:foo.com/a", "2:foo.com/b"];
@ -230,8 +222,7 @@ function testSubPartiallyMatches()
// XXX: because subsExist isn't actually implemented, this is the same
// test as above but with a second add chunk that should fail to be added
// because of a pending sub chunk.
function testSubPartiallyMatches2()
{
function testSubPartiallyMatches2() {
var addUrls = ["foo.com/a"];
var subUrls = ["1:foo.com/a", "2:foo.com/b"];
var addUrls2 = ["foo.com/b"];
@ -396,8 +387,7 @@ function testDuplicateAddChunks() {
// that we need to add the same add chunk twice, with an expiration
// in the middle. This would be easier if subsDontExist actually
// worked...
function testExpireWholeSub()
{
function testExpireWholeSub() {
var subUrls = ["1:foo.com/a"];
var update = buildPhishingUpdate(
@ -433,8 +423,7 @@ function testExpireWholeSub()
// This test is roughly the opposite of testExpireWholeSub(). We add
// the empty add first, and make sure that it prevents a sub for that
// add from being applied.
function testPreventWholeSub()
{
function testPreventWholeSub() {
var subUrls = ["1:foo.com/a"];
var update = buildPhishingUpdate(
@ -466,8 +455,7 @@ function testPreventWholeSub()
doTest([update], assertions);
}
function run_test()
{
function run_test() {
runTests([
testSimpleAdds,
testMultipleAdds,

View file

@ -13,7 +13,7 @@ function run_test() {
let origList = Services.prefs.getCharPref("browser.safebrowsing.provider.google.lists");
// Remove 'goog-malware-shavar' from the original.
let trimmedList = origList.replace('goog-malware-shavar,', '');
let trimmedList = origList.replace("goog-malware-shavar,", "");
Services.prefs.setCharPref("browser.safebrowsing.provider.google.lists", trimmedList);
try {
@ -25,7 +25,7 @@ function run_test() {
//
SafeBrowsing.registerTables();
} catch (e) {
ok(false, 'Exception thrown due to ' + e.toString());
ok(false, "Exception thrown due to " + e.toString());
}
Services.prefs.setCharPref("browser.safebrowsing.provider.google.lists", origList);

View file

@ -105,8 +105,7 @@ function testFailure(arg) {
do_throw(arg);
}
function checkNoHost()
{
function checkNoHost() {
// Looking up a no-host uri such as a data: uri should throw an exception.
var exception;
try {
@ -122,8 +121,7 @@ function checkNoHost()
do_test_finished();
}
function tablesCallbackWithoutSub(tables)
{
function tablesCallbackWithoutSub(tables) {
var parts = tables.split("\n");
parts.sort();
@ -140,8 +138,7 @@ function expireSubSuccess(result) {
dbservice.getTables(tablesCallbackWithoutSub);
}
function tablesCallbackWithSub(tables)
{
function tablesCallbackWithSub(tables) {
var parts = tables.split("\n");
parts.sort();
@ -159,8 +156,7 @@ function tablesCallbackWithSub(tables)
doSimpleUpdate(data, expireSubSuccess, testFailure);
}
function checkChunksWithSub()
{
function checkChunksWithSub() {
dbservice.getTables(tablesCallbackWithSub);
}
@ -217,8 +213,7 @@ function blockedExists(result) {
}
}
function checkState()
{
function checkState() {
numExpecting = 0;
@ -253,8 +248,7 @@ function checkState()
}
}
function testSubSuccess(result)
{
function testSubSuccess(result) {
do_check_eq(result, "1000");
checkState();
}

View file

@ -261,8 +261,7 @@ function run_test() {
let numChars = COMPLETE_LENGTH - responseCompletion.hash.length;
responseCompletion.hash += (new Array(numChars + 1)).join("\u0000");
}
}
else {
} else {
let numChars = COMPLETE_LENGTH - completion.hash.length;
completion.hash += (new Array(numChars + 1)).join("\u0000");
}
@ -372,8 +371,7 @@ callback.prototype = {
break;
}
}
}
else {
} else {
// Hashes are not actually strings and can contain arbitrary data.
do_check_eq(JSON.stringify(hash), JSON.stringify(this._completion.hash));
do_check_eq(table, this._completion.table);

View file

@ -68,8 +68,8 @@ let gHttpServV4 = null;
let gUpdatedCntForTableData = 0; // For TEST_TABLE_DATA_LIST.
let gIsV4Updated = false; // For TEST_TABLE_DATA_V4.
const NEW_CLIENT_STATE = 'sta\0te';
const CHECKSUM = '\x30\x67\xc7\x2c\x5e\x50\x1c\x31\xe3\xfe\xca\x73\xf0\x47\xdc\x34\x1a\x95\x63\x99\xec\x70\x5e\x0a\xee\x9e\xfb\x17\xa1\x55\x35\x78';
const NEW_CLIENT_STATE = "sta\0te";
const CHECKSUM = "\x30\x67\xc7\x2c\x5e\x50\x1c\x31\xe3\xfe\xca\x73\xf0\x47\xdc\x34\x1a\x95\x63\x99\xec\x70\x5e\x0a\xee\x9e\xfb\x17\xa1\x55\x35\x78";
prefBranch.setBoolPref("browser.safebrowsing.debug", true);
@ -245,8 +245,8 @@ function run_test() {
// V4 append the base64 encoded request to the query string.
equal(request.queryString, gExpectedQueryV4);
equal(request.queryString.indexOf('+'), -1);
equal(request.queryString.indexOf('/'), -1);
equal(request.queryString.indexOf("+"), -1);
equal(request.queryString.indexOf("/"), -1);
// Respond a V2 compatible content for now. In the future we can
// send a meaningful response to test Bug 1284178 to see if the

View file

@ -11,8 +11,7 @@ function DummyCompleter() {
DummyCompleter.prototype =
{
QueryInterface: function(iid)
{
QueryInterface(iid) {
if (!iid.equals(Ci.nsISupports) &&
!iid.equals(Ci.nsIUrlClassifierHashCompleter)) {
throw Cr.NS_ERROR_NO_INTERFACE;
@ -20,8 +19,7 @@ QueryInterface: function(iid)
return this;
},
complete: function(partialHash, gethashUrl, tableName, cb)
{
complete(partialHash, gethashUrl, tableName, cb) {
this.queries.push(partialHash);
var fragments = this.fragments;
var self = this;
@ -43,8 +41,7 @@ complete: function(partialHash, gethashUrl, tableName, cb)
var timer = new Timer(0, doCallback);
},
getHash: function(fragment)
{
getHash(fragment) {
var converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].
createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
@ -56,22 +53,19 @@ getHash: function(fragment)
return hash.slice(0, 32);
},
addFragment: function(chunkId, fragment)
{
addFragment(chunkId, fragment) {
this.addHash(chunkId, this.getHash(fragment));
},
// This method allows the caller to generate complete hashes that match the
// prefix of a real fragment, but have different complete hashes.
addConflict: function(chunkId, fragment)
{
addConflict(chunkId, fragment) {
var realHash = this.getHash(fragment);
var invalidHash = this.getHash("blah blah blah blah blah");
this.addHash(chunkId, realHash.slice(0, 4) + invalidHash.slice(4, 32));
},
addHash: function(chunkId, hash)
{
addHash(chunkId, hash) {
var partial = hash.slice(0, 4);
if (this.fragments[partial]) {
this.fragments[partial].push([chunkId, hash]);
@ -80,8 +74,7 @@ addHash: function(chunkId, hash)
}
},
compareQueries: function(fragments)
{
compareQueries(fragments) {
var expectedQueries = [];
for (var i = 0; i < fragments.length; i++) {
expectedQueries.push(this.getHash(fragments[i]).slice(0, 4));
@ -95,8 +88,7 @@ compareQueries: function(fragments)
}
};
function setupCompleter(table, hits, conflicts)
{
function setupCompleter(table, hits, conflicts) {
var completer = new DummyCompleter();
completer.tableName = table;
for (var i = 0; i < hits.length; i++) {
@ -119,8 +111,7 @@ function setupCompleter(table, hits, conflicts)
return completer;
}
function installCompleter(table, fragments, conflictFragments)
{
function installCompleter(table, fragments, conflictFragments) {
return setupCompleter(table, fragments, conflictFragments);
}
@ -131,15 +122,13 @@ function installFailingCompleter(table) {
}
// Helper assertion for checking dummy completer queries
gAssertions.completerQueried = function(data, cb)
{
gAssertions.completerQueried = function(data, cb) {
var completer = data[0];
completer.compareQueries(data[1]);
cb();
}
function doTest(updates, assertions)
{
function doTest(updates, assertions) {
doUpdateTest(updates, assertions, runNextTest, updateError);
}
@ -154,7 +143,7 @@ function testPartialAdds() {
4);
var completer = installCompleter('test-phish-simple', [[1, addUrls]], []);
var completer = installCompleter("test-phish-simple", [[1, addUrls]], []);
var assertions = {
"tableData": "test-phish-simple;a:1",
@ -176,7 +165,7 @@ function testPartialAddsWithConflicts() {
4);
// Each result will have both a real match and a conflict
var completer = installCompleter('test-phish-simple',
var completer = installCompleter("test-phish-simple",
[[1, addUrls]],
[[1, addUrls]]);
@ -200,7 +189,7 @@ function testFragments() {
4);
var completer = installCompleter('test-phish-simple', [[1, addUrls]], []);
var completer = installCompleter("test-phish-simple", [[1, addUrls]], []);
var assertions = {
"tableData": "test-phish-simple;a:1",
@ -234,7 +223,7 @@ function testSpecFragments() {
4);
var completer = installCompleter('test-phish-simple', [[1, addUrls]], []);
var completer = installCompleter("test-phish-simple", [[1, addUrls]], []);
var assertions = {
"tableData": "test-phish-simple;a:1",
@ -269,7 +258,7 @@ function testMoreSpecFragments() {
}],
4);
var completer = installCompleter('test-phish-simple', [[1, addUrls]], []);
var completer = installCompleter("test-phish-simple", [[1, addUrls]], []);
var assertions = {
"tableData": "test-phish-simple;a:1",
@ -292,7 +281,7 @@ function testFalsePositives() {
// Each result will have no matching complete hashes and a non-matching
// conflict
var completer = installCompleter('test-phish-simple', [], [[1, addUrls]]);
var completer = installCompleter("test-phish-simple", [], [[1, addUrls]]);
var assertions = {
"tableData": "test-phish-simple;a:1",
@ -313,7 +302,7 @@ function testEmptyCompleter() {
4);
// Completer will never return full hashes
var completer = installCompleter('test-phish-simple', [], []);
var completer = installCompleter("test-phish-simple", [], []);
var assertions = {
"tableData": "test-phish-simple;a:1",
@ -334,7 +323,7 @@ function testCompleterFailure() {
4);
// Completer will never return full hashes
var completer = installFailingCompleter('test-phish-simple');
var completer = installFailingCompleter("test-phish-simple");
var assertions = {
"tableData": "test-phish-simple;a:1",
@ -361,7 +350,7 @@ function testMixedSizesSameDomain() {
32);
// We should only need to complete the partial hashes
var completer = installCompleter('test-phish-simple', [[1, add1Urls]], []);
var completer = installCompleter("test-phish-simple", [[1, add1Urls]], []);
var assertions = {
"tableData": "test-phish-simple;a:1-2",
@ -390,7 +379,7 @@ function testMixedSizesDifferentDomains() {
32);
// We should only need to complete the partial hashes
var completer = installCompleter('test-phish-simple', [[1, add1Urls]], []);
var completer = installCompleter("test-phish-simple", [[1, add1Urls]], []);
var assertions = {
"tableData": "test-phish-simple;a:1-2",
@ -403,8 +392,7 @@ function testMixedSizesDifferentDomains() {
doTest([update1, update2], assertions);
}
function testInvalidHashSize()
{
function testInvalidHashSize() {
var addUrls = [ "foo.com/a", "foo.com/b", "bar.com/c" ];
var update = buildPhishingUpdate(
[
@ -421,7 +409,7 @@ function testInvalidHashSize()
}],
4);
var completer = installCompleter('test-phish-simple', [[1, addUrls]], []);
var completer = installCompleter("test-phish-simple", [[1, addUrls]], []);
var assertions = {
"tableData": "test-phish-simple;a:2",
@ -432,8 +420,7 @@ function testInvalidHashSize()
doUpdateTest([update2, update], assertions, updateError, runNextTest);
}
function testWrongTable()
{
function testWrongTable() {
var addUrls = [ "foo.com/a" ];
var update = buildPhishingUpdate(
[
@ -441,7 +428,7 @@ function testWrongTable()
"urls": addUrls
}],
4);
var completer = installCompleter('test-malware-simple', // wrong table
var completer = installCompleter("test-malware-simple", // wrong table
[[1, addUrls]], []);
// The above installCompleter installs the completer for test-malware-simple,
@ -466,7 +453,7 @@ function testWrongTable()
// The miss earlier will have caused a miss to be cached.
// Resetting the completer does not count as an update,
// so we will not be probed again.
var newCompleter = installCompleter('test-malware-simple', [[1, addUrls]], []); dbservice.setHashCompleter("test-phish-simple",
var newCompleter = installCompleter("test-malware-simple", [[1, addUrls]], []); dbservice.setHashCompleter("test-phish-simple",
newCompleter);
var assertions = {
@ -477,8 +464,7 @@ function testWrongTable()
}, updateError);
}
function setupCachedResults(addUrls, part2)
{
function setupCachedResults(addUrls, part2) {
var update = buildPhishingUpdate(
[
{ "chunkNum": 1,
@ -486,7 +472,7 @@ function setupCachedResults(addUrls, part2)
}],
4);
var completer = installCompleter('test-phish-simple', [[1, addUrls]], []);
var completer = installCompleter("test-phish-simple", [[1, addUrls]], []);
var assertions = {
"tableData": "test-phish-simple;a:1",
@ -503,14 +489,13 @@ function setupCachedResults(addUrls, part2)
}, updateError);
}
function testCachedResults()
{
function testCachedResults() {
setupCachedResults(["foo.com/a"], function(add) {
// This is called after setupCachedResults(). Verify that
// checking the url again does not cause a completer request.
// install a new completer, this one should never be queried.
var newCompleter = installCompleter('test-phish-simple', [[1, []]], []);
var newCompleter = installCompleter("test-phish-simple", [[1, []]], []);
var assertions = {
"urlsExist": ["foo.com/a"],
@ -523,7 +508,7 @@ function testCachedResults()
function testCachedResultsWithSub() {
setupCachedResults(["foo.com/a"], function() {
// install a new completer, this one should never be queried.
var newCompleter = installCompleter('test-phish-simple', [[1, []]], []);
var newCompleter = installCompleter("test-phish-simple", [[1, []]], []);
var removeUpdate = buildPhishingUpdate(
[ { "chunkNum": 2,
@ -543,7 +528,7 @@ function testCachedResultsWithSub() {
function testCachedResultsWithExpire() {
setupCachedResults(["foo.com/a"], function() {
// install a new completer, this one should never be queried.
var newCompleter = installCompleter('test-phish-simple', [[1, []]], []);
var newCompleter = installCompleter("test-phish-simple", [[1, []]], []);
var expireUpdate =
"n:1000\n" +
@ -558,15 +543,14 @@ function testCachedResultsWithExpire() {
});
}
function testCachedResultsFailure()
{
function testCachedResultsFailure() {
var existUrls = ["foo.com/a"];
setupCachedResults(existUrls, function() {
// This is called after setupCachedResults(). Verify that
// checking the url again does not cause a completer request.
// install a new completer, this one should never be queried.
var newCompleter = installCompleter('test-phish-simple', [[1, []]], []);
var newCompleter = installCompleter("test-phish-simple", [[1, []]], []);
var assertions = {
"urlsExist": existUrls,
@ -586,7 +570,7 @@ function testCachedResultsFailure()
// Apply the update. The cached completes should be gone.
doErrorUpdate("test-phish-simple,test-malware-simple", function() {
// Now the completer gets queried again.
var newCompleter2 = installCompleter('test-phish-simple', [[1, existUrls]], []);
var newCompleter2 = installCompleter("test-phish-simple", [[1, existUrls]], []);
var assertions2 = {
"tableData": "test-phish-simple;a:1",
"urlsExist": existUrls,
@ -598,8 +582,7 @@ function testCachedResultsFailure()
});
}
function testErrorList()
{
function testErrorList() {
var addUrls = [ "foo.com/a", "foo.com/b", "bar.com/c" ];
var update = buildPhishingUpdate(
[
@ -610,7 +593,7 @@ function testErrorList()
// The update failure should will kill the completes, so the above
// must be a prefix to get any hit at all past the update failure.
var completer = installCompleter('test-phish-simple', [[1, addUrls]], []);
var completer = installCompleter("test-phish-simple", [[1, addUrls]], []);
var assertions = {
"tableData": "test-phish-simple;a:1",
@ -634,8 +617,7 @@ function testErrorList()
// Verify that different lists (test-phish-simple,
// test-malware-simple) maintain their freshness separately.
function testErrorListIndependent()
{
function testErrorListIndependent() {
var phishUrls = [ "phish.com/a" ];
var malwareUrls = [ "attack.com/a" ];
var update = buildPhishingUpdate(
@ -654,7 +636,7 @@ function testErrorListIndependent()
}],
32);
var completer = installCompleter('test-phish-simple', [[1, phishUrls]], []);
var completer = installCompleter("test-phish-simple", [[1, phishUrls]], []);
var assertions = {
"tableData": "test-malware-simple;a:2\ntest-phish-simple;a:1",
@ -677,8 +659,7 @@ function testErrorListIndependent()
}, updateError);
}
function run_test()
{
function run_test() {
runTests([
testPartialAdds,
testPartialAddsWithConflicts,

View file

@ -45,7 +45,7 @@ function checkContents(pset, prefixes) {
function wrappedProbe(pset, prefix) {
return pset.contains(prefix);
};
}
// doRandomLookups: we use this to test for false membership with random input
// over the range of prefixes (unsigned 32-bits integers).
@ -160,7 +160,7 @@ function testLoadSaveLargeSet() {
checkContents(pset, arr);
// Now try to save, restore, and redo the lookups
var file = dirSvc.get('ProfLD', Ci.nsIFile);
var file = dirSvc.get("ProfLD", Ci.nsIFile);
file.append("testLarge.pset");
pset.storeToFile(file);
@ -205,7 +205,7 @@ function testLoadSaveNoDelta() {
doExpectedLookups(pset, arr, 1);
var file = dirSvc.get('ProfLD', Ci.nsIFile);
var file = dirSvc.get("ProfLD", Ci.nsIFile);
file.append("testNoDelta.pset");
pset.storeToFile(file);

View file

@ -1,5 +1,4 @@
function doTest(updates, assertions, expectError)
{
function doTest(updates, assertions, expectError) {
if (expectError) {
doUpdateTest(updates, assertions, updateError, runNextTest);
} else {
@ -215,8 +214,7 @@ function Observer(callback) {
Observer.prototype =
{
QueryInterface: function(iid)
{
QueryInterface(iid) {
if (!iid.equals(Ci.nsISupports) &&
!iid.equals(Ci.nsIObserver)) {
throw Cr.NS_ERROR_NO_INTERFACE;
@ -272,8 +270,7 @@ function testReset() {
}
function run_test()
{
function run_test() {
runTests([
testSimpleForward,
testNestedForward,