Bug 1457835 - Enable ESLint for testing/mochitest (automatic changes). r=jmaher

MozReview-Commit-ID: 4Et3MAxcEQl

--HG--
extra : rebase_source : b6456aa9dd18df77cfb7fbb5012de33bd6fed681
This commit is contained in:
Mark Banner 2018-01-26 21:32:30 +00:00
Родитель bb6a861576
Коммит 7953526ea2
26 изменённых файлов: 258 добавлений и 288 удалений

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

@ -97,7 +97,7 @@ var BrowserTestUtils = {
options = {
gBrowser: Services.wm.getMostRecentWindow("navigator:browser").gBrowser,
url: options
}
};
}
let tab = await BrowserTestUtils.openNewForegroundTab(options);
let originalWindow = tab.ownerGlobal;
@ -187,12 +187,11 @@ var BrowserTestUtils = {
}
promises = [
BrowserTestUtils.switchTab(tabbrowser, function () {
BrowserTestUtils.switchTab(tabbrowser, function() {
if (typeof opening == "function") {
opening();
tab = tabbrowser.selectedTab;
}
else {
} else {
tabbrowser.selectedTab = tab = tabbrowser.addTab(opening);
}
})
@ -235,8 +234,7 @@ var BrowserTestUtils = {
if (typeof tab == "function") {
tab();
}
else {
} else {
tabbrowser.selectedTab = tab;
}
return promise;
@ -267,11 +265,11 @@ var BrowserTestUtils = {
* @return {Promise}
* @resolves When a load event is triggered for the browser.
*/
browserLoaded(browser, includeSubFrames=false, wantLoad=null,
maybeErrorPage=false) {
browserLoaded(browser, includeSubFrames = false, wantLoad = null,
maybeErrorPage = false) {
// Passing a url as second argument is a common mistake we should prevent.
if (includeSubFrames && typeof includeSubFrames != "boolean") {
throw("The second argument to browserLoaded should be a boolean.");
throw ("The second argument to browserLoaded should be a boolean.");
}
// If browser belongs to tabbrowser-tab, ensure it has been
@ -286,10 +284,10 @@ var BrowserTestUtils = {
return true;
} else if (typeof(wantLoad) == "function") {
return wantLoad(url);
} else {
}
// It's a string.
return wantLoad == url;
}
}
return new Promise(resolve => {
@ -338,7 +336,7 @@ var BrowserTestUtils = {
let selectedBrowser = win.gBrowser.selectedBrowser;
return msg.target == selectedBrowser &&
(aboutBlank || selectedBrowser.currentURI.spec != "about:blank")
(aboutBlank || selectedBrowser.currentURI.spec != "about:blank");
});
},
@ -359,7 +357,7 @@ var BrowserTestUtils = {
* @return {Promise}
* @resolves When STATE_STOP reaches the tab's progress listener
*/
browserStopped(browser, expectedURI, checkAborts=false) {
browserStopped(browser, expectedURI, checkAborts = false) {
return new Promise(resolve => {
const kDocStopFlags = Ci.nsIWebProgressListener.STATE_IS_NETWORK |
Ci.nsIWebProgressListener.STATE_STOP;
@ -377,7 +375,7 @@ var BrowserTestUtils = {
BrowserTestUtils._webProgressListeners.delete(wpl);
resolve();
}
};
}
},
onSecurityChange() {},
onStatusChange() {},
@ -665,7 +663,7 @@ var BrowserTestUtils = {
* @return {Promise}
* Resolves with the new window once it is loaded.
*/
async openNewBrowserWindow(options={}) {
async openNewBrowserWindow(options = {}) {
let argString = Cc["@mozilla.org/supports-string;1"].
createInstance(Ci.nsISupportsString);
argString.data = "";
@ -751,7 +749,7 @@ var BrowserTestUtils = {
* browser windows, the Promise will also wait until all final
* SessionStore messages have been sent up from all browser tabs.
*/
windowClosed(win) {
windowClosed(win) {
let domWinClosedPromise = BrowserTestUtils.domWindowClosed(win);
let promises = [domWinClosedPromise];
let winType = win.document.documentElement.getAttribute("windowtype");
@ -763,7 +761,7 @@ var BrowserTestUtils = {
// messages back from them.
browserSet.forEach((browser) => {
win.gBrowser._insertBrowser(win.gBrowser.getTabForBrowser(browser));
})
});
let mm = win.getGroupMessageManager("browsers");
mm.addMessageListener("SessionStore:update", function onMessage(msg) {
@ -1103,8 +1101,7 @@ var BrowserTestUtils = {
* @returns {Promise}
* @resolves True if the mouse event was cancelled.
*/
synthesizeMouse(target, offsetX, offsetY, event, browser)
{
synthesizeMouse(target, offsetX, offsetY, event, browser) {
return new Promise((resolve, reject) => {
let mm = browser.messageManager;
mm.addMessageListener("Test:SynthesizeMouseDone", function mouseMsg(message) {
@ -1127,7 +1124,7 @@ var BrowserTestUtils = {
}
mm.sendAsyncMessage("Test:SynthesizeMouse",
{target, targetFn, x: offsetX, y: offsetY, event: event},
{target, targetFn, x: offsetX, y: offsetY, event},
{object: cpowObject});
});
},
@ -1157,8 +1154,7 @@ var BrowserTestUtils = {
* Version of synthesizeMouse that uses the center of the target as the mouse
* location. Arguments and the return value are the same.
*/
synthesizeMouseAtCenter(target, event, browser)
{
synthesizeMouseAtCenter(target, event, browser) {
// Use a flag to indicate to center rather than having a separate message.
event.centered = true;
return BrowserTestUtils.synthesizeMouse(target, 0, 0, event, browser);
@ -1169,8 +1165,7 @@ var BrowserTestUtils = {
* window instead of a target as the offset. Otherwise, the arguments and
* return value are the same as synthesizeMouse.
*/
synthesizeMouseAtPoint(offsetX, offsetY, event, browser)
{
synthesizeMouseAtPoint(offsetX, offsetY, event, browser) {
return BrowserTestUtils.synthesizeMouse(null, offsetX, offsetY, event, browser);
},
@ -1216,8 +1211,8 @@ var BrowserTestUtils = {
* @resolves An Object with key-value pairs representing the data from the
* crash report's extra file (if applicable).
*/
async crashBrowser(browser, shouldShowTabCrashPage=true,
shouldClearMinidumps=true) {
async crashBrowser(browser, shouldShowTabCrashPage = true,
shouldClearMinidumps = true) {
let extra = {};
let KeyValueParser = {};
if (AppConstants.MOZ_CRASHREPORTER) {
@ -1234,7 +1229,7 @@ var BrowserTestUtils = {
* @return nsIFile
*/
function getMinidumpDirectory() {
let dir = Services.dirsvc.get('ProfD', Ci.nsIFile);
let dir = Services.dirsvc.get("ProfD", Ci.nsIFile);
dir.append("minidumps");
return dir;
}
@ -1267,12 +1262,12 @@ var BrowserTestUtils = {
privateNoteIntentionalCrash();
let zero = new ctypes.intptr_t(8);
let badptr = ctypes.cast(zero, ctypes.PointerType(ctypes.int32_t));
badptr.contents
badptr.contents;
};
dump("\nEt tu, Brute?\n");
dies();
}
};
let expectedPromises = [];
@ -1293,7 +1288,7 @@ var BrowserTestUtils = {
let dumpID;
if (AppConstants.MOZ_CRASHREPORTER) {
dumpID = subject.getPropertyAsAString('dumpID');
dumpID = subject.getPropertyAsAString("dumpID");
if (!dumpID) {
return reject("dumpID was not present despite crash reporting " +
"being enabled");
@ -1307,25 +1302,25 @@ var BrowserTestUtils = {
.then(() => {
let minidumpDirectory = getMinidumpDirectory();
let extrafile = minidumpDirectory.clone();
extrafile.append(dumpID + '.extra');
extrafile.append(dumpID + ".extra");
if (extrafile.exists()) {
dump(`\nNo .extra file for dumpID: ${dumpID}\n`);
if (AppConstants.MOZ_CRASHREPORTER) {
extra = KeyValueParser.parseKeyValuePairsFromFile(extrafile);
} else {
dump('\nCrashReporter not enabled - will not return any extra data\n');
dump("\nCrashReporter not enabled - will not return any extra data\n");
}
}
if (shouldClearMinidumps) {
removeFile(minidumpDirectory, dumpID + '.dmp');
removeFile(minidumpDirectory, dumpID + '.extra');
removeFile(minidumpDirectory, dumpID + ".dmp");
removeFile(minidumpDirectory, dumpID + ".extra");
}
});
}
removalPromise.then(() => {
Services.obs.removeObserver(observer, 'ipc:content-shutdown');
Services.obs.removeObserver(observer, "ipc:content-shutdown");
dump("\nCrash cleaned up\n");
// There might be other ipc:content-shutdown handlers that need to
// run before we want to continue, so we'll resolve on the next tick
@ -1334,7 +1329,7 @@ var BrowserTestUtils = {
});
};
Services.obs.addObserver(observer, 'ipc:content-shutdown');
Services.obs.addObserver(observer, "ipc:content-shutdown");
});
expectedPromises.push(crashCleanupPromise);
@ -1387,7 +1382,7 @@ var BrowserTestUtils = {
(value && element.getAttribute(attr) === value)) {
resolve();
mut.disconnect();
return;
}
});
@ -1423,8 +1418,8 @@ var BrowserTestUtils = {
});
mm.sendAsyncMessage("Test:SendChar", {
char: char,
seq: seq
char,
seq
});
});
},
@ -1597,7 +1592,7 @@ var BrowserTestUtils = {
addEventListener("MozAfterPaint", function onPaint() {
removeEventListener("MozAfterPaint", onPaint);
resolve();
})
});
});
});
},
@ -1673,7 +1668,7 @@ var BrowserTestUtils = {
* specified button is clicked.
*/
async promiseAlertDialogOpen(buttonAction,
uri="chrome://global/content/commonDialog.xul",
uri = "chrome://global/content/commonDialog.xul",
func) {
let win = await this.domWindowOpened(null, async win => {
// The test listens for the "load" event which guarantees that the alert
@ -1709,7 +1704,7 @@ var BrowserTestUtils = {
* specified button is clicked, and the dialog has been fully closed.
*/
async promiseAlertDialog(buttonAction,
uri="chrome://global/content/commonDialog.xul",
uri = "chrome://global/content/commonDialog.xul",
func) {
let win = await this.promiseAlertDialogOpen(buttonAction, uri, func);
return this.windowClosed(win);

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

@ -80,9 +80,9 @@ var ContentTask = {
browser.messageManager.sendAsyncMessage(
"content-task:spawn",
{
id: id,
id,
runnable: task.toString(),
arg: arg,
arg,
});
return deferred.promise;

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

@ -36,7 +36,7 @@ var ContentTaskUtils = {
* Resolves when condition is true.
* Rejects if timeout is exceeded or condition ever throws.
*/
waitForCondition(condition, msg, interval=100, maxTries=50) {
waitForCondition(condition, msg, interval = 100, maxTries = 50) {
return new Promise((resolve, reject) => {
let tries = 0;
let intervalID = setInterval(() => {
@ -50,7 +50,7 @@ var ContentTaskUtils = {
let conditionPassed = false;
try {
conditionPassed = condition();
} catch(e) {
} catch (e) {
msg += ` - threw exception: ${e}`;
clearInterval(intervalID);
reject(msg);

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

@ -8,7 +8,7 @@ ChromeUtils.import("resource://gre/modules/Task.jsm", this);
ChromeUtils.import("resource://testing-common/ContentTaskUtils.jsm", this);
const AssertCls = ChromeUtils.import("resource://testing-common/Assert.jsm", null).Assert;
addMessageListener("content-task:spawn", function (msg) {
addMessageListener("content-task:spawn", function(msg) {
let id = msg.data.id;
let source = msg.data.runnable || "()=>{}";
@ -22,7 +22,7 @@ addMessageListener("content-task:spawn", function (msg) {
var Assert = new AssertCls((err, message, stack) => {
sendAsyncMessage("content-task:test-result", {
id: id,
id,
condition: !err,
name: err ? err.message : message,
stack: getStack(err ? err.stack : stack)
@ -45,24 +45,24 @@ addMessageListener("content-task:spawn", function (msg) {
let runnablestr = `
(() => {
return (${source});
})();`
})();`;
let runnable = eval(runnablestr);
let iterator = runnable.call(this, msg.data.arg);
Task.spawn(iterator).then((val) => {
sendAsyncMessage("content-task:complete", {
id: id,
id,
result: val,
});
}, (e) => {
sendAsyncMessage("content-task:complete", {
id: id,
id,
error: e.toString(),
});
});
} catch (e) {
sendAsyncMessage("content-task:complete", {
id: id,
id,
error: e.toString(),
});
}

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

@ -11,14 +11,14 @@ addEventListener("DOMContentLoaded", function(event) {
// For error page, internalURL is 'about:neterror?...', and visibleURL
// is the original URL.
sendAsyncMessage("browser-test-utils:DOMContentLoadedEvent",
{subframe: subframe, internalURL: event.target.documentURI,
{subframe, internalURL: event.target.documentURI,
visibleURL: content.document.location.href});
}, true);
addEventListener("load", function(event) {
let subframe = event.target != content.document;
sendAsyncMessage("browser-test-utils:loadEvent",
{subframe: subframe, internalURL: event.target.documentURI,
{subframe, internalURL: event.target.documentURI,
visibleURL: content.document.location.href});
}, true);

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

@ -13,7 +13,7 @@ var EXPORTED_SYMBOLS = ["ContentCollector"];
// docshells should be destroyed.
var ContentCollector = {
init: function() {
init() {
let processType = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime).processType;
if (processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT) {
// In the main process, we handle triggering collections in browser-test.js
@ -23,7 +23,7 @@ var ContentCollector = {
Services.cpmm.addMessageListener("browser-test:collect-request", this);
},
receiveMessage: function(aMessage) {
receiveMessage(aMessage) {
switch (aMessage.name) {
case "browser-test:collect-request":
Services.obs.notifyObservers(null, "memory-pressure", "heap-minimize");
@ -45,7 +45,7 @@ var ContentCollector = {
setTimeout(() => {
shutdownCleanup(() => {
this.finish();
})
});
}, 1000);
});

16
testing/mochitest/bootstrap.js поставляемый
Просмотреть файл

@ -13,7 +13,7 @@ function loadChromeScripts(win) {
Services.scriptloader.loadSubScript("chrome://mochikit/content/browser-test.js", win);
}
/////// Android ///////
// ///// Android ///////
Cu.importGlobalProperties(["TextDecoder"]);
@ -46,25 +46,25 @@ function androidStartup(data, reason) {
}
}
/////// Desktop ///////
// ///// Desktop ///////
var WindowListener = {
// browser-test.js is only loaded into the first window. Setup that
// needs to happen in all navigator:browser windows should go here.
setupWindow: function(win) {
setupWindow(win) {
win.nativeConsole = win.console;
ChromeUtils.defineModuleGetter(win, "console",
"resource://gre/modules/Console.jsm");
},
tearDownWindow: function(win) {
tearDownWindow(win) {
if (win.nativeConsole) {
win.console = win.nativeConsole;
win.nativeConsole = undefined;
}
},
onOpenWindow: function (win) {
onOpenWindow(win) {
win = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindow);
win.addEventListener("load", function() {
@ -73,14 +73,14 @@ var WindowListener = {
}
}, {once: true});
}
}
};
function loadMochitest(e) {
let flavor = e.detail[0];
let url = e.detail[1];
let win = Services.wm.getMostRecentWindow("navigator:browser");
win.removeEventListener('mochitest-load', loadMochitest);
win.removeEventListener("mochitest-load", loadMochitest);
// for mochitest-plain, navigating to the url is all we need
win.loadURI(url);
@ -101,7 +101,7 @@ function startup(data, reason) {
let win = Services.wm.getMostRecentWindow("navigator:browser");
// wait for event fired from start_desktop.js containing the
// suite and url to load
win.addEventListener('mochitest-load', loadMochitest);
win.addEventListener("mochitest-load", loadMochitest);
}
}

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

@ -15,7 +15,7 @@ const SIMPLETEST_OVERRIDES =
["ok", "is", "isnot", "todo", "todo_is", "todo_isnot", "info", "expectAssertions", "requestCompleteLog"];
// non-android is bootstrapped by marionette
if (Services.appinfo.OS == 'Android') {
if (Services.appinfo.OS == "Android") {
window.addEventListener("load", function() {
window.addEventListener("MozAfterPaint", function() {
setTimeout(testInit, 0);
@ -29,17 +29,17 @@ var TabDestroyObserver = {
outstanding: new Set(),
promiseResolver: null,
init: function() {
init() {
Services.obs.addObserver(this, "message-manager-close");
Services.obs.addObserver(this, "message-manager-disconnect");
},
destroy: function() {
destroy() {
Services.obs.removeObserver(this, "message-manager-close");
Services.obs.removeObserver(this, "message-manager-disconnect");
},
observe: function(subject, topic, data) {
observe(subject, topic, data) {
if (topic == "message-manager-close") {
this.outstanding.add(subject);
} else if (topic == "message-manager-disconnect") {
@ -50,7 +50,7 @@ var TabDestroyObserver = {
}
},
wait: function() {
wait() {
if (!this.outstanding.size) {
return Promise.resolve();
}
@ -230,7 +230,7 @@ function takeInstrumentation() {
namespaceURI: element.namespaceURI,
localName: element.localName,
binding: (binding && binding != "none") ? binding : null,
}
};
}
// The selector for just this element
@ -475,7 +475,7 @@ Tester.prototype = {
start: function Tester_start() {
TabDestroyObserver.init();
//if testOnLoad was not called, then gConfig is not defined
// if testOnLoad was not called, then gConfig is not defined
if (!gConfig)
gConfig = readConfig();
@ -676,8 +676,7 @@ Tester.prototype = {
if (isGenerator(result)) {
this.SimpleTest.ok(false, "Cleanup function returned a generator");
}
}
catch (ex) {
} catch (ex) {
this.currentTest.addResult(new testResult({
name: "Cleanup function threw an exception",
ex,
@ -717,7 +716,7 @@ Tester.prototype = {
this.PromiseTestUtils.assertNoUncaughtRejections();
this.PromiseTestUtils.assertNoMoreExpectedRejections();
Object.keys(window).forEach(function (prop) {
Object.keys(window).forEach(function(prop) {
if (parseInt(prop) == prop) {
// This is a string which when parsed as an integer and then
// stringified gives the original string. As in, this is in fact a
@ -839,8 +838,7 @@ Tester.prototype = {
// Dump memory stats for main thread.
if (Cc["@mozilla.org/xre/runtime;1"]
.getService(Ci.nsIXULRuntime)
.processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT)
{
.processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT) {
this.MemoryStats.dump(this.currentTestIndex,
this.currentTest.path,
gConfig.dumpOutputDirectory,
@ -883,7 +881,7 @@ Tester.prototype = {
// frames and browser intentionally kept alive until shutdown to
// eliminate false positives.
if (gConfig.testRoot == "browser") {
//Skip if SeaMonkey
// Skip if SeaMonkey
if (AppConstants.MOZ_APP_NAME != "seamonkey") {
// Replace the document currently loaded in the browser's sidebar.
// This will prevent false positives for tests that were the last
@ -1019,7 +1017,7 @@ Tester.prototype = {
this.SimpleTest[m] = this[m];
}, scope);
//load the tools to work with chrome .jar and remote
// load the tools to work with chrome .jar and remote
try {
this._scriptLoader.loadSubScript("chrome://mochikit/content/chrome-harness.js", scope);
} catch (ex) { /* no chrome-harness tools */ }
@ -1090,7 +1088,7 @@ Tester.prototype = {
}));
// We timed out, so we've already cleaned up for this test, just get outta here.
return;
} else {
}
currentTest.addResult(new testResult({
name: "Uncaught exception",
pass: this.SimpleTest.isExpectingUncaughtException(),
@ -1098,7 +1096,7 @@ Tester.prototype = {
stack: (typeof ex == "object" && "stack" in ex) ? ex.stack : null,
allowFailure: currentTest.allowFailure,
}));
}
}
PromiseTestUtils.assertNoUncaughtRejections();
this.SimpleTest.info("Leaving test " + task.name);
@ -1129,8 +1127,7 @@ Tester.prototype = {
// will trigger the next test when it is done.
if (this.currentTest.scope.__done) {
this.nextTest();
}
else {
} else {
var self = this;
var timeoutExpires = Date.now() + gTimeoutSeconds * 1000;
var waitUntilAtLeast = timeoutExpires - 1000;
@ -1178,7 +1175,7 @@ Tester.prototype = {
}
},
QueryInterface: function(aIID) {
QueryInterface(aIID) {
if (aIID.equals(Ci.nsIConsoleListener) ||
aIID.equals(Ci.nsISupports))
return this;
@ -1257,6 +1254,7 @@ function testResult({ name, pass, todo, ex, stack, allowFailure }) {
if (gConfig.debugOnFailure) {
// You've hit this line because you requested to break into the
// debugger upon a testcase failure on your test run.
// eslint-disable-next-line no-debugger
debugger;
}
}
@ -1310,7 +1308,7 @@ function testScope(aTester, aTest, expected) {
this.executeSoon = function test_executeSoon(func) {
Services.tm.dispatchToMainThread({
run: function() {
run() {
func();
}
});
@ -1384,7 +1382,7 @@ function testScope(aTester, aTest, expected) {
self.__tester.structuredLogger.deactivateBuffering();
self.registerCleanupFunction(function() {
self.__tester.structuredLogger.activateBuffering();
})
});
};
// If we're running a test that requires unsafe CPOWs, create a
@ -1479,7 +1477,7 @@ testScope.prototype = {
* is(result, "foo");
* });
*/
add_task: function(aFunction) {
add_task(aFunction) {
if (!this.__tasks) {
this.waitForExplicitFinish();
this.__tasks = [];

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

@ -35,7 +35,7 @@ function getResolvedURI(url) {
try {
resolvedURI = resolvedURI.QueryInterface(Ci.nsIJARURI);
} catch (ex) {} //not a jar file
} catch (ex) {} // not a jar file
return resolvedURI;
}
@ -57,24 +57,22 @@ function getChromeDir(resolvedURI) {
return chromeDir.parent.QueryInterface(Ci.nsIFile);
}
//used by tests to determine their directory based off window.location.path
// used by tests to determine their directory based off window.location.path
function getRootDirectory(path, chromeURI) {
if (chromeURI === undefined)
{
if (chromeURI === undefined) {
chromeURI = getChromeURI(path);
}
var myURL = chromeURI.QueryInterface(Ci.nsIURL);
var mydir = myURL.directory;
if (mydir.match('/$') != '/')
{
mydir += '/';
if (mydir.match("/$") != "/") {
mydir += "/";
}
return chromeURI.prePath + mydir;
}
//used by tests to determine their directory based off window.location.path
// used by tests to determine their directory based off window.location.path
function getChromePrePath(path, chromeURI) {
if (chromeURI === undefined) {
@ -124,19 +122,19 @@ function extractJarToTmp(jar) {
var fileName = fileHandler.getFileFromURLSpec(jar.JARFile.spec);
zReader.open(fileName);
//filepath represents the path in the jar file without the filename
// filepath represents the path in the jar file without the filename
var filepath = "";
var parts = jar.JAREntry.split('/');
for (var i =0; i < parts.length - 1; i++) {
if (parts[i] != '') {
filepath += parts[i] + '/';
var parts = jar.JAREntry.split("/");
for (var i = 0; i < parts.length - 1; i++) {
if (parts[i] != "") {
filepath += parts[i] + "/";
}
}
/* Create dir structure first, no guarantee about ordering of directories and
* files returned from findEntries.
*/
var dirs = zReader.findEntries(filepath + '*/');
var dirs = zReader.findEntries(filepath + "*/");
while (dirs.hasMore()) {
var targetDir = buildRelativePath(dirs.getNext(), tmpdir, filepath);
// parseInt is used because octal escape sequences cause deprecation warnings
@ -146,11 +144,11 @@ function extractJarToTmp(jar) {
}
}
//now do the files
// now do the files
var files = zReader.findEntries(filepath + "*");
while (files.hasMore()) {
var fname = files.getNext();
if (fname.substr(-1) != '/') {
if (fname.substr(-1) != "/") {
var targetFile = buildRelativePath(fname, tmpdir, filepath);
zReader.extract(fname, targetFile);
}
@ -183,7 +181,7 @@ function getTestFilePath(path) {
}
// Then walk by the given relative path
path.split("/")
.forEach(function (p) {
.forEach(function(p) {
if (p == "..") {
file = file.parent;
} else if (p != ".") {
@ -197,14 +195,13 @@ function getTestFilePath(path) {
* Simple utility function to take the directory structure in jarentryname and
* translate that to a path of a nsIFile.
*/
function buildRelativePath(jarentryname, destdir, basepath)
{
var baseParts = basepath.split('/');
if (baseParts[baseParts.length-1] == '') {
function buildRelativePath(jarentryname, destdir, basepath) {
var baseParts = basepath.split("/");
if (baseParts[baseParts.length - 1] == "") {
baseParts.pop();
}
var parts = jarentryname.split('/');
var parts = jarentryname.split("/");
var targetFile = Cc["@mozilla.org/file/local;1"]
.createInstance(Ci.nsIFile);
@ -238,7 +235,7 @@ function readConfig(filename) {
}
function getTestList(params, callback) {
var baseurl = 'chrome://mochitests/content';
var baseurl = "chrome://mochitests/content";
if (window.parseQueryString) {
params = parseQueryString(location.search.substring(1), true);
}
@ -258,5 +255,5 @@ function getTestList(params, callback) {
}
params = config;
getTestManifest("http://mochi.test:8888/" + params.manifestFile, params, callback);
return;
}

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

@ -19,20 +19,20 @@ info("\nProfile::PluginUtilsLoadTime: " + (loadTime - start) + "\n");
function starttest() {
SimpleTest.waitForExplicitFinish();
var startTime = new Date();
//increase the runtime of the test so it is detectible, otherwise we get 0-1ms
// increase the runtime of the test so it is detectible, otherwise we get 0-1ms
runtimes = 100;
function runTest(plugin) {
is(plugin.version, "1.0.0.0", "Make sure version is correct");
is(plugin.name, "Test Plug-in");
};
}
while (runtimes > 0) {
ok(PluginUtils.withTestPlugin(runTest), "Test plugin should be found");
--runtimes;
}
var endTime = new Date();
info("\nProfile::PluginUtilsRunTime: " + (endTime-startTime) + "\n");
info("\nProfile::PluginUtilsRunTime: " + (endTime - startTime) + "\n");
SimpleTest.finish();
};
}
</script>
</body>
</html>

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

@ -6,10 +6,10 @@ function skipTests(tests, startTestPattern, endTestPattern) {
var startIndex = 0, endIndex = tests.length - 1;
for (var i = 0; i < tests.length; ++i) {
var test_path;
if ((tests[i] instanceof Object) && ('test' in tests[i])) {
test_path = tests[i]['test']['url'];
} else if ((tests[i] instanceof Object) && ('url' in tests[i])) {
test_path = tests[i]['url'];
if ((tests[i] instanceof Object) && ("test" in tests[i])) {
test_path = tests[i].test.url;
} else if ((tests[i] instanceof Object) && ("url" in tests[i])) {
test_path = tests[i].url;
} else {
test_path = tests[i];
}

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

@ -14,22 +14,22 @@ function parseTestManifest(testManifest, params, callback) {
return;
}
// For mochitest-chrome and mochitest-browser-chrome harnesses, we
// For mochitest-chrome and mochitest-browser-chrome harnesses, we
// define tests as links[testname] = true.
// For mochitest-plain, we define lists as an array of testnames.
for (var obj of testManifest['tests']) {
var path = obj['path'];
for (var obj of testManifest.tests) {
var path = obj.path;
// Note that obj.disabled may be "". We still want to skip in that case.
if ("disabled" in obj) {
dump("TEST-SKIPPED | " + path + " | " + obj.disabled + "\n");
continue;
}
if (params.testRoot != 'tests' && params.testRoot !== undefined) {
name = params.baseurl + '/' + params.testRoot + '/' + path;
links[name] = {'test': {'url': name, 'expected': obj['expected'], 'uses-unsafe-cpows': obj['uses-unsafe-cpows']}};
if (params.testRoot != "tests" && params.testRoot !== undefined) {
name = params.baseurl + "/" + params.testRoot + "/" + path;
links[name] = {"test": {"url": name, "expected": obj.expected, "uses-unsafe-cpows": obj["uses-unsafe-cpows"]}};
} else {
name = params.testPrefix + path;
paths.push({'test': {'url': name, 'expected': obj['expected'], 'uses-unsafe-cpows': obj['uses-unsafe-cpows']}});
paths.push({"test": {"url": name, "expected": obj.expected, "uses-unsafe-cpows": obj["uses-unsafe-cpows"]}});
}
}
if (paths.length > 0) {
@ -56,7 +56,7 @@ function getTestManifest(url, params, callback) {
callback({});
}
}
}
};
req.send();
}
@ -84,14 +84,14 @@ function filterTests(filter, testList, runOnly) {
return testList;
}
if ('runtests' in filter) {
if ("runtests" in filter) {
runtests = filter.runtests;
}
if ('excludetests' in filter) {
if ("excludetests" in filter) {
excludetests = filter.excludetests;
}
if (!('runtests' in filter) && !('excludetests' in filter)) {
if (runOnly == 'true') {
if (!("runtests" in filter) && !("excludetests" in filter)) {
if (runOnly == "true") {
runtests = filter;
} else {
excludetests = filter;
@ -103,16 +103,16 @@ function filterTests(filter, testList, runOnly) {
// filteredTests.
if (Object.keys(runtests).length) {
for (var i = 0; i < testList.length; i++) {
if ((testList[i] instanceof Object) && ('test' in testList[i])) {
var testpath = testList[i]['test']['url'];
if ((testList[i] instanceof Object) && ("test" in testList[i])) {
var testpath = testList[i].test.url;
} else {
var testpath = testList[i];
}
var tmppath = testpath.replace(/^\//, '');
var tmppath = testpath.replace(/^\//, "");
for (var f in runtests) {
// Remove leading /tests/ if exists
file = f.replace(/^\//, '')
file = file.replace(/^tests\//, '')
file = f.replace(/^\//, "");
file = file.replace(/^tests\//, "");
// Match directory or filename, testList has <testroot>/<path>
if (tmppath.match(testRoot + "/" + file) != null) {
@ -134,16 +134,16 @@ function filterTests(filter, testList, runOnly) {
var refilteredTests = [];
for (var i = 0; i < filteredTests.length; i++) {
var found = false;
if ((filteredTests[i] instanceof Object) && ('test' in filteredTests[i])) {
var testpath = filteredTests[i]['test']['url'];
if ((filteredTests[i] instanceof Object) && ("test" in filteredTests[i])) {
var testpath = filteredTests[i].test.url;
} else {
var testpath = filteredTests[i];
}
var tmppath = testpath.replace(/^\//, '');
var tmppath = testpath.replace(/^\//, "");
for (var f in excludetests) {
// Remove leading /tests/ if exists
file = f.replace(/^\//, '')
file = file.replace(/^tests\//, '')
file = f.replace(/^\//, "");
file = file.replace(/^tests\//, "");
// Match directory or filename, testList has <testroot>/<path>
if (tmppath.match(testRoot + "/" + file) != null) {

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

@ -1,26 +1,23 @@
var gTestURL = '';
var gTestURL = "";
function addPermissions()
{
function addPermissions() {
SpecialPowers.pushPermissions(
[{ type: "browser", allow: true, context: document }],
addPreferences);
}
function addPreferences()
{
function addPreferences() {
SpecialPowers.pushPrefEnv(
{"set": [["dom.mozBrowserFramesEnabled", true]]},
insertFrame);
}
function insertFrame()
{
function insertFrame() {
SpecialPowers.nestedFrameSetup();
var iframe = document.createElement('iframe');
iframe.id = 'nested-parent-frame';
var iframe = document.createElement("iframe");
iframe.id = "nested-parent-frame";
iframe.width = "100%";
iframe.height = "100%";
iframe.scoring = "no";
@ -28,4 +25,4 @@ function insertFrame()
iframe.setAttribute("mozbrowser", "true");
iframe.src = gTestURL;
document.getElementById("holder-div").appendChild(iframe);
}
}

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

@ -3,8 +3,7 @@
<title>redirecting...</title>
<script type="text/javascript">
function redirect(aURL)
{
function redirect(aURL) {
// We create a listener for this event in browser-test.js which will
// get picked up when specifying --flavor=chrome or --flavor=a11y
var event = new CustomEvent("contentEvent", {
@ -17,8 +16,7 @@
document.dispatchEvent(event);
}
function redirectToHarness()
{
function redirectToHarness() {
redirect("chrome://mochikit/content/harness.xul");
}

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

@ -20,48 +20,46 @@ var server; // for use in the shutdown handler, if necessary
//
// HTML GENERATION
//
var tags = ['A', 'ABBR', 'ACRONYM', 'ADDRESS', 'APPLET', 'AREA', 'B', 'BASE',
'BASEFONT', 'BDO', 'BIG', 'BLOCKQUOTE', 'BODY', 'BR', 'BUTTON',
'CAPTION', 'CENTER', 'CITE', 'CODE', 'COL', 'COLGROUP', 'DD',
'DEL', 'DFN', 'DIR', 'DIV', 'DL', 'DT', 'EM', 'FIELDSET', 'FONT',
'FORM', 'FRAME', 'FRAMESET', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6',
'HEAD', 'HR', 'HTML', 'I', 'IFRAME', 'IMG', 'INPUT', 'INS',
'ISINDEX', 'KBD', 'LABEL', 'LEGEND', 'LI', 'LINK', 'MAP', 'MENU',
'META', 'NOFRAMES', 'NOSCRIPT', 'OBJECT', 'OL', 'OPTGROUP',
'OPTION', 'P', 'PARAM', 'PRE', 'Q', 'S', 'SAMP', 'SCRIPT',
'SELECT', 'SMALL', 'SPAN', 'STRIKE', 'STRONG', 'STYLE', 'SUB',
'SUP', 'TABLE', 'TBODY', 'TD', 'TEXTAREA', 'TFOOT', 'TH', 'THEAD',
'TITLE', 'TR', 'TT', 'U', 'UL', 'VAR'];
var tags = ["A", "ABBR", "ACRONYM", "ADDRESS", "APPLET", "AREA", "B", "BASE",
"BASEFONT", "BDO", "BIG", "BLOCKQUOTE", "BODY", "BR", "BUTTON",
"CAPTION", "CENTER", "CITE", "CODE", "COL", "COLGROUP", "DD",
"DEL", "DFN", "DIR", "DIV", "DL", "DT", "EM", "FIELDSET", "FONT",
"FORM", "FRAME", "FRAMESET", "H1", "H2", "H3", "H4", "H5", "H6",
"HEAD", "HR", "HTML", "I", "IFRAME", "IMG", "INPUT", "INS",
"ISINDEX", "KBD", "LABEL", "LEGEND", "LI", "LINK", "MAP", "MENU",
"META", "NOFRAMES", "NOSCRIPT", "OBJECT", "OL", "OPTGROUP",
"OPTION", "P", "PARAM", "PRE", "Q", "S", "SAMP", "SCRIPT",
"SELECT", "SMALL", "SPAN", "STRIKE", "STRONG", "STYLE", "SUB",
"SUP", "TABLE", "TBODY", "TD", "TEXTAREA", "TFOOT", "TH", "THEAD",
"TITLE", "TR", "TT", "U", "UL", "VAR"];
/**
* Below, we'll use makeTagFunc to create a function for each of the
* strings in 'tags'. This will allow us to use s-expression like syntax
* to create HTML.
*/
function makeTagFunc(tagName)
{
return function (attrs /* rest... */)
{
function makeTagFunc(tagName) {
return function(attrs /* rest... */) {
var startChildren = 0;
var response = "";
// write the start tag and attributes
response += "<" + tagName;
// if attr is an object, write attributes
if (attrs && typeof attrs == 'object') {
if (attrs && typeof attrs == "object") {
startChildren = 1;
for (let key in attrs) {
const value = attrs[key];
var val = "" + value;
response += " " + key + '="' + val.replace('"','&quot;') + '"';
response += " " + key + '="' + val.replace('"', "&quot;") + '"';
}
}
response += ">";
// iterate through the rest of the args
for (var i = startChildren; i < arguments.length; i++) {
if (typeof arguments[i] == 'function') {
if (typeof arguments[i] == "function") {
response += arguments[i]();
} else {
response += arguments[i];
@ -71,7 +69,7 @@ function makeTagFunc(tagName)
// write the close tag
response += "</" + tagName + ">\n";
return response;
}
};
}
function makeTags() {
@ -84,21 +82,19 @@ function makeTags() {
var _quitting = false;
/** Quit when all activity has completed. */
function serverStopped()
{
function serverStopped() {
_quitting = true;
}
// only run the "main" section if httpd.js was loaded ahead of us
if (this["nsHttpServer"]) {
if (this.nsHttpServer) {
//
// SCRIPT CODE
//
runServer();
// We can only have gotten here if the /server/shutdown path was requested.
if (_quitting)
{
if (_quitting) {
dumpn("HTTP server stopped, all pending requests complete");
quit(0);
}
@ -117,21 +113,20 @@ var SERVER_PORT;
//
// SERVER SETUP
//
function runServer()
{
function runServer() {
serverBasePath = __LOCATION__.parent;
server = createMochitestServer(serverBasePath);
//verify server address
//if a.b.c.d or 'localhost'
// verify server address
// if a.b.c.d or 'localhost'
if (typeof(_SERVER_ADDR) != "undefined") {
if (_SERVER_ADDR == "localhost") {
gServerAddress = _SERVER_ADDR;
} else {
var quads = _SERVER_ADDR.split('.');
var quads = _SERVER_ADDR.split(".");
if (quads.length == 4) {
var invalid = false;
for (var i=0; i < 4; i++) {
for (var i = 0; i < 4; i++) {
if (quads[i] < 0 || quads[i] > 255)
invalid = true;
}
@ -206,8 +201,7 @@ function runServer()
}
/** Creates and returns an HTTP server configured to serve Mochitests. */
function createMochitestServer(serverBasePath)
{
function createMochitestServer(serverBasePath) {
var server = new nsHttpServer();
server.registerDirectory("/", serverBasePath);
@ -229,15 +223,14 @@ function createMochitestServer(serverBasePath)
var serverRoot =
{
getFile: function getFile(path)
{
getFile: function getFile(path) {
var file = serverBasePath.clone().QueryInterface(Ci.nsIFile);
path.split("/").forEach(function(p) {
file.appendRelativePath(p);
});
return file;
},
QueryInterface: function(aIID) { return this; }
QueryInterface(aIID) { return this; }
};
server.setObjectState("SERVER_ROOT", serverRoot);
@ -252,8 +245,7 @@ function createMochitestServer(serverBasePath)
* requests, so that it can properly respond to requests on any of the hosts it
* serves.
*/
function processLocations(server)
{
function processLocations(server) {
var serverLocations = serverBasePath.clone();
serverLocations.append("server-locations.txt");
@ -283,8 +275,7 @@ function processLocations(server)
var line = {};
var lineno = 0;
var seenPrimary = false;
do
{
do {
var more = lis.readLine(line);
lineno++;
@ -297,12 +288,9 @@ function processLocations(server)
throw new Error("Syntax error in server-locations.txt, line " + lineno);
var [, scheme, host, port, options] = match;
if (options)
{
if (options.split(",").includes("primary"))
{
if (seenPrimary)
{
if (options) {
if (options.split(",").includes("primary")) {
if (seenPrimary) {
throw new Error("Multiple primary locations in server-locations.txt, " +
"line " + lineno);
}
@ -321,8 +309,7 @@ function processLocations(server)
// PATH HANDLERS
// /server/shutdown
function serverShutdown(metadata, response)
{
function serverShutdown(metadata, response) {
response.setStatusLine("1.1", 200, "OK");
response.setHeader("Content-type", "text/plain", false);
@ -334,8 +321,7 @@ function serverShutdown(metadata, response)
}
// /server/debug?[012]
function serverDebug(metadata, response)
{
function serverDebug(metadata, response) {
response.setStatusLine(metadata.httpVersion, 400, "Bad debugging level");
if (metadata.queryString.length !== 1)
return;
@ -374,8 +360,7 @@ function serverDebug(metadata, response)
* Creates a generator that iterates over the contents of
* an nsIFile directory.
*/
function* dirIter(dir)
{
function* dirIter(dir) {
var en = dir.directoryEntries;
while (en.hasMoreElements()) {
var file = en.getNext();
@ -387,8 +372,7 @@ function* dirIter(dir)
* Builds an optionally nested object containing links to the
* files and directories within dir.
*/
function list(requestPath, directory, recurse)
{
function list(requestPath, directory, recurse) {
var count = 0;
var path = requestPath;
if (path.charAt(path.length - 1) != "/") {
@ -427,11 +411,9 @@ function list(requestPath, directory, recurse)
if (recurse && file.isDirectory()) {
[links[key], childCount] = list(key, file, recurse);
count += childCount;
} else {
if (file.leafName.charAt(0) != '.') {
links[key] = {'test': {'url': key, 'expected': 'pass'}};
} else if (file.leafName.charAt(0) != ".") {
links[key] = {"test": {"url": key, "expected": "pass"}};
}
}
}
return [links, count];
@ -442,8 +424,7 @@ function list(requestPath, directory, recurse)
* is a test case to be executed in the harness, or just
* a supporting file.
*/
function isTest(filename, pattern)
{
function isTest(filename, pattern) {
if (pattern)
return pattern.test(filename);
@ -452,7 +433,7 @@ function isTest(filename, pattern)
var testPrefix = typeof(_TEST_PREFIX) == "string" ? _TEST_PREFIX : "test_";
var testPattern = new RegExp("^" + testPrefix);
var pathPieces = filename.split('/');
var pathPieces = filename.split("/");
return testPattern.test(pathPieces[pathPieces.length - 1]) &&
!filename.includes(".js") &&
@ -463,8 +444,7 @@ function isTest(filename, pattern)
/**
* Transform nested hashtables of paths to nested HTML lists.
*/
function linksToListItems(links)
{
function linksToListItems(links) {
var response = "";
var children = "";
for (let link in links) {
@ -487,8 +467,8 @@ function linksToListItems(links)
if ((bug_title == null) || (bug_num == null)) {
response += LI({class: classVal}, A({href: link}, link), children);
} else {
var bug_url = "https://bugzilla.mozilla.org/show_bug.cgi?id="+bug_num;
response += LI({class: classVal}, A({href: link}, link), " - ", A({href: bug_url}, "Bug "+bug_num), children);
var bug_url = "https://bugzilla.mozilla.org/show_bug.cgi?id=" + bug_num;
response += LI({class: classVal}, A({href: link}, link), " - ", A({href: bug_url}, "Bug " + bug_num), children);
}
}
@ -498,18 +478,17 @@ function linksToListItems(links)
/**
* Transform nested hashtables of paths to a flat table rows.
*/
function linksToTableRows(links, recursionLevel)
{
function linksToTableRows(links, recursionLevel) {
var response = "";
for (let link in links) {
const value = links[link];
var classVal = (!isTest(link) && ((value instanceof Object) && ('test' in value)))
var classVal = (!isTest(link) && ((value instanceof Object) && ("test" in value)))
? "non-test invisible"
: "";
var spacer = "padding-left: " + (10 * recursionLevel) + "px";
if ((value instanceof Object) && !('test' in value)) {
if ((value instanceof Object) && !("test" in value)) {
response += TR({class: "dir", id: "tr-" + link },
TD({colspan: "3"}, "&#160;"),
TD({style: spacer},
@ -546,21 +525,20 @@ function linksToTableRows(links, recursionLevel)
function arrayOfTestFiles(linkArray, fileArray, testPattern) {
for (let link in linkArray) {
const value = linkArray[link];
if ((value instanceof Object) && !('test' in value)) {
if ((value instanceof Object) && !("test" in value)) {
arrayOfTestFiles(value, fileArray, testPattern);
} else if (isTest(link, testPattern) && (value instanceof Object)) {
fileArray.push(value['test'])
fileArray.push(value.test);
}
}
}
/**
* Produce a flat array of test file paths to be executed in the harness.
*/
function jsonArrayOfTestFiles(links)
{
function jsonArrayOfTestFiles(links) {
var testFiles = [];
arrayOfTestFiles(links, testFiles);
testFiles = testFiles.map(function(file) { return '"' + file['url'] + '"'; });
testFiles = testFiles.map(function(file) { return '"' + file.url + '"'; });
return "[" + testFiles.join(",\n") + "]";
}
@ -568,8 +546,7 @@ function jsonArrayOfTestFiles(links)
/**
* Produce a normal directory listing.
*/
function regularListing(metadata, response)
{
function regularListing(metadata, response) {
var [links, count] = list(metadata.path,
metadata.getProperty("directory"),
false);
@ -591,8 +568,7 @@ function regularListing(metadata, response)
* Read a manifestFile located at the root of the server's directory and turn
* it into an object for creating a table of clickable links for each test.
*/
function convertManifestToTestLinks(root, manifest)
{
function convertManifestToTestLinks(root, manifest) {
ChromeUtils.import("resource://gre/modules/NetUtil.jsm");
var manifestFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
@ -605,7 +581,7 @@ function convertManifestToTestLinks(root, manifest)
var manifestObj = JSON.parse(NetUtil.readInputStreamToString(manifestStream,
manifestStream.available()));
var paths = manifestObj.tests;
var pathPrefix = '/' + root + '/'
var pathPrefix = "/" + root + "/";
return [paths.reduce(function(t, p) { t[pathPrefix + p.path] = true; return t; }, {}),
paths.length];
}
@ -613,8 +589,7 @@ function convertManifestToTestLinks(root, manifest)
/**
* Produce a test harness page that has one remote iframe
*/
function nestedTest(metadata, response)
{
function nestedTest(metadata, response) {
response.setStatusLine("1.1", 200, "OK");
response.setHeader("Content-type", "text/html;charset=utf-8", false);
response.write(
@ -639,22 +614,21 @@ function nestedTest(metadata, response)
* Produce a test harness page containing all the test cases
* below it, recursively.
*/
function testListing(metadata, response)
{
function testListing(metadata, response) {
var links = {};
var count = 0;
if (!metadata.queryString.includes('manifestFile')) {
if (!metadata.queryString.includes("manifestFile")) {
[links, count] = list(metadata.path,
metadata.getProperty("directory"),
true);
} else if (typeof(Components) != undefined) {
var manifest = metadata.queryString.match(/manifestFile=([^&]+)/)[1];
[links, count] = convertManifestToTestLinks(metadata.path.split('/')[1],
[links, count] = convertManifestToTestLinks(metadata.path.split("/")[1],
manifest);
}
var table_class = metadata.queryString.indexOf("hideResultsTable=1") > -1 ? "invisible": "";
var table_class = metadata.queryString.indexOf("hideResultsTable=1") > -1 ? "invisible" : "";
let testname = (metadata.queryString.indexOf("testname=") > -1)
? metadata.queryString.match(/testname=([^&]+)/)[1]
@ -697,15 +671,15 @@ function testListing(metadata, response)
P({style: "float: right;"},
SMALL(
"Based on the ",
A({href:"http://www.mochikit.com/"}, "MochiKit"),
A({href: "http://www.mochikit.com/"}, "MochiKit"),
" unit tests."
)
),
DIV({class: "status"},
H1({id: "indicator"}, "Status"),
H2({id: "pass"}, "Passed: ", SPAN({id: "pass-count"},"0")),
H2({id: "fail"}, "Failed: ", SPAN({id: "fail-count"},"0")),
H2({id: "fail"}, "Todo: ", SPAN({id: "todo-count"},"0"))
H2({id: "pass"}, "Passed: ", SPAN({id: "pass-count"}, "0")),
H2({id: "fail"}, "Failed: ", SPAN({id: "fail-count"}, "0")),
H2({id: "fail"}, "Todo: ", SPAN({id: "todo-count"}, "0"))
),
DIV({class: "clear"}),
DIV({id: "current-test"},
@ -746,8 +720,7 @@ function testListing(metadata, response)
* Respond to requests that match a file system directory.
* Under the tests/ directory, return a test harness page.
*/
function defaultDirHandler(metadata, response)
{
function defaultDirHandler(metadata, response) {
response.setStatusLine("1.1", 200, "OK");
response.setHeader("Content-type", "text/html;charset=utf-8", false);
try {

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

@ -2,8 +2,8 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const flavor = __webDriverArguments[0]["flavor"];
const url = __webDriverArguments[0]["testUrl"];
const flavor = __webDriverArguments[0].flavor;
const url = __webDriverArguments[0].testUrl;
let wm = Cc["@mozilla.org/appshell/window-mediator;1"]
.getService(Ci.nsIWindowMediator);
@ -11,5 +11,5 @@ let win = wm.getMostRecentWindow("navigator:browser");
// mochikit's bootstrap.js has set up a listener for this event. It's
// used so bootstrap.js knows which flavor and url to load.
let ev = new CustomEvent('mochitest-load', {'detail': [flavor, url]});
let ev = new CustomEvent("mochitest-load", {"detail": [flavor, url]});
win.dispatchEvent(ev);

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

@ -0,0 +1,7 @@
"use strict";
module.exports = {
"extends": [
"plugin:mozilla/browser-test"
]
};

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

@ -1,12 +1,11 @@
function getLastEventDetails(browser)
{
function getLastEventDetails(browser) {
return ContentTask.spawn(browser, {}, async function() {
return content.document.getElementById('out').textContent;
return content.document.getElementById("out").textContent;
});
}
add_task(async function() {
let onClickEvt = 'document.getElementById("out").textContent = event.target.localName + "," + event.clientX + "," + event.clientY;'
let onClickEvt = 'document.getElementById("out").textContent = event.target.localName + "," + event.clientX + "," + event.clientY;';
const url = "<body onclick='" + onClickEvt + "' style='margin: 0'>" +
"<button id='one' style='margin: 0; margin-left: 16px; margin-top: 14px; width: 30px; height: 40px;'>Test</button>" +
"<div onmousedown='event.preventDefault()' style='margin: 0; width: 80px; height: 60px;'>Other</div>" +

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

@ -1,6 +1,6 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
'use strict';
"use strict";
function isDOMLoaded(browser) {
return ContentTask.spawn(browser, null, async function() {
@ -12,7 +12,7 @@ function isDOMLoaded(browser) {
// It checks if calling BrowserTestUtils.browserLoaded() yields
// browser object.
add_task(async function() {
let tab = BrowserTestUtils.addTab(gBrowser, 'http://example.com');
let tab = BrowserTestUtils.addTab(gBrowser, "http://example.com");
let browser = tab.linkedBrowser;
await BrowserTestUtils.browserLoaded(browser);
await isDOMLoaded(browser);
@ -27,20 +27,20 @@ add_task(async function() {
`http://mochi.test:8888`,
`http://test:80`,
];
//Add tabs, get the respective browsers
// Add tabs, get the respective browsers
let browsers = tabURLs.map(u => BrowserTestUtils.addTab(gBrowser, u).linkedBrowser);
//wait for promises to settle
await Promise.all((function*() {
// wait for promises to settle
await Promise.all((function* () {
for (let b of browsers) {
yield BrowserTestUtils.browserLoaded(b);
}
})());
let expected = 'Expected all promised browsers to have loaded.';
let expected = "Expected all promised browsers to have loaded.";
for (const browser of browsers) {
await isDOMLoaded(browser);
}
//cleanup
// cleanup
browsers
.map(browser => gBrowser.getTabForBrowser(browser))
.forEach(tab => gBrowser.removeTab(tab));

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

@ -5,39 +5,39 @@ function test() {
waitForExplicitFinish();
SimpleTest.doesThrow(function () {
getTestFilePath("/browser_getTestFile.js")
SimpleTest.doesThrow(function() {
getTestFilePath("/browser_getTestFile.js");
}, "getTestFilePath rejects absolute paths");
Promise.all([
OS.File.exists(getTestFilePath("browser_getTestFile.js"))
.then(function (exists) {
.then(function(exists) {
ok(exists, "getTestFilePath consider the path as being relative");
}),
OS.File.exists(getTestFilePath("./browser_getTestFile.js"))
.then(function (exists) {
.then(function(exists) {
ok(exists, "getTestFilePath also accepts explicit relative path");
}),
OS.File.exists(getTestFilePath("./browser_getTestFileTypo.xul"))
.then(function (exists) {
.then(function(exists) {
ok(!exists, "getTestFilePath do not throw if the file doesn't exists");
}),
OS.File.read(getTestFilePath("test-dir/test-file"))
.then(function (array) {
.then(function(array) {
is(decoder.decode(array), "foo\n", "getTestFilePath can reach sub-folder files 1/2");
}),
OS.File.read(getTestFilePath("./test-dir/test-file"))
.then(function (array) {
.then(function(array) {
is(decoder.decode(array), "foo\n", "getTestFilePath can reach sub-folder files 2/2");
})
]).then(function () {
]).then(function() {
finish();
}, function (error) {
}, function(error) {
ok(false, error);
finish();
});

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

@ -6,8 +6,7 @@ function test() {
try {
var prefs = Cc["@mozilla.org/preferences-service;1"].
getService(Ci.nsIPrefBranch);
}
catch (e) {
} catch (e) {
hasPrivileges = false;
}

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

@ -1,8 +1,7 @@
const gBaseURL = "https://example.com/browser/testing/mochitest/tests/browser/";
function promiseTabLoadEvent(tab, url)
{
function promiseTabLoadEvent(tab, url) {
let promise = BrowserTestUtils.browserLoaded(tab.linkedBrowser, false, url);
if (url) {
tab.linkedBrowser.loadURI(url);

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

@ -1,12 +1,12 @@
var headVar = "I'm a var in head file";
function headMethod() {
return true;
};
ok(true, "I'm a test in head file");
registerCleanupFunction(function() {
ok(true, "I'm a cleanup function in head file");
is(this.headVar, "I'm a var in head file", "Head cleanup function scope is correct");
});
var headVar = "I'm a var in head file";
function headMethod() {
return true;
}
ok(true, "I'm a test in head file");
registerCleanupFunction(function() {
ok(true, "I'm a cleanup function in head file");
is(this.headVar, "I'm a var in head file", "Head cleanup function scope is correct");
});

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

@ -0,0 +1,8 @@
"use strict";
module.exports = {
"extends": [
"plugin:mozilla/browser-test",
"plugin:mozilla/mochitest-test"
]
};

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

@ -12,7 +12,7 @@ https://bugzilla.mozilla.org/show_bug.cgi?id=1343659
const Cc = SpecialPowers.Cc;
const Ci = SpecialPowers.Ci;
let debug = Cc["@mozilla.org/xpcom/debug;1"].getService(Ci.nsIDebug2);
debug.assertion('failed assertion check', 'false', 'test_assertion.html', 15);
debug.assertion("failed assertion check", "false", "test_assertion.html", 15);
ok(true, "Should pass");
</script>
</head>

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

@ -12,7 +12,7 @@ https://bugzilla.mozilla.org/show_bug.cgi?id=1343659
const Cc = SpecialPowers.Cc;
const Ci = SpecialPowers.Ci;
let debug = Cc["@mozilla.org/xpcom/debug;1"].getService(Ci.nsIDebug2);
debug.abort('test_crash.html', 15);
debug.abort("test_crash.html", 15);
ok(true, "Should pass");
</script>
</head>