Bug 1313956: Async all the tests. r=aswan

MozReview-Commit-ID: CyNCfEsDD42

--HG--
extra : source : efc9b52a218f7ffd40ba346de74fd846a9059ceb
This commit is contained in:
Kris Maglione 2016-11-07 21:03:14 -08:00
parent 28452cb319
commit 9c000b319d
73 changed files with 1995 additions and 2223 deletions

View File

@ -29,4 +29,8 @@ module.exports = { // eslint-disable-line no-undef
"openExtensionContextMenu": true,
"CustomizableUI": true,
},
"rules": {
"no-shadow": 0,
},
};

View File

@ -4,37 +4,23 @@
function* runTests(options) {
function background(getTests) {
// Gets the current details of the browser action, and returns a
// promise that resolves to an object containing them.
function getDetails(tabId) {
return Promise.all([
browser.browserAction.getTitle({tabId}),
browser.browserAction.getPopup({tabId}),
browser.browserAction.getBadgeText({tabId}),
browser.browserAction.getBadgeBackgroundColor({tabId})]
).then(details => {
return Promise.resolve({title: details[0],
popup: details[1],
badge: details[2],
badgeBackgroundColor: details[3]});
});
}
async function checkDetails(expecting, tabId) {
let title = await browser.browserAction.getTitle({tabId});
browser.test.assertEq(expecting.title, title,
"expected value from getTitle");
function checkDetails(expecting, tabId) {
return getDetails(tabId).then(details => {
browser.test.assertEq(expecting.title, details.title,
"expected value from getTitle");
let popup = await browser.browserAction.getPopup({tabId});
browser.test.assertEq(expecting.popup, popup,
"expected value from getPopup");
browser.test.assertEq(expecting.popup, details.popup,
"expected value from getPopup");
let badge = await browser.browserAction.getBadgeText({tabId});
browser.test.assertEq(expecting.badge, badge,
"expected value from getBadge");
browser.test.assertEq(expecting.badge, details.badge,
"expected value from getBadge");
browser.test.assertEq(String(expecting.badgeBackgroundColor),
String(details.badgeBackgroundColor),
"expected value from getBadgeBackgroundColor");
});
let badgeBackgroundColor = await browser.browserAction.getBadgeBackgroundColor({tabId});
browser.test.assertEq(String(expecting.badgeBackgroundColor),
String(badgeBackgroundColor),
"expected value from getBadgeBackgroundColor");
}
let expectDefaults = expecting => {
@ -78,18 +64,15 @@ function* runTests(options) {
function nextTest() {
let test = tests.shift();
test(expecting => {
test(async expecting => {
// Check that the API returns the expected values, and then
// run the next test.
new Promise(resolve => {
return browser.tabs.query({active: true, currentWindow: true}, resolve);
}).then(tabs => {
return checkDetails(expecting, tabs[0].id);
}).then(() => {
// Check that the actual icon has the expected values, then
// run the next test.
browser.test.sendMessage("nextTest", expecting, tests.length);
});
let tabs = await browser.tabs.query({active: true, currentWindow: true});
await checkDetails(expecting, tabs[0].id);
// Check that the actual icon has the expected values, then
// run the next test.
browser.test.sendMessage("nextTest", expecting, tests.length);
});
}
@ -241,29 +224,28 @@ add_task(function* testTabSwitchContext() {
];
return [
expect => {
async expect => {
browser.test.log("Initial state, expect default properties.");
expectDefaults(details[0]).then(() => {
expect(details[0]);
});
await expectDefaults(details[0]);
expect(details[0]);
},
expect => {
async expect => {
browser.test.log("Change the icon in the current tab. Expect default properties excluding the icon.");
browser.browserAction.setIcon({tabId: tabs[0], path: "1.png"});
expectDefaults(details[0]).then(() => {
expect(details[1]);
});
await expectDefaults(details[0]);
expect(details[1]);
},
expect => {
async expect => {
browser.test.log("Create a new tab. Expect default properties.");
browser.tabs.create({active: true, url: "about:blank?0"}, tab => {
tabs.push(tab.id);
expectDefaults(details[0]).then(() => {
expect(details[0]);
});
});
let tab = await browser.tabs.create({active: true, url: "about:blank?0"});
tabs.push(tab.id);
await expectDefaults(details[0]);
expect(details[0]);
},
expect => {
async expect => {
browser.test.log("Change properties. Expect new properties.");
let tabId = tabs[1];
browser.browserAction.setIcon({tabId, path: "2.png"});
@ -273,9 +255,8 @@ add_task(function* testTabSwitchContext() {
browser.browserAction.setBadgeBackgroundColor({tabId, color: "#ff0000"});
browser.browserAction.disable(tabId);
expectDefaults(details[0]).then(() => {
expect(details[2]);
});
await expectDefaults(details[0]);
expect(details[2]);
},
expect => {
browser.test.log("Navigate to a new page. Expect no changes.");
@ -291,13 +272,12 @@ add_task(function* testTabSwitchContext() {
browser.tabs.update(tabs[1], {url: "about:blank?1"});
},
expect => {
async expect => {
browser.test.log("Switch back to the first tab. Expect previously set properties.");
browser.tabs.update(tabs[0], {active: true}, () => {
expect(details[1]);
});
await browser.tabs.update(tabs[0], {active: true});
expect(details[1]);
},
expect => {
async expect => {
browser.test.log("Change default values, expect those changes reflected.");
browser.browserAction.setIcon({path: "default-2.png"});
browser.browserAction.setPopup({popup: "default-2.html"});
@ -305,43 +285,39 @@ add_task(function* testTabSwitchContext() {
browser.browserAction.setBadgeText({text: "d2"});
browser.browserAction.setBadgeBackgroundColor({color: [0, 0xff, 0, 0xff]});
browser.browserAction.disable();
expectDefaults(details[3]).then(() => {
expect(details[3]);
});
await expectDefaults(details[3]);
expect(details[3]);
},
expect => {
async expect => {
browser.test.log("Re-enable by default. Expect enabled.");
browser.browserAction.enable();
expectDefaults(details[4]).then(() => {
expect(details[4]);
});
await expectDefaults(details[4]);
expect(details[4]);
},
expect => {
async expect => {
browser.test.log("Switch back to tab 2. Expect former value, unaffected by changes to defaults in previous step.");
browser.tabs.update(tabs[1], {active: true}, () => {
expectDefaults(details[3]).then(() => {
expect(details[2]);
});
});
await browser.tabs.update(tabs[1], {active: true});
await expectDefaults(details[3]);
expect(details[2]);
},
expect => {
async expect => {
browser.test.log("Delete tab, switch back to tab 1. Expect previous results again.");
browser.tabs.remove(tabs[1], () => {
expect(details[4]);
});
await browser.tabs.remove(tabs[1]);
expect(details[4]);
},
expect => {
async expect => {
browser.test.log("Create a new tab. Expect new default properties.");
browser.tabs.create({active: true, url: "about:blank?2"}, tab => {
tabs.push(tab.id);
expect(details[5]);
});
let tab = await browser.tabs.create({active: true, url: "about:blank?2"});
tabs.push(tab.id);
expect(details[5]);
},
expect => {
async expect => {
browser.test.log("Delete tab.");
browser.tabs.remove(tabs[2], () => {
expect(details[4]);
});
await browser.tabs.remove(tabs[2]);
expect(details[4]);
},
];
},
@ -391,39 +367,39 @@ add_task(function* testDefaultTitle() {
];
return [
expect => {
async expect => {
browser.test.log("Initial state. Expect extension title as default title.");
expectDefaults(details[0]).then(() => {
expect(details[0]);
});
await expectDefaults(details[0]);
expect(details[0]);
},
expect => {
async expect => {
browser.test.log("Change the title. Expect new title.");
browser.browserAction.setTitle({tabId: tabs[0], title: "Foo Title"});
expectDefaults(details[0]).then(() => {
expect(details[1]);
});
await expectDefaults(details[0]);
expect(details[1]);
},
expect => {
async expect => {
browser.test.log("Change the default. Expect same properties.");
browser.browserAction.setTitle({title: "Bar Title"});
expectDefaults(details[2]).then(() => {
expect(details[1]);
});
await expectDefaults(details[2]);
expect(details[1]);
},
expect => {
async expect => {
browser.test.log("Clear the title. Expect new default title.");
browser.browserAction.setTitle({tabId: tabs[0], title: ""});
expectDefaults(details[2]).then(() => {
expect(details[2]);
});
await expectDefaults(details[2]);
expect(details[2]);
},
expect => {
async expect => {
browser.test.log("Set default title to null string. Expect null string from API, extension title in UI.");
browser.browserAction.setTitle({title: ""});
expectDefaults(details[3]).then(() => {
expect(details[3]);
});
await expectDefaults(details[3]);
expect(details[3]);
},
];
},

View File

@ -14,7 +14,7 @@ add_task(function* testIncognitoPopup() {
},
},
background() {
background: async function() {
let resolveMessage;
browser.runtime.onMessage.addListener(msg => {
if (resolveMessage && msg.message == "popup-details") {
@ -31,22 +31,19 @@ add_task(function* testIncognitoPopup() {
});
};
let testWindow = window => {
return browser.tabs.query({active: true, windowId: window.id}).then(([tab]) => {
return browser.pageAction.show(tab.id);
}).then(() => {
browser.test.sendMessage("click-pageAction");
let testWindow = async window => {
let [tab] = await browser.tabs.query({active: true, windowId: window.id});
return awaitPopup(window.id);
}).then(msg => {
browser.test.assertEq(window.incognito, msg.incognito, "Correct incognito status in pageAction popup");
await browser.pageAction.show(tab.id);
browser.test.sendMessage("click-pageAction");
browser.test.sendMessage("click-browserAction");
let msg = await awaitPopup(window.id);
browser.test.assertEq(window.incognito, msg.incognito, "Correct incognito status in pageAction popup");
return awaitPopup(window.id);
}).then(msg => {
browser.test.assertEq(window.incognito, msg.incognito, "Correct incognito status in browserAction popup");
});
browser.test.sendMessage("click-browserAction");
msg = await awaitPopup(window.id);
browser.test.assertEq(window.incognito, msg.incognito, "Correct incognito status in browserAction popup");
};
const URL = "http://example.com/incognito";
@ -59,36 +56,40 @@ add_task(function* testIncognitoPopup() {
});
});
browser.windows.getCurrent().then(window => {
return testWindow(window);
}).then(() => {
return browser.windows.create({incognito: true, url: URL});
}).then(window => {
return windowReady.then(() => {
return testWindow(window);
}).then(() => {
return browser.windows.remove(window.id);
});
}).then(() => {
try {
{
let window = await browser.windows.getCurrent();
await testWindow(window);
}
{
let window = await browser.windows.create({incognito: true, url: URL});
await windowReady;
await testWindow(window);
await browser.windows.remove(window.id);
}
browser.test.notifyPass("incognito");
}).catch(error => {
} catch (error) {
browser.test.fail(`Error: ${error} :: ${error.stack}`);
browser.test.notifyFail("incognito");
});
}
},
files: {
"popup.html": '<html><head><meta charset="utf-8"><script src="popup.js"></script></head></html>',
"popup.js": function() {
browser.windows.getCurrent().then(win => {
browser.runtime.sendMessage({
message: "popup-details",
windowId: win.id,
incognito: browser.extension.inIncognitoContext,
});
window.close();
"popup.js": async function() {
let win = await browser.windows.getCurrent();
browser.runtime.sendMessage({
message: "popup-details",
windowId: win.id,
incognito: browser.extension.inIncognitoContext,
});
window.close();
},
},
});

View File

@ -27,17 +27,19 @@ add_task(function* test_legacy_extension_context_contentscript_connection() {
// in a test message.
let uuid = window.location.hostname;
browser.test.onMessage.addListener(msg => {
browser.test.onMessage.addListener(async msg => {
if (msg == "open-test-tab") {
browser.tabs.create({url: "http://example.com/"})
.then(tab => browser.test.sendMessage("get-expected-sender-info", {
uuid, tab,
}));
let tab = await browser.tabs.create({url: "http://example.com/"});
browser.test.sendMessage("get-expected-sender-info",
{uuid, tab});
} else if (msg == "close-current-tab") {
browser.tabs.query({active: true})
.then(tabs => browser.tabs.remove(tabs[0].id))
.then(() => browser.test.sendMessage("current-tab-closed", true))
.catch(() => browser.test.sendMessage("current-tab-closed", false));
try {
let [tab] = await browser.tabs.query({active: true});
await browser.tabs.remove(tab.id);
browser.test.sendMessage("current-tab-closed", true);
} catch (e) {
browser.test.sendMessage("current-tab-closed", false);
}
}
});

View File

@ -17,16 +17,17 @@ add_task(function* test_tab_options_privileges() {
browser.runtime.openOptionsPage();
}
function optionsScript() {
browser.tabs.query({url: "http://example.com/"}).then(tabs => {
browser.test.assertEq("http://example.com/", tabs[0].url, "Got the expect tab");
return browser.tabs.getCurrent();
}).then(tab => {
async function optionsScript() {
try {
let [tab] = await browser.tabs.query({url: "http://example.com/"});
browser.test.assertEq("http://example.com/", tab.url, "Got the expect tab");
tab = await browser.tabs.getCurrent();
browser.runtime.sendMessage({msgName: "removeTabId", tabId: tab.id});
}).catch(error => {
} catch (error) {
browser.test.log(`Error: ${error} :: ${error.stack}`);
browser.test.notifyFail("options-ui-privileges");
});
}
}
const ID = "options_privileges@tests.mozilla.org";

View File

@ -79,52 +79,51 @@ add_task(function* testTabSwitchContext() {
});
});
};
return [
expect => {
browser.test.log("Initial state. No icon visible.");
expect(null);
},
expect => {
async expect => {
browser.test.log("Show the icon on the first tab, expect default properties.");
browser.pageAction.show(tabs[0]).then(() => {
expect(details[0]);
});
await browser.pageAction.show(tabs[0]);
expect(details[0]);
},
expect => {
browser.test.log("Change the icon. Expect default properties excluding the icon.");
browser.pageAction.setIcon({tabId: tabs[0], path: "1.png"});
expect(details[1]);
},
expect => {
async expect => {
browser.test.log("Create a new tab. No icon visible.");
browser.tabs.create({active: true, url: "about:blank?0"}, tab => {
tabs.push(tab.id);
expect(null);
});
let tab = await browser.tabs.create({active: true, url: "about:blank?0"});
tabs.push(tab.id);
expect(null);
},
expect => {
browser.test.log("Await tab load. No icon visible.");
expect(null);
},
expect => {
async expect => {
browser.test.log("Change properties. Expect new properties.");
let tabId = tabs[1];
browser.pageAction.show(tabId).then(() => {
browser.pageAction.setIcon({tabId, path: "2.png"});
browser.pageAction.setPopup({tabId, popup: "2.html"});
browser.pageAction.setTitle({tabId, title: "Title 2"});
await browser.pageAction.show(tabId);
expect(details[2]);
});
browser.pageAction.setIcon({tabId, path: "2.png"});
browser.pageAction.setPopup({tabId, popup: "2.html"});
browser.pageAction.setTitle({tabId, title: "Title 2"});
expect(details[2]);
},
expect => {
async expect => {
browser.test.log("Change the hash. Expect same properties.");
promiseTabLoad({id: tabs[1], url: "about:blank?0#ref"}).then(() => {
expect(details[2]);
});
let promise = promiseTabLoad({id: tabs[1], url: "about:blank?0#ref"});
browser.tabs.update(tabs[1], {url: "about:blank?0#ref"});
await promise;
expect(details[2]);
},
expect => {
browser.test.log("Clear the title. Expect default title.");
@ -132,48 +131,46 @@ add_task(function* testTabSwitchContext() {
expect(details[3]);
},
expect => {
async expect => {
browser.test.log("Navigate to a new page. Expect icon hidden.");
// TODO: This listener should not be necessary, but the |tabs.update|
// callback currently fires too early in e10s windows.
promiseTabLoad({id: tabs[1], url: "about:blank?1"}).then(() => {
expect(null);
});
let promise = promiseTabLoad({id: tabs[1], url: "about:blank?1"});
browser.tabs.update(tabs[1], {url: "about:blank?1"});
await promise;
expect(null);
},
expect => {
async expect => {
browser.test.log("Show the icon. Expect default properties again.");
browser.pageAction.show(tabs[1]).then(() => {
expect(details[0]);
});
await browser.pageAction.show(tabs[1]);
expect(details[0]);
},
expect => {
async expect => {
browser.test.log("Switch back to the first tab. Expect previously set properties.");
browser.tabs.update(tabs[0], {active: true}, () => {
expect(details[1]);
});
await browser.tabs.update(tabs[0], {active: true});
expect(details[1]);
},
expect => {
async expect => {
browser.test.log("Hide the icon on tab 2. Switch back, expect hidden.");
browser.pageAction.hide(tabs[1]).then(() => {
browser.tabs.update(tabs[1], {active: true}, () => {
expect(null);
});
});
await browser.pageAction.hide(tabs[1]);
await browser.tabs.update(tabs[1], {active: true});
expect(null);
},
expect => {
async expect => {
browser.test.log("Switch back to tab 1. Expect previous results again.");
browser.tabs.remove(tabs[1], () => {
expect(details[1]);
});
await browser.tabs.remove(tabs[1]);
expect(details[1]);
},
expect => {
async expect => {
browser.test.log("Hide the icon. Expect hidden.");
browser.pageAction.hide(tabs[0]).then(() => {
expect(null);
});
await browser.pageAction.hide(tabs[0]);
expect(null);
},
];
},

View File

@ -39,7 +39,7 @@ add_task(function* testPageActionPopup() {
"data/background.html": scriptPage("background.js"),
"data/background.js": function() {
"data/background.js": async function() {
let tabId;
let sendClick;
@ -115,7 +115,7 @@ add_task(function* testPageActionPopup() {
browser.test.sendMessage("next-test");
});
browser.test.onMessage.addListener((msg) => {
browser.test.onMessage.addListener(msg => {
if (msg == "close-popup") {
browser.runtime.sendMessage("close-popup");
return;
@ -133,13 +133,11 @@ add_task(function* testPageActionPopup() {
}
});
browser.tabs.query({active: true, currentWindow: true}, tabs => {
tabId = tabs[0].id;
let [tab] = await browser.tabs.query({active: true, currentWindow: true});
tabId = tab.id;
browser.pageAction.show(tabId).then(() => {
browser.test.sendMessage("next-test");
});
});
await browser.pageAction.show(tabId);
browser.test.sendMessage("next-test");
},
},
});

View File

@ -84,47 +84,46 @@ add_task(function* testTabSwitchContext() {
browser.test.log("Initial state. No icon visible.");
expect(null);
},
expect => {
async expect => {
browser.test.log("Show the icon on the first tab, expect default properties.");
browser.pageAction.show(tabs[0]).then(() => {
expect(details[0]);
});
await browser.pageAction.show(tabs[0]);
expect(details[0]);
},
expect => {
browser.test.log("Change the icon. Expect default properties excluding the icon.");
browser.pageAction.setIcon({tabId: tabs[0], path: "1.png"});
expect(details[1]);
},
expect => {
async expect => {
browser.test.log("Create a new tab. No icon visible.");
browser.tabs.create({active: true, url: "about:blank?0"}, tab => {
tabs.push(tab.id);
expect(null);
});
let tab = await browser.tabs.create({active: true, url: "about:blank?0"});
tabs.push(tab.id);
expect(null);
},
expect => {
browser.test.log("Await tab load. No icon visible.");
expect(null);
},
expect => {
async expect => {
browser.test.log("Change properties. Expect new properties.");
let tabId = tabs[1];
browser.pageAction.show(tabId).then(() => {
browser.pageAction.setIcon({tabId, path: "2.png"});
browser.pageAction.setPopup({tabId, popup: "2.html"});
browser.pageAction.setTitle({tabId, title: "Title 2"});
expect(details[2]);
});
await browser.pageAction.show(tabId);
browser.pageAction.setIcon({tabId, path: "2.png"});
browser.pageAction.setPopup({tabId, popup: "2.html"});
browser.pageAction.setTitle({tabId, title: "Title 2"});
expect(details[2]);
},
expect => {
async expect => {
browser.test.log("Change the hash. Expect same properties.");
promiseTabLoad({id: tabs[1], url: "about:blank?0#ref"}).then(() => {
expect(details[2]);
});
let promise = promiseTabLoad({id: tabs[1], url: "about:blank?0#ref"});
browser.tabs.update(tabs[1], {url: "about:blank?0#ref"});
await promise;
expect(details[2]);
},
expect => {
browser.test.log("Clear the title. Expect default title.");
@ -132,48 +131,43 @@ add_task(function* testTabSwitchContext() {
expect(details[3]);
},
expect => {
async expect => {
browser.test.log("Navigate to a new page. Expect icon hidden.");
// TODO: This listener should not be necessary, but the |tabs.update|
// callback currently fires too early in e10s windows.
promiseTabLoad({id: tabs[1], url: "about:blank?1"}).then(() => {
expect(null);
});
let promise = promiseTabLoad({id: tabs[1], url: "about:blank?1"});
browser.tabs.update(tabs[1], {url: "about:blank?1"});
await promise;
expect(null);
},
expect => {
async expect => {
browser.test.log("Show the icon. Expect default properties again.");
browser.pageAction.show(tabs[1]).then(() => {
expect(details[0]);
});
await browser.pageAction.show(tabs[1]);
expect(details[0]);
},
expect => {
async expect => {
browser.test.log("Switch back to the first tab. Expect previously set properties.");
browser.tabs.update(tabs[0], {active: true}, () => {
expect(details[1]);
});
await browser.tabs.update(tabs[0], {active: true});
expect(details[1]);
},
expect => {
async expect => {
browser.test.log("Hide the icon on tab 2. Switch back, expect hidden.");
browser.pageAction.hide(tabs[1]).then(() => {
browser.tabs.update(tabs[1], {active: true}, () => {
expect(null);
});
});
await browser.pageAction.hide(tabs[1]);
await browser.tabs.update(tabs[1], {active: true});
expect(null);
},
expect => {
async expect => {
browser.test.log("Switch back to tab 1. Expect previous results again.");
browser.tabs.remove(tabs[1], () => {
expect(details[1]);
});
await browser.tabs.remove(tabs[1]);
expect(details[1]);
},
expect => {
async expect => {
browser.test.log("Hide the icon. Expect hidden.");
browser.pageAction.hide(tabs[0]).then(() => {
expect(null);
});
await browser.pageAction.hide(tabs[0]);
expect(null);
},
];
},
@ -211,11 +205,10 @@ add_task(function* testDefaultTitle() {
browser.test.log("Initial state. No icon visible.");
expect(null);
},
expect => {
async expect => {
browser.test.log("Show the icon on the first tab, expect extension title as default title.");
browser.pageAction.show(tabs[0]).then(() => {
expect(details[0]);
});
await browser.pageAction.show(tabs[0]);
expect(details[0]);
},
expect => {
browser.test.log("Change the title. Expect new title.");

View File

@ -4,11 +4,10 @@
let getExtension = () => {
return ExtensionTestUtils.loadExtension({
background() {
browser.tabs.query({active: true, currentWindow: true}, tabs => {
browser.pageAction.show(tabs[0].id)
.then(() => { browser.test.sendMessage("pageAction ready"); });
});
background: async function() {
let [tab] = await browser.tabs.query({active: true, currentWindow: true});
await browser.pageAction.show(tab.id);
browser.test.sendMessage("pageAction ready");
},
manifest: {

View File

@ -61,7 +61,7 @@ add_tasks(function* test_inline_options(extraOptions) {
},
},
background: function() {
background: async function() {
let _optionsPromise;
let awaitOptions = () => {
browser.test.assertFalse(_optionsPromise, "Should not be awaiting options already");
@ -82,66 +82,63 @@ add_tasks(function* test_inline_options(extraOptions) {
}
});
let firstTab, optionsTab;
browser.tabs.query({currentWindow: true, active: true}).then(tabs => {
firstTab = tabs[0].id;
try {
let [firstTab] = await browser.tabs.query({currentWindow: true, active: true});
browser.test.log("Open options page. Expect fresh load.");
return Promise.all([
let [, optionsTab] = await Promise.all([
browser.runtime.openOptionsPage(),
awaitOptions(),
]);
}).then(([, tab]) => {
browser.test.assertEq("about:addons", tab.url, "Tab contains AddonManager");
browser.test.assertTrue(tab.active, "Tab is active");
browser.test.assertTrue(tab.id != firstTab, "Tab is a new tab");
optionsTab = tab.id;
browser.test.assertEq("about:addons", optionsTab.url, "Tab contains AddonManager");
browser.test.assertTrue(optionsTab.active, "Tab is active");
browser.test.assertTrue(optionsTab.id != firstTab.id, "Tab is a new tab");
browser.test.assertEq(0, browser.extension.getViews({type: "popup"}).length, "viewType is not popup");
browser.test.assertEq(1, browser.extension.getViews({type: "tab"}).length, "viewType is tab");
browser.test.assertEq(1, browser.extension.getViews({windowId: tab.windowId}).length, "windowId matches");
browser.test.assertEq(1, browser.extension.getViews({windowId: optionsTab.windowId}).length, "windowId matches");
let views = browser.extension.getViews();
browser.test.assertEq(2, views.length, "Expected the options page and the background page");
browser.test.assertTrue(views.includes(window), "One of the views is the background page");
browser.test.assertTrue(views.some(w => w.iAmOption), "One of the views is the options page");
browser.test.log("Switch tabs.");
return browser.tabs.update(firstTab, {active: true});
}).then(() => {
await browser.tabs.update(firstTab.id, {active: true});
browser.test.log("Open options page again. Expect tab re-selected, no new load.");
return browser.runtime.openOptionsPage();
}).then(() => {
return browser.tabs.query({currentWindow: true, active: true});
}).then(([tab]) => {
browser.test.assertEq(optionsTab, tab.id, "Tab is the same as the previous options tab");
await browser.runtime.openOptionsPage();
let [tab] = await browser.tabs.query({currentWindow: true, active: true});
browser.test.assertEq(optionsTab.id, tab.id, "Tab is the same as the previous options tab");
browser.test.assertEq("about:addons", tab.url, "Tab contains AddonManager");
browser.test.log("Ping options page.");
return browser.runtime.sendMessage("ping");
}).then((pong) => {
let pong = await browser.runtime.sendMessage("ping");
browser.test.assertEq("pong", pong, "Got pong.");
browser.test.log("Remove options tab.");
return browser.tabs.remove(optionsTab);
}).then(() => {
await browser.tabs.remove(optionsTab.id);
browser.test.log("Open options page again. Expect fresh load.");
return Promise.all([
[, tab] = await Promise.all([
browser.runtime.openOptionsPage(),
awaitOptions(),
]);
}).then(([, tab]) => {
browser.test.assertEq("about:addons", tab.url, "Tab contains AddonManager");
browser.test.assertTrue(tab.active, "Tab is active");
browser.test.assertTrue(tab.id != optionsTab, "Tab is a new tab");
browser.test.assertTrue(tab.id != optionsTab.id, "Tab is a new tab");
await browser.tabs.remove(tab.id);
return browser.tabs.remove(tab.id);
}).then(() => {
browser.test.notifyPass("options-ui");
}).catch(error => {
browser.test.log(`Error: ${error} :: ${error.stack}`);
} catch (error) {
browser.test.fail(`Error: ${error} :: ${error.stack}`);
browser.test.notifyFail("options-ui");
});
}
},
}));
@ -165,7 +162,7 @@ add_tasks(function* test_tab_options(extraOptions) {
},
},
background: function() {
background: async function() {
let _optionsPromise;
let awaitOptions = () => {
browser.test.assertFalse(_optionsPromise, "Should not be awaiting options already");
@ -188,39 +185,36 @@ add_tasks(function* test_tab_options(extraOptions) {
let optionsURL = browser.extension.getURL("options.html");
let firstTab, optionsTab;
browser.tabs.query({currentWindow: true, active: true}).then(tabs => {
firstTab = tabs[0].id;
try {
let [firstTab] = await browser.tabs.query({currentWindow: true, active: true});
browser.test.log("Open options page. Expect fresh load.");
return Promise.all([
let [, optionsTab] = await Promise.all([
browser.runtime.openOptionsPage(),
awaitOptions(),
]);
}).then(([, tab]) => {
browser.test.assertEq(optionsURL, tab.url, "Tab contains options.html");
browser.test.assertTrue(tab.active, "Tab is active");
browser.test.assertTrue(tab.id != firstTab, "Tab is a new tab");
browser.test.assertEq(optionsURL, optionsTab.url, "Tab contains options.html");
browser.test.assertTrue(optionsTab.active, "Tab is active");
browser.test.assertTrue(optionsTab.id != firstTab.id, "Tab is a new tab");
optionsTab = tab.id;
browser.test.assertEq(0, browser.extension.getViews({type: "popup"}).length, "viewType is not popup");
browser.test.assertEq(1, browser.extension.getViews({type: "tab"}).length, "viewType is tab");
browser.test.assertEq(1, browser.extension.getViews({windowId: tab.windowId}).length, "windowId matches");
browser.test.assertEq(1, browser.extension.getViews({windowId: optionsTab.windowId}).length, "windowId matches");
let views = browser.extension.getViews();
browser.test.assertEq(2, views.length, "Expected the options page and the background page");
browser.test.assertTrue(views.includes(window), "One of the views is the background page");
browser.test.assertTrue(views.some(w => w.iAmOption), "One of the views is the options page");
browser.test.log("Switch tabs.");
return browser.tabs.update(firstTab, {active: true});
}).then(() => {
await browser.tabs.update(firstTab.id, {active: true});
browser.test.log("Open options page again. Expect tab re-selected, no new load.");
return browser.runtime.openOptionsPage();
}).then(() => {
return browser.tabs.query({currentWindow: true, active: true});
}).then(([tab]) => {
browser.test.assertEq(optionsTab, tab.id, "Tab is the same as the previous options tab");
await browser.runtime.openOptionsPage();
let [tab] = await browser.tabs.query({currentWindow: true, active: true});
browser.test.assertEq(optionsTab.id, tab.id, "Tab is the same as the previous options tab");
browser.test.assertEq(optionsURL, tab.url, "Tab contains options.html");
// Unfortunately, we can't currently do this, since onMessage doesn't
@ -230,25 +224,24 @@ add_tasks(function* test_tab_options(extraOptions) {
// return new Promise(resolve => browser.runtime.sendMessage("ping", resolve));
browser.test.log("Remove options tab.");
return browser.tabs.remove(optionsTab);
}).then(() => {
await browser.tabs.remove(optionsTab.id);
browser.test.log("Open options page again. Expect fresh load.");
return Promise.all([
[, tab] = await Promise.all([
browser.runtime.openOptionsPage(),
awaitOptions(),
]);
}).then(([, tab]) => {
browser.test.assertEq(optionsURL, tab.url, "Tab contains options.html");
browser.test.assertTrue(tab.active, "Tab is active");
browser.test.assertTrue(tab.id != optionsTab, "Tab is a new tab");
browser.test.assertTrue(tab.id != optionsTab.id, "Tab is a new tab");
await browser.tabs.remove(tab.id);
return browser.tabs.remove(tab.id);
}).then(() => {
browser.test.notifyPass("options-ui-tab");
}).catch(error => {
browser.test.log(`Error: ${error} :: ${error.stack}`);
} catch (error) {
browser.test.fail(`Error: ${error} :: ${error.stack}`);
browser.test.notifyFail("options-ui-tab");
});
}
},
}));
@ -283,7 +276,7 @@ add_tasks(function* test_options_no_manifest(extraOptions) {
).then(() => {
browser.test.notifyPass("options-no-manifest");
}).catch(error => {
browser.test.log(`Error: ${error} :: ${error.stack}`);
browser.test.fail(`Error: ${error} :: ${error.stack}`);
browser.test.notifyFail("options-no-manifest");
});
},

View File

@ -48,7 +48,7 @@ add_task(function* test_inline_options_uninstall() {
},
},
background: function() {
background: async function() {
let _optionsPromise;
let awaitOptions = () => {
browser.test.assertFalse(_optionsPromise, "Should not be awaiting options already");
@ -69,24 +69,23 @@ add_task(function* test_inline_options_uninstall() {
}
});
let firstTab;
browser.tabs.query({currentWindow: true, active: true}).then(tabs => {
firstTab = tabs[0].id;
try {
let [firstTab] = await browser.tabs.query({currentWindow: true, active: true});
browser.test.log("Open options page. Expect fresh load.");
return Promise.all([
let [, tab] = await Promise.all([
browser.runtime.openOptionsPage(),
awaitOptions(),
]);
}).then(([, tab]) => {
browser.test.assertEq("about:addons", tab.url, "Tab contains AddonManager");
browser.test.assertTrue(tab.active, "Tab is active");
browser.test.assertTrue(tab.id != firstTab, "Tab is a new tab");
browser.test.assertTrue(tab.id != firstTab.id, "Tab is a new tab");
browser.test.sendMessage("options-ui-open");
}).catch(error => {
} catch (error) {
browser.test.fail(`Error: ${error} :: ${error.stack}`);
});
}
},
});

View File

@ -30,7 +30,7 @@ function* makeAndInstallXPI(id, backgroundScript, loadedURL) {
add_task(function* test_setuninstallurl_badargs() {
function backgroundScript() {
async function backgroundScript() {
let promises = [
browser.runtime.setUninstallURL("this is not a url")
.then(() => {
@ -49,8 +49,8 @@ add_task(function* test_setuninstallurl_badargs() {
}),
];
Promise.all(promises)
.then(() => browser.test.notifyPass("setUninstallURL bad params"));
await Promise.all(promises);
browser.test.notifyPass("setUninstallURL bad params");
}
let extension = ExtensionTestUtils.loadExtension({
@ -65,9 +65,9 @@ add_task(function* test_setuninstallurl_badargs() {
// empty string is equivalent to not setting an uninstall URL
// (i.e., no new tab is opened upon uninstall)
add_task(function* test_setuninstall_empty_url() {
function backgroundScript() {
browser.runtime.setUninstallURL("")
.then(() => browser.tabs.create({url: "http://example.com/addon_loaded"}));
async function backgroundScript() {
await browser.runtime.setUninstallURL("");
browser.tabs.create({url: "http://example.com/addon_loaded"});
}
let addon = yield makeAndInstallXPI("test_uinstallurl2@tests.mozilla.org",
@ -82,9 +82,9 @@ add_task(function* test_setuninstall_empty_url() {
});
add_task(function* test_setuninstallurl() {
function backgroundScript() {
browser.runtime.setUninstallURL("http://example.com/addon_uninstalled")
.then(() => browser.tabs.create({url: "http://example.com/addon_loaded"}));
async function backgroundScript() {
await browser.runtime.setUninstallURL("http://example.com/addon_uninstalled");
browser.tabs.create({url: "http://example.com/addon_loaded"});
}
let addon = yield makeAndInstallXPI("test_uinstallurl@tests.mozilla.org",

View File

@ -8,17 +8,7 @@ add_task(function* () {
gBrowser.selectedTab = tab1;
function background() {
// Wrap API methods in promise-based variants.
let promiseTabs = {};
Object.keys(browser.tabs).forEach(method => {
promiseTabs[method] = (...args) => {
return new Promise(resolve => {
browser.tabs[method](...args, resolve);
});
};
});
async function background() {
function promiseUpdated(tabId, attr) {
return new Promise(resolve => {
let onUpdated = (tabId_, changeInfo, tab) => {
@ -47,9 +37,8 @@ add_task(function* () {
}
let windowId;
let tabIds;
promiseTabs.query({lastFocusedWindow: true}).then(tabs => {
try {
let tabs = await browser.tabs.query({lastFocusedWindow: true});
browser.test.assertEq(tabs.length, 3, "We have three tabs");
for (let tab of tabs) {
@ -60,17 +49,15 @@ add_task(function* () {
browser.test.assertEq(false, tab.audible, "Tab is not audible");
}
windowId = tabs[0].windowId;
tabIds = [tabs[1].id, tabs[2].id];
let windowId = tabs[0].windowId;
let tabIds = [tabs[1].id, tabs[2].id];
browser.test.log("Test initial queries for muted and audible return no tabs");
return Promise.all([
promiseTabs.query({windowId, audible: false}),
promiseTabs.query({windowId, audible: true}),
promiseTabs.query({windowId, muted: true}),
promiseTabs.query({windowId, muted: false}),
]);
}).then(([silent, audible, muted, nonMuted]) => {
let silent = await browser.tabs.query({windowId, audible: false});
let audible = await browser.tabs.query({windowId, audible: true});
let muted = await browser.tabs.query({windowId, muted: true});
let nonMuted = await browser.tabs.query({windowId, muted: false});
browser.test.assertEq(3, silent.length, "Three silent tabs");
browser.test.assertEq(0, audible.length, "No audible tabs");
@ -78,13 +65,13 @@ add_task(function* () {
browser.test.assertEq(3, nonMuted.length, "Three non-muted tabs");
browser.test.log("Toggle muted and audible externally on one tab each, and check results");
return Promise.all([
[muted, audible] = await Promise.all([
promiseUpdated(tabIds[0], "mutedInfo"),
promiseUpdated(tabIds[1], "audible"),
changeTab(tabIds[0], "muted", true),
changeTab(tabIds[1], "audible", true),
]);
}).then(([muted, audible]) => {
for (let obj of [muted.changeInfo, muted.tab]) {
browser.test.assertEq(true, obj.mutedInfo.muted, "Tab is muted");
browser.test.assertEq("user", obj.mutedInfo.reason, "Tab was muted by the user");
@ -94,13 +81,11 @@ add_task(function* () {
browser.test.assertEq(true, audible.tab.audible, "Tab is audible");
browser.test.log("Re-check queries. Expect one audible and one muted tab");
return Promise.all([
promiseTabs.query({windowId, audible: false}),
promiseTabs.query({windowId, audible: true}),
promiseTabs.query({windowId, muted: true}),
promiseTabs.query({windowId, muted: false}),
]);
}).then(([silent, audible, muted, nonMuted]) => {
silent = await browser.tabs.query({windowId, audible: false});
audible = await browser.tabs.query({windowId, audible: true});
muted = await browser.tabs.query({windowId, muted: true});
nonMuted = await browser.tabs.query({windowId, muted: false});
browser.test.assertEq(2, silent.length, "Two silent tabs");
browser.test.assertEq(1, audible.length, "One audible tab");
@ -113,21 +98,21 @@ add_task(function* () {
browser.test.assertEq(true, audible[0].audible, "Tab is audible");
browser.test.log("Toggle muted internally on two tabs, and check results");
return Promise.all([
[nonMuted, muted] = await Promise.all([
promiseUpdated(tabIds[0], "mutedInfo"),
promiseUpdated(tabIds[1], "mutedInfo"),
promiseTabs.update(tabIds[0], {muted: false}),
promiseTabs.update(tabIds[1], {muted: true}),
browser.tabs.update(tabIds[0], {muted: false}),
browser.tabs.update(tabIds[1], {muted: true}),
]);
}).then(([unmuted, muted]) => {
for (let obj of [unmuted.changeInfo, unmuted.tab]) {
for (let obj of [nonMuted.changeInfo, nonMuted.tab]) {
browser.test.assertEq(false, obj.mutedInfo.muted, "Tab is not muted");
}
for (let obj of [muted.changeInfo, muted.tab]) {
browser.test.assertEq(true, obj.mutedInfo.muted, "Tab is muted");
}
for (let obj of [unmuted.changeInfo, unmuted.tab, muted.changeInfo, muted.tab]) {
for (let obj of [nonMuted.changeInfo, nonMuted.tab, muted.changeInfo, muted.tab]) {
browser.test.assertEq("extension", obj.mutedInfo.reason, "Mute state changed by extension");
// FIXME: browser.runtime.id is currently broken.
@ -137,8 +122,8 @@ add_task(function* () {
}
browser.test.log("Test that mutedInfo is preserved by sessionstore");
return changeTab(tabIds[1], "duplicate").then(promiseTabs.get);
}).then(tab => {
let tab = await changeTab(tabIds[1], "duplicate").then(browser.tabs.get);
browser.test.assertEq(true, tab.mutedInfo.muted, "Tab is muted");
browser.test.assertEq("extension", tab.mutedInfo.reason, "Mute state changed by extension");
@ -149,22 +134,22 @@ add_task(function* () {
"Mute state changed by extension");
browser.test.log("Unmute externally, and check results");
return Promise.all([
[nonMuted] = await Promise.all([
promiseUpdated(tabIds[1], "mutedInfo"),
changeTab(tabIds[1], "muted", false),
promiseTabs.remove(tab.id),
browser.tabs.remove(tab.id),
]);
}).then(([unmuted]) => {
for (let obj of [unmuted.changeInfo, unmuted.tab]) {
for (let obj of [nonMuted.changeInfo, nonMuted.tab]) {
browser.test.assertEq(false, obj.mutedInfo.muted, "Tab is not muted");
browser.test.assertEq("user", obj.mutedInfo.reason, "Mute state changed by user");
}
browser.test.notifyPass("tab-audio");
}).catch(e => {
} catch (e) {
browser.test.fail(`${e} :: ${e.stack}`);
browser.test.notifyFail("tab-audio");
});
}
}
let extension = ExtensionTestUtils.loadExtension({

View File

@ -26,93 +26,85 @@ function* runTest(options) {
tab.linkedBrowser.fullZoom = options.fullZoom;
function background(options) {
// Wrap API methods in promise-based variants.
let promiseTabs = {};
Object.keys(browser.tabs).forEach(method => {
promiseTabs[method] = (...args) => {
return new Promise(resolve => {
browser.tabs[method](...args, resolve);
});
};
});
async function background(options) {
browser.test.log(`Test color ${options.color} at fullZoom=${options.fullZoom}`);
promiseTabs.query({currentWindow: true, active: true}).then(([tab]) => {
return Promise.all([
promiseTabs.captureVisibleTab(tab.windowId, {format: "jpeg", quality: 95}),
promiseTabs.captureVisibleTab(tab.windowId, {format: "png", quality: 95}),
promiseTabs.captureVisibleTab(tab.windowId, {quality: 95}),
promiseTabs.captureVisibleTab(tab.windowId),
]).then(([jpeg, png, ...pngs]) => {
browser.test.assertTrue(pngs.every(url => url == png), "All PNGs are identical");
try {
let [tab] = await browser.tabs.query({currentWindow: true, active: true});
browser.test.assertTrue(jpeg.startsWith("data:image/jpeg;base64,"), "jpeg is JPEG");
browser.test.assertTrue(png.startsWith("data:image/png;base64,"), "png is PNG");
let [jpeg, png, ...pngs] = await Promise.all([
browser.tabs.captureVisibleTab(tab.windowId, {format: "jpeg", quality: 95}),
browser.tabs.captureVisibleTab(tab.windowId, {format: "png", quality: 95}),
browser.tabs.captureVisibleTab(tab.windowId, {quality: 95}),
browser.tabs.captureVisibleTab(tab.windowId),
]);
let promises = [jpeg, png].map(url => new Promise(resolve => {
let img = new Image();
img.src = url;
img.onload = () => resolve(img);
}));
return Promise.all(promises);
}).then(([jpeg, png]) => {
let tabDims = `${tab.width}\u00d7${tab.height}`;
browser.test.assertTrue(pngs.every(url => url == png), "All PNGs are identical");
let images = {jpeg, png};
for (let format of Object.keys(images)) {
let img = images[format];
browser.test.assertTrue(jpeg.startsWith("data:image/jpeg;base64,"), "jpeg is JPEG");
browser.test.assertTrue(png.startsWith("data:image/png;base64,"), "png is PNG");
let dims = `${img.width}\u00d7${img.height}`;
browser.test.assertEq(tabDims, dims, `${format} dimensions are correct`);
let promises = [jpeg, png].map(url => new Promise(resolve => {
let img = new Image();
img.src = url;
img.onload = () => resolve(img);
}));
let canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
canvas.mozOpaque = true;
[jpeg, png] = await Promise.all(promises);
let tabDims = `${tab.width}\u00d7${tab.height}`;
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
let images = {jpeg, png};
for (let format of Object.keys(images)) {
let img = images[format];
// Check the colors of the first and last pixels of the image, to make
// sure we capture the entire frame, and scale it correctly.
let coords = [
{x: 0, y: 0,
color: options.color},
{x: img.width - 1,
y: img.height - 1,
color: options.color},
{x: img.width / 2 | 0,
y: img.height / 2 | 0,
color: options.neutral},
];
let dims = `${img.width}\u00d7${img.height}`;
browser.test.assertEq(tabDims, dims, `${format} dimensions are correct`);
for (let {x, y, color} of coords) {
let imageData = ctx.getImageData(x, y, 1, 1).data;
let canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
canvas.mozOpaque = true;
if (format == "png") {
browser.test.assertEq(`rgba(${color},255)`, `rgba(${[...imageData]})`, `${format} image color is correct at (${x}, ${y})`);
} else {
// Allow for some deviation in JPEG version due to lossy compression.
const SLOP = 3;
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
browser.test.log(`Testing ${format} image color at (${x}, ${y}), have rgba(${[...imageData]}), expecting approx. rgba(${color},255)`);
// Check the colors of the first and last pixels of the image, to make
// sure we capture the entire frame, and scale it correctly.
let coords = [
{x: 0, y: 0,
color: options.color},
{x: img.width - 1,
y: img.height - 1,
color: options.color},
{x: img.width / 2 | 0,
y: img.height / 2 | 0,
color: options.neutral},
];
browser.test.assertTrue(Math.abs(color[0] - imageData[0]) <= SLOP, `${format} image color.red is correct at (${x}, ${y})`);
browser.test.assertTrue(Math.abs(color[1] - imageData[1]) <= SLOP, `${format} image color.green is correct at (${x}, ${y})`);
browser.test.assertTrue(Math.abs(color[2] - imageData[2]) <= SLOP, `${format} image color.blue is correct at (${x}, ${y})`);
browser.test.assertEq(255, imageData[3], `${format} image color.alpha is correct at (${x}, ${y})`);
}
for (let {x, y, color} of coords) {
let imageData = ctx.getImageData(x, y, 1, 1).data;
if (format == "png") {
browser.test.assertEq(`rgba(${color},255)`, `rgba(${[...imageData]})`, `${format} image color is correct at (${x}, ${y})`);
} else {
// Allow for some deviation in JPEG version due to lossy compression.
const SLOP = 3;
browser.test.log(`Testing ${format} image color at (${x}, ${y}), have rgba(${[...imageData]}), expecting approx. rgba(${color},255)`);
browser.test.assertTrue(Math.abs(color[0] - imageData[0]) <= SLOP, `${format} image color.red is correct at (${x}, ${y})`);
browser.test.assertTrue(Math.abs(color[1] - imageData[1]) <= SLOP, `${format} image color.green is correct at (${x}, ${y})`);
browser.test.assertTrue(Math.abs(color[2] - imageData[2]) <= SLOP, `${format} image color.blue is correct at (${x}, ${y})`);
browser.test.assertEq(255, imageData[3], `${format} image color.alpha is correct at (${x}, ${y})`);
}
}
}
browser.test.notifyPass("captureVisibleTab");
});
}).catch(e => {
browser.test.notifyPass("captureVisibleTab");
} catch (e) {
browser.test.fail(`Error: ${e} :: ${e.stack}`);
browser.test.notifyFail("captureVisibleTab");
});
}
}
let extension = ExtensionTestUtils.loadExtension({

View File

@ -42,97 +42,79 @@ add_task(function* () {
browser.test.assertEq(data.expectedCookieStoreId, tab.cookieStoreId, "tab should have the correct cookieStoreId");
}
function runTest(data) {
// Tab Creation
browser.tabs.create({windowId: data.privateTab ? this.privateWindowId : this.defaultWindowId,
cookieStoreId: data.cookieStoreId})
async function runTest(data) {
try {
// Tab Creation
let tab = await browser.tabs.create({
windowId: data.privateTab ? this.privateWindowId : this.defaultWindowId,
cookieStoreId: data.cookieStoreId,
}).then((tab) => {
// Tests for tab creation
testTab(data, tab);
return tab;
}, (error) => {
browser.test.assertTrue(!!data.failure, "we want a failure");
if (data.failure == "illegal") {
browser.test.assertTrue(/Illegal cookieStoreId/.test(error.message),
"runtime.lastError should report the expected error message");
} else if (data.failure == "defaultToPrivate") {
browser.test.assertTrue("Illegal to set private cookieStorageId in a non private window",
error.message,
"runtime.lastError should report the expected error message");
} else if (data.failure == "privateToDefault") {
browser.test.assertTrue("Illegal to set non private cookieStorageId in a private window",
error.message,
"runtime.lastError should report the expected error message");
} else if (data.failure == "exist") {
browser.test.assertTrue(/No cookie store exists/.test(error.message),
"runtime.lastError should report the expected error message");
} else {
browser.test.fail("The test is broken");
}
// Tests for tab creation
.then((tab) => {
testTab(data, tab);
return tab;
}, (error) => {
browser.test.assertTrue(!!data.failure, "we want a failure");
if (data.failure == "illegal") {
browser.test.assertTrue(/Illegal cookieStoreId/.test(error.message),
"runtime.lastError should report the expected error message");
} else if (data.failure == "defaultToPrivate") {
browser.test.assertTrue("Illegal to set private cookieStorageId in a non private window",
error.message,
"runtime.lastError should report the expected error message");
} else if (data.failure == "privateToDefault") {
browser.test.assertTrue("Illegal to set non private cookieStorageId in a private window",
error.message,
"runtime.lastError should report the expected error message");
} else if (data.failure == "exist") {
browser.test.assertTrue(/No cookie store exists/.test(error.message),
"runtime.lastError should report the expected error message");
} else {
browser.test.fail("The test is broken");
}
return null;
});
return null;
})
// Tests for tab querying
.then((tab) => {
if (tab) {
return browser.tabs.query({windowId: data.privateTab ? this.privateWindowId : this.defaultWindowId,
cookieStoreId: data.cookieStoreId})
.then((tabs) => {
browser.test.assertTrue(tabs.length >= 1, "Tab found!");
testTab(data, tabs[0]);
return tab;
});
}
})
{
// Tests for tab querying
let [tab] = await browser.tabs.query({
windowId: data.privateTab ? this.privateWindowId : this.defaultWindowId,
cookieStoreId: data.cookieStoreId,
});
.then((tab) => {
if (tab) {
return browser.cookies.getAllCookieStores()
.then(stores => {
let store = stores.find(store => store.id === tab.cookieStoreId);
browser.test.assertTrue(!!store, "We have a store for this tab.");
return tab;
});
}
})
browser.test.assertTrue(tab != undefined, "Tab found!");
testTab(data, tab);
}
.then((tab) => {
if (tab) {
return browser.tabs.remove(tab.id);
}
})
let stores = await browser.cookies.getAllCookieStores();
let store = stores.find(store => store.id === tab.cookieStoreId);
browser.test.assertTrue(!!store, "We have a store for this tab.");
await browser.tabs.remove(tab.id);
}
.then(() => {
browser.test.sendMessage("test-done");
}, () => {
browser.test.fail("An exception has ben thrown");
});
} catch (e) {
browser.test.fail("An exception has been thrown");
}
}
function initialize() {
browser.windows.create({incognito: true})
.then((win) => {
this.privateWindowId = win.id;
return browser.windows.create({incognito: false});
})
.then((win) => {
this.defaultWindowId = win.id;
})
.then(() => {
browser.test.sendMessage("ready");
});
async function initialize() {
let win = await browser.windows.create({incognito: true});
this.privateWindowId = win.id;
win = await browser.windows.create({incognito: false});
this.defaultWindowId = win.id;
browser.test.sendMessage("ready");
}
function shutdown() {
browser.windows.remove(this.privateWindowId)
.then(() => {
browser.windows.remove(this.defaultWindowId);
})
.then(() => {
browser.test.sendMessage("gone");
});
async function shutdown() {
await browser.windows.remove(this.privateWindowId);
await browser.windows.remove(this.defaultWindowId);
browser.test.sendMessage("gone");
}
// Waiting for messages

View File

@ -90,7 +90,7 @@ add_task(function* () {
},
];
function nextTest() {
async function nextTest() {
if (!tests.length) {
browser.test.notifyPass("tabs.create");
return;
@ -119,33 +119,29 @@ add_task(function* () {
browser.tabs.onCreated.addListener(onCreated);
});
let tabId;
Promise.all([
let [tab] = await Promise.all([
browser.tabs.create(test.create),
createdPromise,
]).then(([tab]) => {
tabId = tab.id;
]);
let tabId = tab.id;
for (let key of Object.keys(expected)) {
if (key === "url") {
// FIXME: This doesn't get updated until later in the load cycle.
continue;
}
browser.test.assertEq(expected[key], tab[key], `Expected value for tab.${key}`);
for (let key of Object.keys(expected)) {
if (key === "url") {
// FIXME: This doesn't get updated until later in the load cycle.
continue;
}
return updatedPromise;
}).then(updated => {
browser.test.assertEq(tabId, updated.tabId, `Expected value for tab.id`);
browser.test.assertEq(expected.url, updated.url, `Expected value for tab.url`);
browser.test.assertEq(expected[key], tab[key], `Expected value for tab.${key}`);
}
return browser.tabs.remove(tabId);
}).then(() => {
return browser.tabs.update(activeTab, {active: true});
}).then(() => {
nextTest();
});
let updated = await updatedPromise;
browser.test.assertEq(tabId, updated.tabId, `Expected value for tab.id`);
browser.test.assertEq(expected.url, updated.url, `Expected value for tab.url`);
await browser.tabs.remove(tabId);
await browser.tabs.update(activeTab, {active: true});
nextTest();
}
nextTest();

View File

@ -8,38 +8,34 @@ add_task(function* testDetectLanguage() {
"permissions": ["tabs"],
},
background() {
background: async function() {
const BASE_PATH = "browser/browser/components/extensions/test/browser";
function loadTab(url) {
return browser.tabs.create({url});
}
loadTab(`http://example.co.jp/${BASE_PATH}/file_language_ja.html`).then(tab => {
return browser.tabs.detectLanguage(tab.id).then(lang => {
browser.test.assertEq("ja", lang, "Japanese document should be detected as Japanese");
return browser.tabs.remove(tab.id);
});
}).then(() => {
return loadTab(`http://example.co.jp/${BASE_PATH}/file_language_fr_en.html`);
}).then(tab => {
return browser.tabs.detectLanguage(tab.id).then(lang => {
browser.test.assertEq("fr", lang, "French/English document should be detected as primarily French");
return browser.tabs.remove(tab.id);
});
}).then(() => {
return loadTab(`http://example.co.jp/${BASE_PATH}/file_language_tlh.html`);
}).then(tab => {
return browser.tabs.detectLanguage(tab.id).then(lang => {
browser.test.assertEq("und", lang, "Klingon document should not be detected, should return 'und'");
return browser.tabs.remove(tab.id);
});
}).then(() => {
try {
let tab = await loadTab(`http://example.co.jp/${BASE_PATH}/file_language_ja.html`);
let lang = await browser.tabs.detectLanguage(tab.id);
browser.test.assertEq("ja", lang, "Japanese document should be detected as Japanese");
await browser.tabs.remove(tab.id);
tab = await loadTab(`http://example.co.jp/${BASE_PATH}/file_language_fr_en.html`);
lang = await browser.tabs.detectLanguage(tab.id);
browser.test.assertEq("fr", lang, "French/English document should be detected as primarily French");
await browser.tabs.remove(tab.id);
tab = await loadTab(`http://example.co.jp/${BASE_PATH}/file_language_tlh.html`);
lang = await browser.tabs.detectLanguage(tab.id);
browser.test.assertEq("und", lang, "Klingon document should not be detected, should return 'und'");
await browser.tabs.remove(tab.id);
browser.test.notifyPass("detectLanguage");
}).catch(e => {
} catch (e) {
browser.test.fail(`Error: ${e} :: ${e.stack}`);
browser.test.notifyFail("detectLanguage");
});
}
},
});

View File

@ -41,7 +41,7 @@ add_task(function* testDuplicateTab() {
});
add_task(function* testDuplicateTabLazily() {
function background() {
async function background() {
let tabLoadComplete = new Promise(resolve => {
browser.test.onMessage.addListener((message, tabId, result) => {
if (message == "duplicate-tab-done") {
@ -61,32 +61,28 @@ add_task(function* testDuplicateTabLazily() {
});
}
let startTabId;
let url = "http://example.com/browser/browser/components/extensions/test/browser/file_dummy.html";
browser.tabs.create({url}, tab => {
startTabId = tab.id;
try {
let url = "http://example.com/browser/browser/components/extensions/test/browser/file_dummy.html";
let tab = await browser.tabs.create({url});
let startTabId = tab.id;
awaitLoad(startTabId).then(() => {
browser.test.sendMessage("duplicate-tab", startTabId);
await awaitLoad(startTabId);
browser.test.sendMessage("duplicate-tab", startTabId);
tabLoadComplete.then(unloadedTabId => {
browser.tabs.get(startTabId, loadedtab => {
browser.test.assertEq("Dummy test page", loadedtab.title, "Title should be returned for loaded pages");
browser.test.assertEq("complete", loadedtab.status, "Tab status should be complete for loaded pages");
});
let unloadedTabId = await tabLoadComplete;
let loadedtab = await browser.tabs.get(startTabId);
browser.test.assertEq("Dummy test page", loadedtab.title, "Title should be returned for loaded pages");
browser.test.assertEq("complete", loadedtab.status, "Tab status should be complete for loaded pages");
browser.tabs.get(unloadedTabId, unloadedtab => {
browser.test.assertEq("Dummy test page", unloadedtab.title, "Title should be returned after page has been unloaded");
});
let unloadedtab = await browser.tabs.get(unloadedTabId);
browser.test.assertEq("Dummy test page", unloadedtab.title, "Title should be returned after page has been unloaded");
browser.tabs.remove([tab.id, unloadedTabId]);
browser.test.notifyPass("tabs.hasCorrectTabTitle");
});
}).catch(e => {
browser.test.fail(`${e} :: ${e.stack}`);
browser.test.notifyFail("tabs.hasCorrectTabTitle");
});
});
await browser.tabs.remove([tab.id, unloadedTabId]);
browser.test.notifyPass("tabs.hasCorrectTabTitle");
} catch (e) {
browser.test.fail(`${e} :: ${e.stack}`);
browser.test.notifyFail("tabs.hasCorrectTabTitle");
}
}
let extension = ExtensionTestUtils.loadExtension({

View File

@ -3,7 +3,7 @@
"use strict";
add_task(function* testTabEvents() {
function background() {
async function background() {
let events = [];
browser.tabs.onCreated.addListener(tab => {
events.push({type: "onCreated", tab});
@ -25,126 +25,121 @@ add_task(function* testTabEvents() {
events.push(Object.assign({type: "onMoved", tabId}, info));
});
function expectEvents(names) {
async function expectEvents(names) {
browser.test.log(`Expecting events: ${names.join(", ")}`);
return new Promise(resolve => {
setTimeout(resolve, 0);
}).then(() => {
browser.test.assertEq(names.length, events.length, "Got expected number of events");
for (let [i, name] of names.entries()) {
browser.test.assertEq(name, i in events && events[i].type,
`Got expected ${name} event`);
}
return events.splice(0);
});
await new Promise(resolve => setTimeout(resolve, 0));
browser.test.assertEq(names.length, events.length, "Got expected number of events");
for (let [i, name] of names.entries()) {
browser.test.assertEq(name, i in events && events[i].type,
`Got expected ${name} event`);
}
return events.splice(0);
}
browser.test.log("Create second browser window");
let windowId;
Promise.all([
browser.windows.getCurrent(),
browser.windows.create({url: "about:blank"}),
]).then(windows => {
windowId = windows[0].id;
try {
browser.test.log("Create second browser window");
let windows = await Promise.all([
browser.windows.getCurrent(),
browser.windows.create({url: "about:blank"}),
]);
let windowId = windows[0].id;
let otherWindowId = windows[1].id;
let initialTab;
return expectEvents(["onCreated"]).then(([created]) => {
initialTab = created.tab;
let [created] = await expectEvents(["onCreated"]);
let initialTab = created.tab;
browser.test.log("Create tab in window 1");
return browser.tabs.create({windowId, index: 0, url: "about:blank"});
}).then(tab => {
let oldIndex = tab.index;
browser.test.assertEq(0, oldIndex, "Tab has the expected index");
return expectEvents(["onCreated"]).then(([created]) => {
browser.test.assertEq(tab.id, created.tab.id, "Got expected tab ID");
browser.test.assertEq(oldIndex, created.tab.index, "Got expected tab index");
browser.test.log("Create tab in window 1");
let tab = await browser.tabs.create({windowId, index: 0, url: "about:blank"});
let oldIndex = tab.index;
browser.test.assertEq(0, oldIndex, "Tab has the expected index");
browser.test.log("Move tab to window 2");
return browser.tabs.move([tab.id], {windowId: otherWindowId, index: 0});
}).then(() => {
return expectEvents(["onDetached", "onAttached"]);
}).then(([detached, attached]) => {
browser.test.assertEq(oldIndex, detached.oldPosition, "Expected old index");
browser.test.assertEq(windowId, detached.oldWindowId, "Expected old window ID");
[created] = await expectEvents(["onCreated"]);
browser.test.assertEq(tab.id, created.tab.id, "Got expected tab ID");
browser.test.assertEq(oldIndex, created.tab.index, "Got expected tab index");
browser.test.assertEq(0, attached.newPosition, "Expected new index");
browser.test.assertEq(otherWindowId, attached.newWindowId, "Expected new window ID");
browser.test.log("Move tab within the same window");
return browser.tabs.move([tab.id], {index: 1});
}).then(([moved]) => {
browser.test.assertEq(1, moved.index, "Expected new index");
browser.test.log("Move tab to window 2");
await browser.tabs.move([tab.id], {windowId: otherWindowId, index: 0});
return expectEvents(["onMoved"]);
}).then(([moved]) => {
browser.test.assertEq(tab.id, moved.tabId, "Expected tab ID");
browser.test.assertEq(0, moved.fromIndex, "Expected old index");
browser.test.assertEq(1, moved.toIndex, "Expected new index");
browser.test.assertEq(otherWindowId, moved.windowId, "Expected window ID");
let [detached, attached] = await expectEvents(["onDetached", "onAttached"]);
browser.test.assertEq(oldIndex, detached.oldPosition, "Expected old index");
browser.test.assertEq(windowId, detached.oldWindowId, "Expected old window ID");
browser.test.assertEq(0, attached.newPosition, "Expected new index");
browser.test.assertEq(otherWindowId, attached.newWindowId, "Expected new window ID");
browser.test.log("Move tab within the same window");
let [moved] = await browser.tabs.move([tab.id], {index: 1});
browser.test.assertEq(1, moved.index, "Expected new index");
[moved] = await expectEvents(["onMoved"]);
browser.test.assertEq(tab.id, moved.tabId, "Expected tab ID");
browser.test.assertEq(0, moved.fromIndex, "Expected old index");
browser.test.assertEq(1, moved.toIndex, "Expected new index");
browser.test.assertEq(otherWindowId, moved.windowId, "Expected window ID");
browser.test.log("Remove tab");
await browser.tabs.remove(tab.id);
let [removed] = await expectEvents(["onRemoved"]);
browser.test.assertEq(tab.id, removed.tabId, "Expected removed tab ID");
browser.test.assertEq(otherWindowId, removed.windowId, "Expected removed tab window ID");
// Note: We want to test for the actual boolean value false here.
browser.test.assertEq(false, removed.isWindowClosing, "Expected isWindowClosing value");
browser.test.log("Close second window");
await browser.windows.remove(otherWindowId);
[removed] = await expectEvents(["onRemoved"]);
browser.test.assertEq(initialTab.id, removed.tabId, "Expected removed tab ID");
browser.test.assertEq(otherWindowId, removed.windowId, "Expected removed tab window ID");
browser.test.assertEq(true, removed.isWindowClosing, "Expected isWindowClosing value");
browser.test.log("Remove tab");
return browser.tabs.remove(tab.id);
}).then(() => {
return expectEvents(["onRemoved"]);
}).then(([removed]) => {
browser.test.assertEq(tab.id, removed.tabId, "Expected removed tab ID");
browser.test.assertEq(otherWindowId, removed.windowId, "Expected removed tab window ID");
// Note: We want to test for the actual boolean value false here.
browser.test.assertEq(false, removed.isWindowClosing, "Expected isWindowClosing value");
browser.test.log("Close second window");
return browser.windows.remove(otherWindowId);
}).then(() => {
return expectEvents(["onRemoved"]);
}).then(([removed]) => {
browser.test.assertEq(initialTab.id, removed.tabId, "Expected removed tab ID");
browser.test.assertEq(otherWindowId, removed.windowId, "Expected removed tab window ID");
browser.test.assertEq(true, removed.isWindowClosing, "Expected isWindowClosing value");
});
});
}).then(() => {
browser.test.log("Create additional tab in window 1");
return browser.tabs.create({windowId, url: "about:blank"});
}).then(tab => {
return expectEvents(["onCreated"]).then(() => {
browser.test.log("Create a new window, adopting the new tab");
tab = await browser.tabs.create({windowId, url: "about:blank"});
await expectEvents(["onCreated"]);
// We have to explicitly wait for the event here, since its timing is
// not predictable.
let promiseAttached = new Promise(resolve => {
browser.tabs.onAttached.addListener(function listener(tabId) {
browser.tabs.onAttached.removeListener(listener);
resolve();
});
});
return Promise.all([
browser.windows.create({tabId: tab.id}),
promiseAttached,
]);
}).then(([window]) => {
return expectEvents(["onDetached", "onAttached"]).then(([detached, attached]) => {
browser.test.assertEq(tab.id, detached.tabId, "Expected onDetached tab ID");
browser.test.assertEq(tab.id, attached.tabId, "Expected onAttached tab ID");
browser.test.assertEq(0, attached.newPosition, "Expected onAttached new index");
browser.test.assertEq(window.id, attached.newWindowId,
"Expected onAttached new window id");
browser.test.log("Close the new window");
return browser.windows.remove(window.id);
browser.test.log("Create a new window, adopting the new tab");
// We have to explicitly wait for the event here, since its timing is
// not predictable.
let promiseAttached = new Promise(resolve => {
browser.tabs.onAttached.addListener(function listener(tabId) {
browser.tabs.onAttached.removeListener(listener);
resolve();
});
});
}).then(() => {
let [window] = await Promise.all([
browser.windows.create({tabId: tab.id}),
promiseAttached,
]);
[detached, attached] = await expectEvents(["onDetached", "onAttached"]);
browser.test.assertEq(tab.id, detached.tabId, "Expected onDetached tab ID");
browser.test.assertEq(tab.id, attached.tabId, "Expected onAttached tab ID");
browser.test.assertEq(0, attached.newPosition, "Expected onAttached new index");
browser.test.assertEq(window.id, attached.newWindowId,
"Expected onAttached new window id");
browser.test.log("Close the new window");
await browser.windows.remove(window.id);
browser.test.notifyPass("tabs-events");
}).catch(e => {
} catch (e) {
browser.test.fail(`${e} :: ${e.stack}`);
browser.test.notifyFail("tabs-events");
});
}
}
let extension = ExtensionTestUtils.loadExtension({
@ -176,16 +171,14 @@ add_task(function* testTabEventsSize() {
}
});
browser.test.onMessage.addListener((msg, arg) => {
browser.test.onMessage.addListener(async (msg, arg) => {
if (msg === "create-tab") {
browser.tabs.create({url: "http://example.com/"}).then(tab => {
sendSizeMessages(tab, "create");
browser.test.sendMessage("created-tab-id", tab.id);
});
let tab = await browser.tabs.create({url: "http://example.com/"});
sendSizeMessages(tab, "create");
browser.test.sendMessage("created-tab-id", tab.id);
} else if (msg === "update-tab") {
browser.tabs.update(arg, {url: "http://example.org/"}).then(tab => {
sendSizeMessages(tab, "update");
});
let tab = await browser.tabs.update(arg, {url: "http://example.org/"});
sendSizeMessages(tab, "update");
} else if (msg === "remove-tab") {
browser.tabs.remove(arg);
browser.test.sendMessage("tab-removed");
@ -238,9 +231,7 @@ add_task(function* testTabEventsSize() {
});
add_task(function* testTabRemovalEvent() {
function background() {
let removalTabId;
async function background() {
function awaitLoad(tabId) {
return new Promise(resolve => {
browser.tabs.onUpdated.addListener(function listener(tabId_, changed, tab) {
@ -262,17 +253,16 @@ add_task(function* testTabRemovalEvent() {
});
});
let url = "http://example.com/browser/browser/components/extensions/test/browser/context.html";
browser.tabs.create({url: url})
.then(tab => {
removalTabId = tab.id;
return awaitLoad(tab.id);
}).then(() => {
return browser.tabs.remove(removalTabId);
}).catch(e => {
try {
let url = "http://example.com/browser/browser/components/extensions/test/browser/context.html";
let tab = await browser.tabs.create({url: url});
await awaitLoad(tab.id);
await browser.tabs.remove(tab.id);
} catch (e) {
browser.test.fail(`${e} :: ${e.stack}`);
browser.test.notifyFail("tabs-events");
});
}
}
let extension = ExtensionTestUtils.loadExtension({

View File

@ -36,12 +36,13 @@ add_task(function* testExecuteScript() {
const URL = BASE + "file_iframe_document.html";
let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, URL, true);
function background() {
browser.tabs.query({active: true, currentWindow: true}).then(tabs => {
return browser.webNavigation.getAllFrames({tabId: tabs[0].id});
}).then(frames => {
async function background() {
try {
let [tab] = await browser.tabs.query({active: true, currentWindow: true});
let frames = await browser.webNavigation.getAllFrames({tabId: tab.id});
browser.test.log(`FRAMES: ${frames[1].frameId} ${JSON.stringify(frames)}\n`);
return Promise.all([
await Promise.all([
browser.tabs.executeScript({
code: "42",
}).then(result => {
@ -127,8 +128,8 @@ add_task(function* testExecuteScript() {
error.message, "Got expected error");
}),
browser.tabs.create({url: "http://example.net/", active: false}).then(tab => {
return browser.tabs.executeScript(tab.id, {
browser.tabs.create({url: "http://example.net/", active: false}).then(async tab => {
await browser.tabs.executeScript(tab.id, {
code: "42",
}).then(result => {
browser.test.fail("Expected error when trying to execute on invalid domain");
@ -138,9 +139,9 @@ add_task(function* testExecuteScript() {
};
browser.test.assertEq(`No window matching ${JSON.stringify(details)}`,
error.message, "Got expected error");
}).then(() => {
return browser.tabs.remove(tab.id);
});
await browser.tabs.remove(tab.id);
}),
browser.tabs.executeScript({
@ -178,12 +179,12 @@ add_task(function* testExecuteScript() {
browser.test.assertEq("http://mochi.test:8888/", result[0], "Result for frameId[1] is correct");
}),
browser.tabs.create({url: "http://example.com/"}).then(tab => {
return browser.tabs.executeScript(tab.id, {code: "location.href"}).then(result => {
browser.test.assertEq("http://example.com/", result[0], "Script executed correctly in new tab");
browser.tabs.create({url: "http://example.com/"}).then(async tab => {
let result = await browser.tabs.executeScript(tab.id, {code: "location.href"});
return browser.tabs.remove(tab.id);
});
browser.test.assertEq("http://example.com/", result[0], "Script executed correctly in new tab");
await browser.tabs.remove(tab.id);
}),
new Promise(resolve => {
@ -193,12 +194,12 @@ add_task(function* testExecuteScript() {
});
}),
]);
}).then(() => {
browser.test.notifyPass("executeScript");
}).catch(e => {
} catch (e) {
browser.test.fail(`Error: ${e} :: ${e.stack}`);
browser.test.notifyFail("executeScript");
});
}
}
let extension = ExtensionTestUtils.loadExtension({

View File

@ -5,7 +5,7 @@
function* testHasNoPermission(params) {
let contentSetup = params.contentSetup || (() => Promise.resolve());
function background(contentSetup) {
async function background(contentSetup) {
browser.runtime.onMessage.addListener((msg, sender) => {
browser.test.assertEq(msg, "second script ran", "second script ran");
browser.test.notifyPass("executeScript");
@ -30,9 +30,9 @@ function* testHasNoPermission(params) {
});
});
contentSetup().then(() => {
browser.test.sendMessage("ready");
});
await contentSetup();
browser.test.sendMessage("ready");
}
let extension = ExtensionTestUtils.loadExtension({
@ -132,14 +132,9 @@ add_task(function* testBadPermissions() {
"permissions": ["http://example.com/", "activeTab"],
"page_action": {},
},
contentSetup() {
return new Promise(resolve => {
browser.tabs.query({active: true, currentWindow: true}, tabs => {
browser.pageAction.show(tabs[0].id).then(() => {
resolve();
});
});
});
async contentSetup() {
let [tab] = await browser.tabs.query({active: true, currentWindow: true});
await browser.pageAction.show(tab.id);
},
});
@ -148,57 +143,55 @@ add_task(function* testBadPermissions() {
});
add_task(function* testBadURL() {
function background() {
browser.tabs.query({currentWindow: true}, tabs => {
let promises = [
new Promise(resolve => {
browser.tabs.executeScript({
file: "http://example.com/script.js",
}, result => {
browser.test.assertEq(undefined, result, "Result value");
browser.test.assertTrue(browser.extension.lastError instanceof Error,
"runtime.lastError is Error");
browser.test.assertTrue(browser.runtime.lastError instanceof Error,
"runtime.lastError is Error");
browser.test.assertEq(
"Files to be injected must be within the extension",
browser.extension.lastError && browser.extension.lastError.message,
"extension.lastError value");
browser.test.assertEq(
"Files to be injected must be within the extension",
browser.runtime.lastError && browser.runtime.lastError.message,
"runtime.lastError value");
resolve();
});
}),
async function background() {
let promises = [
new Promise(resolve => {
browser.tabs.executeScript({
file: "http://example.com/script.js",
}).catch(error => {
browser.test.assertTrue(error instanceof Error, "Error is Error");
}, result => {
browser.test.assertEq(undefined, result, "Result value");
browser.test.assertEq(null, browser.extension.lastError,
"extension.lastError value");
browser.test.assertTrue(browser.extension.lastError instanceof Error,
"runtime.lastError is Error");
browser.test.assertEq(null, browser.runtime.lastError,
"runtime.lastError value");
browser.test.assertTrue(browser.runtime.lastError instanceof Error,
"runtime.lastError is Error");
browser.test.assertEq(
"Files to be injected must be within the extension",
error && error.message,
"error value");
}),
];
browser.extension.lastError && browser.extension.lastError.message,
"extension.lastError value");
Promise.all(promises).then(() => {
browser.test.notifyPass("executeScript-lastError");
});
});
browser.test.assertEq(
"Files to be injected must be within the extension",
browser.runtime.lastError && browser.runtime.lastError.message,
"runtime.lastError value");
resolve();
});
}),
browser.tabs.executeScript({
file: "http://example.com/script.js",
}).catch(error => {
browser.test.assertTrue(error instanceof Error, "Error is Error");
browser.test.assertEq(null, browser.extension.lastError,
"extension.lastError value");
browser.test.assertEq(null, browser.runtime.lastError,
"runtime.lastError value");
browser.test.assertEq(
"Files to be injected must be within the extension",
error && error.message,
"error value");
}),
];
await Promise.all(promises);
browser.test.notifyPass("executeScript-lastError");
}
let extension = ExtensionTestUtils.loadExtension({

View File

@ -7,7 +7,7 @@ requestLongerTimeout(2);
function* testHasPermission(params) {
let contentSetup = params.contentSetup || (() => Promise.resolve());
function background(contentSetup) {
async function background(contentSetup) {
browser.runtime.onMessage.addListener((msg, sender) => {
browser.test.assertEq(msg, "script ran", "script ran");
browser.test.notifyPass("executeScript");
@ -21,9 +21,9 @@ function* testHasPermission(params) {
});
});
contentSetup().then(() => {
browser.test.sendMessage("ready");
});
await contentSetup();
browser.test.sendMessage("ready");
}
let extension = ExtensionTestUtils.loadExtension({
@ -122,14 +122,9 @@ add_task(function* testGoodPermissions() {
"permissions": ["activeTab"],
"page_action": {},
},
contentSetup() {
return new Promise(resolve => {
browser.tabs.query({active: true, currentWindow: true}, tabs => {
browser.pageAction.show(tabs[0].id).then(() => {
resolve();
});
});
});
contentSetup: async () => {
let [tab] = await browser.tabs.query({active: true, currentWindow: true});
await browser.pageAction.show(tab.id);
},
setup: clickPageAction,
tearDown: closePageAction,
@ -141,10 +136,9 @@ add_task(function* testGoodPermissions() {
"permissions": ["activeTab"],
"browser_action": {"default_popup": "_blank.html"},
},
setup: extension => {
return clickBrowserAction(extension).then(() => {
return awaitExtensionPanel(extension, window, "_blank.html");
});
setup: async extension => {
await clickBrowserAction(extension);
return awaitExtensionPanel(extension, window, "_blank.html");
},
tearDown: closeBrowserAction,
});
@ -155,14 +149,9 @@ add_task(function* testGoodPermissions() {
"permissions": ["activeTab"],
"page_action": {"default_popup": "_blank.html"},
},
contentSetup() {
return new Promise(resolve => {
browser.tabs.query({active: true, currentWindow: true}, tabs => {
browser.pageAction.show(tabs[0].id).then(() => {
resolve();
});
});
});
contentSetup: async () => {
let [tab] = await browser.tabs.query({active: true, currentWindow: true});
await browser.pageAction.show(tab.id);
},
setup: clickPageAction,
tearDown: closePageAction,

View File

@ -17,37 +17,36 @@
add_task(function* testExecuteScript() {
let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank", true);
function background() {
async function background() {
let tab;
const BASE = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/";
const URL = BASE + "file_iframe_document.sjs";
const MAX_TRIES = 10;
let tries = 0;
function again() {
if (tries++ == MAX_TRIES) {
return Promise.reject(new Error("Max tries exceeded"));
}
try {
[tab] = await browser.tabs.query({active: true, currentWindow: true});
let url = `${URL}?r=${Math.random()}`;
let success = false;
for (let tries = 0; !success && tries < MAX_TRIES; tries++) {
let url = `${URL}?r=${Math.random()}`;
let loadingPromise = new Promise(resolve => {
browser.tabs.onUpdated.addListener(function listener(tabId, changed, tab_) {
if (tabId == tab.id && changed.status == "loading" && tab_.url == url) {
browser.tabs.onUpdated.removeListener(listener);
resolve();
}
let loadingPromise = new Promise(resolve => {
browser.tabs.onUpdated.addListener(function listener(tabId, changed, tab_) {
if (tabId == tab.id && changed.status == "loading" && tab_.url == url) {
browser.tabs.onUpdated.removeListener(listener);
resolve();
}
});
});
});
// TODO: Test allFrames and frameId.
// TODO: Test allFrames and frameId.
return browser.tabs.update({url}).then(() => {
return loadingPromise;
}).then(() => {
return Promise.all([
await browser.tabs.update({url});
await loadingPromise;
let states = await Promise.all([
// Send the executeScript requests in the reverse order that we expect
// them to execute in, to avoid them passing only because of timing
// races.
@ -64,7 +63,7 @@ add_task(function* testExecuteScript() {
runAt: "document_start",
}),
].reverse());
}).then(states => {
browser.test.log(`Got states: ${states}`);
// Make sure that none of our scripts executed earlier than expected,
@ -76,22 +75,18 @@ add_task(function* testExecuteScript() {
// If we have the earliest valid states for each script, we're done.
// Otherwise, try again.
if (states[0] != "loading" || states[1] != "interactive" || states[2] != "complete") {
return again();
}
});
}
success = (states[0] == "loading" &&
states[1] == "interactive" &&
states[2] == "complete");
}
browser.tabs.query({active: true, currentWindow: true}).then(tabs => {
tab = tabs[0];
browser.test.assertTrue(success, "Got the earliest expected states at least once");
return again();
}).then(() => {
browser.test.notifyPass("executeScript-runAt");
}).catch(e => {
} catch (e) {
browser.test.fail(`Error: ${e} :: ${e.stack}`);
browser.test.notifyFail("executeScript-runAt");
});
}
}
let extension = ExtensionTestUtils.loadExtension({

View File

@ -10,8 +10,8 @@ add_task(function* testExecuteScript() {
let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://mochi.test:8888/", true);
function background() {
let promises = [
async function background() {
let tasks = [
{
background: "transparent",
foreground: "rgb(0, 113, 4)",
@ -37,31 +37,25 @@ add_task(function* testExecuteScript() {
return [computedStyle.backgroundColor, computedStyle.color];
}
function next() {
if (!promises.length) {
return;
}
try {
for (let {promise, background, foreground} of tasks) {
let result = await promise();
let {promise, background, foreground} = promises.shift();
return promise().then(result => {
browser.test.assertEq(undefined, result, "Expected callback result");
return browser.tabs.executeScript({
[result] = await browser.tabs.executeScript({
code: `(${checkCSS})()`,
});
}).then(([result]) => {
browser.test.assertEq(background, result[0], "Expected background color");
browser.test.assertEq(foreground, result[1], "Expected foreground color");
return next();
});
}
}
next().then(() => {
browser.test.notifyPass("insertCSS");
}).catch(e => {
} catch (e) {
browser.test.fail(`Error: ${e} :: ${e.stack}`);
browser.test.notifyFailure("insertCSS");
});
}
}
let extension = ExtensionTestUtils.loadExtension({

View File

@ -65,29 +65,22 @@ add_task(function* () {
"permissions": ["tabs"],
},
background: function() {
browser.tabs.query(
{lastFocusedWindow: true},
async background() {
let [, tab] = await browser.tabs.query({lastFocusedWindow: true});
// Assuming that tab.id of 12345 does not exist.
await browser.tabs.move([tab.id, 12345], {index: 0}).then(
tabs => {
let tab = tabs[1];
// Assuming that tab.id of 12345 does not exist.
browser.tabs.move([tab.id, 12345], {index: 0})
.then(
tabs => { browser.test.fail("Promise should not resolve"); },
e => {
browser.test.assertTrue(/Invalid tab/.test(e),
"Invalid tab should be in error");
})
.then(
browser.tabs.query({lastFocusedWindow: true})
.then(
(tabs) => {
browser.test.assertEq(tabs[1].url, tab.url, "should be second tab");
browser.test.notifyPass("tabs.move.invalid");
}
)
);
browser.test.fail("Promise should not resolve");
},
e => {
browser.test.assertTrue(/Invalid tab/.test(e),
"Invalid tab should be in error");
});
let tabs = await browser.tabs.query({lastFocusedWindow: true});
browser.test.assertEq(tabs[1].url, tab.url, "should be second tab");
browser.test.notifyPass("tabs.move.invalid");
},
});

View File

@ -12,32 +12,27 @@ add_task(function* () {
"permissions": ["tabs"],
},
background: function() {
browser.tabs.query({
url: "<all_urls>",
}, function(tabs) {
let destination = tabs[0];
let source = tabs[1]; // skip over about:blank in window1
browser.tabs.move(source.id, {windowId: destination.windowId, index: 0});
async background() {
let tabs = await browser.tabs.query({url: "<all_urls>"});
let destination = tabs[0];
let source = tabs[1]; // skip over about:blank in window1
browser.tabs.query(
{url: "<all_urls>"},
tabs => {
browser.test.assertEq(tabs[0].url, "http://example.com/");
browser.test.assertEq(tabs[0].windowId, destination.windowId);
browser.test.notifyPass("tabs.move.window");
});
// Assuming that this windowId does not exist.
await browser.tabs.move(source.id, {windowId: 123144576, index: 0}).then(
tabs => {
browser.test.fail("Promise should not resolve");
},
e => {
browser.test.assertTrue(/Invalid window/.test(e),
"Invalid window should be in error");
});
// Assuming that this windowId does not exist.
browser.tabs.move(source.id, {windowId: 123144576, index: 0})
.then(
tabs => { browser.test.fail("Promise should not resolve"); },
e => {
browser.test.assertTrue(/Invalid window/.test(e),
"Invalid window should be in error");
}
);
});
browser.tabs.move(source.id, {windowId: destination.windowId, index: 0});
tabs = await browser.tabs.query({url: "<all_urls>"});
browser.test.assertEq(tabs[0].url, "http://example.com/");
browser.test.assertEq(tabs[0].windowId, destination.windowId);
browser.test.notifyPass("tabs.move.window");
},
});
@ -66,23 +61,23 @@ add_task(function* test_currentWindowAfterTabMoved() {
},
};
function background() {
async function background() {
let tabId;
const url = browser.extension.getURL("current.html");
browser.tabs.create({url}).then(tab => {
tabId = tab.id;
});
browser.test.onMessage.addListener(msg => {
browser.test.onMessage.addListener(async msg => {
if (msg === "move") {
browser.windows.create({tabId}).then(() => {
browser.test.sendMessage("moved");
});
await browser.windows.create({tabId});
browser.test.sendMessage("moved");
} else if (msg === "close") {
browser.tabs.remove(tabId).then(() => {
browser.test.sendMessage("done");
});
await browser.tabs.remove(tabId);
browser.test.sendMessage("done");
}
});
let tab = await browser.tabs.create({url});
tabId = tab.id;
}
const extension = ExtensionTestUtils.loadExtension({files, background});

View File

@ -3,7 +3,7 @@
"use strict";
add_task(function* testTabEvents() {
function background() {
async function background() {
/** The list of active tab ID's */
let tabIds = [];
@ -39,79 +39,77 @@ add_task(function* testTabEvents() {
*
* @param {number} tabId
* @param {Array<string>} expectedEvents
* @returns {Promise}
*/
function expectEvents(tabId, expectedEvents) {
async function expectEvents(tabId, expectedEvents) {
browser.test.log(`Expecting events: ${expectedEvents.join(", ")}`);
return new Promise(resolve => {
setTimeout(resolve, 0);
}).then(() => {
browser.test.assertEq(expectedEvents.length, events[tabId].length,
`Got expected number of events for ${tabId}`);
for (let [i, name] of expectedEvents.entries()) {
browser.test.assertEq(name, i in events[tabId] && events[tabId][i],
`Got expected ${name} event`);
}
delete events[tabId];
});
await new Promise(resolve => setTimeout(resolve, 0));
browser.test.assertEq(expectedEvents.length, events[tabId].length,
`Got expected number of events for ${tabId}`);
for (let [i, name] of expectedEvents.entries()) {
browser.test.assertEq(name, i in events[tabId] && events[tabId][i],
`Got expected ${name} event`);
}
delete events[tabId];
}
/**
* Opens a new tab and asserts that the correct events are fired.
*
* @param {number} windowId
* @returns {Promise}
*/
function openTab(windowId) {
return browser.tabs.create({windowId}).then(tab => {
tabIds.push(tab.id);
browser.test.log(`Opened tab ${tab.id}`);
return expectEvents(tab.id, [
"onActivated",
"onHighlighted",
]);
});
async function openTab(windowId) {
let tab = await browser.tabs.create({windowId});
tabIds.push(tab.id);
browser.test.log(`Opened tab ${tab.id}`);
await expectEvents(tab.id, [
"onActivated",
"onHighlighted",
]);
}
/**
* Highlights an existing tab and asserts that the correct events are fired.
*
* @param {number} tabId
* @returns {Promise}
*/
function highlightTab(tabId) {
async function highlightTab(tabId) {
browser.test.log(`Highlighting tab ${tabId}`);
return browser.tabs.update(tabId, {active: true}).then(tab => {
browser.test.assertEq(tab.id, tabId, `Tab ${tab.id} highlighted`);
return expectEvents(tab.id, [
"onActivated",
"onHighlighted",
]);
});
let tab = await browser.tabs.update(tabId, {active: true});
browser.test.assertEq(tab.id, tabId, `Tab ${tab.id} highlighted`);
await expectEvents(tab.id, [
"onActivated",
"onHighlighted",
]);
}
/**
* The main entry point to the tests.
*/
browser.tabs.query({active: true, currentWindow: true}, tabs => {
let activeWindow = tabs[0].windowId;
Promise.all([
openTab(activeWindow),
openTab(activeWindow),
openTab(activeWindow),
]).then(() => {
return Promise.all([
highlightTab(tabIds[0]),
highlightTab(tabIds[1]),
highlightTab(tabIds[2]),
]);
}).then(() => {
return Promise.all(tabIds.map(id => browser.tabs.remove(id)));
}).then(() => {
browser.test.notifyPass("tabs.highlight");
});
});
let tabs = await browser.tabs.query({active: true, currentWindow: true});
let activeWindow = tabs[0].windowId;
await Promise.all([
openTab(activeWindow),
openTab(activeWindow),
openTab(activeWindow),
]);
await Promise.all([
highlightTab(tabIds[0]),
highlightTab(tabIds[1]),
highlightTab(tabIds[2]),
]);
await Promise.all(tabIds.map(id => browser.tabs.remove(id)));
browser.test.notifyPass("tabs.highlight");
}
let extension = ExtensionTestUtils.loadExtension({

View File

@ -139,11 +139,11 @@ add_task(function* () {
},
background: function() {
browser.test.onMessage.addListener((msg) => {
browser.tabs.query({active: true}).then(tabs => {
browser.test.assertEq(tabs.length, 1, "should have one tab");
browser.test.sendMessage("dims", {width: tabs[0].width, height: tabs[0].height});
});
browser.test.onMessage.addListener(async msg => {
let tabs = await browser.tabs.query({active: true});
browser.test.assertEq(tabs.length, 1, "should have one tab");
browser.test.sendMessage("dims", {width: tabs[0].width, height: tabs[0].height});
});
browser.test.sendMessage("ready");
},
@ -182,13 +182,14 @@ add_task(function* testQueryPermissions() {
"permissions": [],
},
background: function(x) {
browser.tabs.query({currentWindow: true, active: true}).then((tabs) => {
async background() {
try {
let tabs = await browser.tabs.query({currentWindow: true, active: true});
browser.test.assertEq(tabs.length, 1, "Expect query to return tabs");
browser.test.notifyPass("queryPermissions");
}).catch((e) => {
} catch (e) {
browser.test.notifyFail("queryPermissions");
});
}
},
});
@ -205,7 +206,7 @@ add_task(function* testQueryWithURLPermissions() {
"permissions": [],
},
background: function(x) {
background: function() {
browser.tabs.query({"url": "http://www.bbc.com/"}).then(() => {
browser.test.notifyFail("queryWithURLPermissions");
}).catch((e) => {

View File

@ -19,31 +19,31 @@ add_task(function* () {
</head>`,
},
background: function() {
async background() {
let tabLoadedCount = 0;
browser.tabs.create({url: "tab.html", active: true}).then(tab => {
browser.runtime.onMessage.addListener(msg => {
if (msg == "tab-loaded") {
tabLoadedCount++;
let tab = await browser.tabs.create({url: "tab.html", active: true});
if (tabLoadedCount == 1) {
// Reload the tab once passing no arguments.
return browser.tabs.reload();
}
browser.runtime.onMessage.addListener(msg => {
if (msg == "tab-loaded") {
tabLoadedCount++;
if (tabLoadedCount == 2) {
// Reload the tab again with explicit arguments.
return browser.tabs.reload(tab.id, {
bypassCache: false,
});
}
if (tabLoadedCount == 3) {
browser.test.notifyPass("tabs.reload");
}
if (tabLoadedCount == 1) {
// Reload the tab once passing no arguments.
return browser.tabs.reload();
}
});
if (tabLoadedCount == 2) {
// Reload the tab again with explicit arguments.
return browser.tabs.reload(tab.id, {
bypassCache: false,
});
}
if (tabLoadedCount == 3) {
browser.test.notifyPass("tabs.reload");
}
}
});
},
});

View File

@ -8,7 +8,7 @@ add_task(function* () {
"permissions": ["tabs", "<all_urls>"],
},
background: function() {
async background() {
const BASE = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/";
const URL = BASE + "file_bypass_cache.sjs";
@ -23,33 +23,32 @@ add_task(function* () {
});
}
let tabId;
browser.tabs.create({url: URL}).then((tab) => {
tabId = tab.id;
return awaitLoad(tabId);
}).then(() => {
return browser.tabs.reload(tabId, {bypassCache: false});
}).then(() => {
return awaitLoad(tabId);
}).then(() => {
return browser.tabs.executeScript(tabId, {code: "document.body.textContent"});
}).then(([textContent]) => {
try {
let tab = await browser.tabs.create({url: URL});
await awaitLoad(tab.id);
await browser.tabs.reload(tab.id, {bypassCache: false});
await awaitLoad(tab.id);
let [textContent] = await browser.tabs.executeScript(tab.id, {code: "document.body.textContent"});
browser.test.assertEq("", textContent, "`textContent` should be empty when bypassCache=false");
return browser.tabs.reload(tabId, {bypassCache: true});
}).then(() => {
return awaitLoad(tabId);
}).then(() => {
return browser.tabs.executeScript(tabId, {code: "document.body.textContent"});
}).then(([textContent]) => {
await browser.tabs.reload(tab.id, {bypassCache: true});
await awaitLoad(tab.id);
[textContent] = await browser.tabs.executeScript(tab.id, {code: "document.body.textContent"});
let [pragma, cacheControl] = textContent.split(":");
browser.test.assertEq("no-cache", pragma, "`pragma` should be set to `no-cache` when bypassCache is true");
browser.test.assertEq("no-cache", cacheControl, "`cacheControl` should be set to `no-cache` when bypassCache is true");
browser.tabs.remove(tabId);
await browser.tabs.remove(tab.id);
browser.test.notifyPass("tabs.reload_bypass_cache");
}).catch(error => {
} catch (error) {
browser.test.fail(`${error} :: ${error.stack}`);
browser.test.notifyFail("tabs.reload_bypass_cache");
});
}
},
});

View File

@ -5,8 +5,8 @@
add_task(function* testExecuteScript() {
let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://mochi.test:8888/", true);
function background() {
let promises = [
async function background() {
let tasks = [
// Insert CSS file.
{
background: "transparent",
@ -54,31 +54,23 @@ add_task(function* testExecuteScript() {
return [computedStyle.backgroundColor, computedStyle.color];
}
function next() {
if (!promises.length) {
return;
}
let {promise, background, foreground} = promises.shift();
return promise().then(result => {
try {
for (let {promise, background, foreground} of tasks) {
let result = await promise();
browser.test.assertEq(undefined, result, "Expected callback result");
return browser.tabs.executeScript({
[result] = await browser.tabs.executeScript({
code: `(${checkCSS})()`,
});
}).then(([result]) => {
browser.test.assertEq(background, result[0], "Expected background color");
browser.test.assertEq(foreground, result[1], "Expected foreground color");
return next();
});
}
}
next().then(() => {
browser.test.notifyPass("removeCSS");
}).catch(e => {
} catch (e) {
browser.test.fail(`Error: ${e} :: ${e.stack}`);
browser.test.notifyFailure("removeCSS");
});
}
}
let extension = ExtensionTestUtils.loadExtension({

View File

@ -14,7 +14,7 @@ add_task(function* tabsSendMessageReply() {
}],
},
background: function() {
background: async function() {
let firstTab;
let promiseResponse = new Promise(resolve => {
browser.runtime.onMessage.addListener((msg, sender, respond) => {
@ -66,14 +66,13 @@ add_task(function* tabsSendMessageReply() {
});
});
browser.tabs.query({currentWindow: true, active: true}).then(tabs => {
firstTab = tabs[0].id;
browser.tabs.create({url: "http://example.com/"});
});
let tabs = await browser.tabs.query({currentWindow: true, active: true});
firstTab = tabs[0].id;
browser.tabs.create({url: "http://example.com/"});
},
files: {
"content-script.js": function() {
"content-script.js": async function() {
browser.runtime.onMessage.addListener((msg, sender, respond) => {
if (msg == "respond-now") {
respond(msg);
@ -90,6 +89,7 @@ add_task(function* tabsSendMessageReply() {
throw new Error(msg);
}
});
browser.runtime.onMessage.addListener((msg, sender, respond) => {
if (msg == "respond-now") {
respond("hello");
@ -97,9 +97,9 @@ add_task(function* tabsSendMessageReply() {
respond(msg);
}
});
browser.runtime.sendMessage("content-script-ready").then(response => {
browser.runtime.sendMessage(["got-response", response]);
});
let response = await browser.runtime.sendMessage("content-script-ready");
browser.runtime.sendMessage(["got-response", response]);
},
},
});
@ -124,7 +124,7 @@ add_task(function* tabsSendHidden() {
}],
},
background: function() {
background: async function() {
let resolveContent;
browser.runtime.onMessage.addListener((msg, sender) => {
if (msg[0] == "content-ready") {
@ -140,36 +140,34 @@ add_task(function* tabsSendHidden() {
});
};
const URL1 = "http://example.com/content1.html";
const URL2 = "http://example.com/content2.html";
browser.tabs.create({url: URL1}).then(tab => {
return awaitContent(URL1).then(() => {
return browser.tabs.sendMessage(tab.id, URL1);
}).then(url => {
browser.test.assertEq(URL1, url, "Should get response from expected content window");
try {
const URL1 = "http://example.com/content1.html";
const URL2 = "http://example.com/content2.html";
return browser.tabs.update(tab.id, {url: URL2});
}).then(() => {
return awaitContent(URL2);
}).then(() => {
return browser.tabs.sendMessage(tab.id, URL2);
}).then(url => {
browser.test.assertEq(URL2, url, "Should get response from expected content window");
let tab = await browser.tabs.create({url: URL1});
await awaitContent(URL1);
// Repeat once just to be sure the first message was processed by all
// listeners before we exit the test.
return browser.tabs.sendMessage(tab.id, URL2);
}).then(url => {
browser.test.assertEq(URL2, url, "Should get response from expected content window");
let url = await browser.tabs.sendMessage(tab.id, URL1);
browser.test.assertEq(URL1, url, "Should get response from expected content window");
await browser.tabs.update(tab.id, {url: URL2});
await awaitContent(URL2);
url = await browser.tabs.sendMessage(tab.id, URL2);
browser.test.assertEq(URL2, url, "Should get response from expected content window");
// Repeat once just to be sure the first message was processed by all
// listeners before we exit the test.
url = await browser.tabs.sendMessage(tab.id, URL2);
browser.test.assertEq(URL2, url, "Should get response from expected content window");
await browser.tabs.remove(tab.id);
return browser.tabs.remove(tab.id);
});
}).then(() => {
browser.test.notifyPass("contentscript-bfcache-window");
}).catch(error => {
} catch (error) {
browser.test.fail(`Error: ${error} :: ${error.stack}`);
browser.test.notifyFail("contentscript-bfcache-window");
});
}
},
files: {
@ -203,22 +201,20 @@ add_task(function* tabsSendMessageNoExceptionOnNonExistentTab() {
"permissions": ["tabs"],
},
background: function() {
async background() {
let url = "http://example.com/mochitest/browser/browser/components/extensions/test/browser/file_dummy.html";
browser.tabs.create({url}, tab => {
let exception;
try {
browser.tabs.sendMessage(tab.id, "message");
browser.tabs.sendMessage(tab.id + 100, "message");
} catch (e) {
exception = e;
}
let tab = await browser.tabs.create({url});
browser.test.assertEq(undefined, exception, "no exception should be raised on tabs.sendMessage to nonexistent tabs");
browser.tabs.remove(tab.id, function() {
browser.test.notifyPass("tabs.sendMessage");
});
});
try {
browser.tabs.sendMessage(tab.id, "message");
browser.tabs.sendMessage(tab.id + 100, "message");
} catch (e) {
browser.test.fail("no exception should be raised on tabs.sendMessage to nonexistent tabs");
}
await browser.tabs.remove(tab.id);
browser.test.notifyPass("tabs.sendMessage");
},
});

View File

@ -24,31 +24,21 @@ function* testTabsUpdateURL(existentTabURL, tabsUpdateURL, isErrorExpected) {
background: function() {
browser.test.sendMessage("ready", browser.runtime.getURL("tab.html"));
browser.test.onMessage.addListener((msg, tabsUpdateURL, isErrorExpected) => {
let onTabsUpdated = (tab) => {
if (isErrorExpected) {
browser.test.fail(`tabs.update with URL ${tabsUpdateURL} should be rejected`);
} else {
browser.test.assertTrue(tab, "on success the tab should be defined");
}
};
browser.test.onMessage.addListener(async (msg, tabsUpdateURL, isErrorExpected) => {
let tabs = await browser.tabs.query({lastFocusedWindow: true});
let onTabsUpdateError = (error) => {
if (!isErrorExpected) {
browser.test.fails(`tabs.update with URL ${tabsUpdateURL} should not be rejected`);
} else {
browser.test.assertTrue(/^Illegal URL/.test(error.message),
"tabs.update should be rejected with the expected error message");
}
};
try {
let tab = await browser.tabs.update(tabs[1].id, {url: tabsUpdateURL});
let onTabsUpdateDone = () => browser.test.sendMessage("done");
browser.test.assertFalse(isErrorExpected, `tabs.update with URL ${tabsUpdateURL} should be rejected`);
browser.test.assertTrue(tab, "on success the tab should be defined");
} catch (error) {
browser.test.assertTrue(isErrorExpected, `tabs.update with URL ${tabsUpdateURL} should not be rejected`);
browser.test.assertTrue(/^Illegal URL/.test(error.message),
"tabs.update should be rejected with the expected error message");
}
browser.tabs.query({lastFocusedWindow: true}, (tabs) => {
browser.tabs.update(tabs[1].id, {url: tabsUpdateURL})
.then(onTabsUpdated, onTabsUpdateError)
.then(onTabsUpdateDone);
});
browser.test.sendMessage("done");
});
},
});

View File

@ -10,7 +10,7 @@ add_task(function* () {
gBrowser.selectedTab = tab1;
function background() {
async function background() {
function promiseUpdated(tabId, attr) {
return new Promise(resolve => {
let onUpdated = (tabId_, changeInfo, tab) => {
@ -50,10 +50,10 @@ add_task(function* () {
}
});
let awaitZoom = (tabId, newValue) => {
let awaitZoom = async (tabId, newValue) => {
let listener;
return new Promise(resolve => {
await new Promise(async resolve => {
listener = info => {
if (info.tabId == tabId && info.newZoomFactor == newValue) {
resolve();
@ -61,17 +61,16 @@ add_task(function* () {
};
browser.tabs.onZoomChange.addListener(listener);
browser.tabs.getZoom(tabId).then(zoomFactor => {
if (zoomFactor == newValue) {
resolve();
}
});
}).then(() => {
browser.tabs.onZoomChange.removeListener(listener);
let zoomFactor = await browser.tabs.getZoom(tabId);
if (zoomFactor == newValue) {
resolve();
}
});
browser.tabs.onZoomChange.removeListener(listener);
};
let checkZoom = (tabId, newValue, oldValue = null) => {
let checkZoom = async (tabId, newValue, oldValue = null) => {
let awaitEvent;
if (oldValue != null && !zoomEvents.length) {
awaitEvent = new Promise(resolve => {
@ -79,95 +78,90 @@ add_task(function* () {
});
}
return Promise.all([
let [apiZoom, realZoom] = await Promise.all([
browser.tabs.getZoom(tabId),
msg("get-zoom", tabId),
awaitEvent,
]).then(([apiZoom, realZoom]) => {
browser.test.assertEq(newValue, apiZoom, `Got expected zoom value from API`);
browser.test.assertEq(newValue, realZoom, `Got expected zoom value from parent`);
]);
if (oldValue != null) {
let event = zoomEvents.shift();
browser.test.assertEq(tabId, event.tabId, `Got expected zoom event tab ID`);
browser.test.assertEq(newValue, event.newZoomFactor, `Got expected zoom event zoom factor`);
browser.test.assertEq(oldValue, event.oldZoomFactor, `Got expected zoom event old zoom factor`);
browser.test.assertEq(newValue, apiZoom, `Got expected zoom value from API`);
browser.test.assertEq(newValue, realZoom, `Got expected zoom value from parent`);
browser.test.assertEq(3, Object.keys(event.zoomSettings).length, `Zoom settings should have 3 keys`);
browser.test.assertEq("automatic", event.zoomSettings.mode, `Mode should be "automatic"`);
browser.test.assertEq("per-origin", event.zoomSettings.scope, `Scope should be "per-origin"`);
browser.test.assertEq(1, event.zoomSettings.defaultZoomFactor, `Default zoom should be 1`);
}
});
if (oldValue != null) {
let event = zoomEvents.shift();
browser.test.assertEq(tabId, event.tabId, `Got expected zoom event tab ID`);
browser.test.assertEq(newValue, event.newZoomFactor, `Got expected zoom event zoom factor`);
browser.test.assertEq(oldValue, event.oldZoomFactor, `Got expected zoom event old zoom factor`);
browser.test.assertEq(3, Object.keys(event.zoomSettings).length, `Zoom settings should have 3 keys`);
browser.test.assertEq("automatic", event.zoomSettings.mode, `Mode should be "automatic"`);
browser.test.assertEq("per-origin", event.zoomSettings.scope, `Scope should be "per-origin"`);
browser.test.assertEq(1, event.zoomSettings.defaultZoomFactor, `Default zoom should be 1`);
}
};
let tabIds;
browser.tabs.query({lastFocusedWindow: true}).then(tabs => {
try {
let tabs = await browser.tabs.query({lastFocusedWindow: true});
browser.test.assertEq(tabs.length, 3, "We have three tabs");
tabIds = [tabs[1].id, tabs[2].id];
let tabIds = [tabs[1].id, tabs[2].id];
await checkZoom(tabIds[0], 1);
return checkZoom(tabIds[0], 1);
}).then(() => {
return browser.tabs.setZoom(tabIds[0], 2);
}).then(() => {
return checkZoom(tabIds[0], 2, 1);
}).then(() => {
return browser.tabs.getZoomSettings(tabIds[0]);
}).then(zoomSettings => {
await browser.tabs.setZoom(tabIds[0], 2);
await checkZoom(tabIds[0], 2, 1);
let zoomSettings = await browser.tabs.getZoomSettings(tabIds[0]);
browser.test.assertEq(3, Object.keys(zoomSettings).length, `Zoom settings should have 3 keys`);
browser.test.assertEq("automatic", zoomSettings.mode, `Mode should be "automatic"`);
browser.test.assertEq("per-origin", zoomSettings.scope, `Scope should be "per-origin"`);
browser.test.assertEq(1, zoomSettings.defaultZoomFactor, `Default zoom should be 1`);
browser.test.log(`Switch to tab 2`);
return browser.tabs.update(tabIds[1], {active: true});
}).then(() => {
return checkZoom(tabIds[1], 1);
}).then(() => {
await browser.tabs.update(tabIds[1], {active: true});
await checkZoom(tabIds[1], 1);
browser.test.log(`Navigate tab 2 to origin of tab 1`);
browser.tabs.update(tabIds[1], {url: "http://example.com"});
await promiseUpdated(tabIds[1], "url");
await checkZoom(tabIds[1], 2, 1);
return promiseUpdated(tabIds[1], "url");
}).then(() => {
return checkZoom(tabIds[1], 2, 1);
}).then(() => {
browser.test.log(`Update zoom in tab 2, expect changes in both tabs`);
return browser.tabs.setZoom(tabIds[1], 1.5);
}).then(() => {
return checkZoom(tabIds[1], 1.5, 2);
}).then(() => {
await browser.tabs.setZoom(tabIds[1], 1.5);
await checkZoom(tabIds[1], 1.5, 2);
browser.test.log(`Switch to tab 1, expect asynchronous zoom change just after the switch`);
return Promise.all([
await Promise.all([
awaitZoom(tabIds[0], 1.5),
browser.tabs.update(tabIds[0], {active: true}),
]);
}).then(() => {
return checkZoom(tabIds[0], 1.5, 2);
}).then(() => {
await checkZoom(tabIds[0], 1.5, 2);
browser.test.log("Set zoom to 0, expect it set to 1");
return browser.tabs.setZoom(tabIds[0], 0);
}).then(() => {
return checkZoom(tabIds[0], 1, 1.5);
}).then(() => {
await browser.tabs.setZoom(tabIds[0], 0);
await checkZoom(tabIds[0], 1, 1.5);
browser.test.log("Change zoom externally, expect changes reflected");
return msg("enlarge");
}).then(() => {
return checkZoom(tabIds[0], 1.1, 1);
}).then(() => {
return Promise.all([
await msg("enlarge");
await checkZoom(tabIds[0], 1.1, 1);
await Promise.all([
browser.tabs.setZoom(tabIds[0], 0),
browser.tabs.setZoom(tabIds[1], 0),
]);
}).then(() => {
return Promise.all([
await Promise.all([
checkZoom(tabIds[0], 1, 1.1),
checkZoom(tabIds[1], 1, 1.5),
]);
}).then(() => {
browser.test.log("Check that invalid zoom values throw an error");
return browser.tabs.setZoom(tabIds[0], 42).then(
await browser.tabs.setZoom(tabIds[0], 42).then(
() => {
browser.test.fail("Expected an error");
},
@ -175,21 +169,20 @@ add_task(function* () {
browser.test.assertTrue(error.message.includes("Zoom value 42 out of range"),
"Got expected error");
});
}).then(() => {
browser.test.log("Disable site-specific zoom, expect correct scope");
return msg("site-specific", false);
}).then(() => {
return browser.tabs.getZoomSettings(tabIds[0]);
}).then(zoomSettings => {
await msg("site-specific", false);
zoomSettings = await browser.tabs.getZoomSettings(tabIds[0]);
browser.test.assertEq("per-tab", zoomSettings.scope, `Scope should be "per-tab"`);
}).then(() => {
return msg("site-specific", null);
}).then(() => {
await msg("site-specific", null);
browser.test.notifyPass("tab-zoom");
}).catch(e => {
} catch (e) {
browser.test.fail(`Error: ${e} :: ${e.stack}`);
browser.test.notifyFail("tab-zoom");
});
}
}
let extension = ExtensionTestUtils.loadExtension({

View File

@ -20,15 +20,13 @@ add_task(function* webNavigation_getFrameId_of_existing_main_frame() {
const DUMMY_URL = BASE + "file_dummy.html";
let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, DUMMY_URL, true);
function background(DUMMY_URL) {
browser.tabs.query({active: true, currentWindow: true}).then(tabs => {
return browser.webNavigation.getAllFrames({tabId: tabs[0].id});
}).then(frames => {
browser.test.assertEq(1, frames.length, "The dummy page has one frame");
browser.test.assertEq(0, frames[0].frameId, "Main frame's ID must be 0");
browser.test.assertEq(DUMMY_URL, frames[0].url, "Main frame URL must match");
browser.test.notifyPass("frameId checked");
});
async function background(DUMMY_URL) {
let tabs = await browser.tabs.query({active: true, currentWindow: true});
let frames = await browser.webNavigation.getAllFrames({tabId: tabs[0].id});
browser.test.assertEq(1, frames.length, "The dummy page has one frame");
browser.test.assertEq(0, frames[0].frameId, "Main frame's ID must be 0");
browser.test.assertEq(DUMMY_URL, frames[0].url, "Main frame URL must match");
browser.test.notifyPass("frameId checked");
}
let extension = ExtensionTestUtils.loadExtension({

View File

@ -4,7 +4,7 @@
add_task(function* testWebNavigationGetNonExistentTab() {
let extension = ExtensionTestUtils.loadExtension({
background: "(" + function() {
background: async function() {
let results = [
// There is no "tabId = 0" because the id assigned by TabManager (defined in ext-utils.js)
// starts from 1.
@ -14,6 +14,7 @@ add_task(function* testWebNavigationGetNonExistentTab() {
browser.test.assertEq("Invalid tab ID: 0", error.message,
"getAllFrames rejected Promise should pass the expected error");
}),
// There is no "tabId = 0" because the id assigned by TabManager (defined in ext-utils.js)
// starts from 1, processId is currently marked as optional and it is ignored.
browser.webNavigation.getFrame({tabId: 0, frameId: 15, processId: 20}).then(() => {
@ -24,10 +25,10 @@ add_task(function* testWebNavigationGetNonExistentTab() {
}),
];
Promise.all(results).then(() => {
browser.test.sendMessage("getNonExistentTab.done");
});
} + ")();",
await Promise.all(results);
browser.test.sendMessage("getNonExistentTab.done");
},
manifest: {
permissions: ["webNavigation"],
},
@ -45,11 +46,11 @@ add_task(function* testWebNavigationGetNonExistentTab() {
add_task(function* testWebNavigationFrames() {
let extension = ExtensionTestUtils.loadExtension({
background: "(" + function() {
background: async function() {
let tabId;
let collectedDetails = [];
browser.webNavigation.onCompleted.addListener((details) => {
browser.webNavigation.onCompleted.addListener(async details => {
collectedDetails.push(details);
if (details.frameId !== 0) {
@ -57,46 +58,43 @@ add_task(function* testWebNavigationFrames() {
return;
}
browser.webNavigation.getAllFrames({tabId}).then((getAllFramesDetails) => {
let getFramePromises = getAllFramesDetails.map((frameDetail) => {
let {frameId} = frameDetail;
// processId is currently marked as optional and it is ignored.
return browser.webNavigation.getFrame({tabId, frameId, processId: 0});
});
let getAllFramesDetails = await browser.webNavigation.getAllFrames({tabId});
Promise.all(getFramePromises).then((getFrameResults) => {
browser.test.sendMessage("webNavigationFrames.done", {
collectedDetails, getAllFramesDetails, getFrameResults,
});
}, () => {
browser.test.assertTrue(false, "None of the getFrame promises should have been rejected");
});
let getFramePromises = getAllFramesDetails.map(({frameId}) => {
// processId is currently marked as optional and it is ignored.
return browser.webNavigation.getFrame({tabId, frameId, processId: 0});
});
// Pick a random frameId.
let nonExistentFrameId = Math.floor(Math.random() * 10000);
let getFrameResults = await Promise.all(getFramePromises);
browser.test.sendMessage("webNavigationFrames.done", {
collectedDetails, getAllFramesDetails, getFrameResults,
});
// Increment the picked random nonExistentFrameId until it doesn't exists.
while (getAllFramesDetails.filter((details) => details.frameId == nonExistentFrameId).length > 0) {
nonExistentFrameId += 1;
}
// Pick a random frameId.
let nonExistentFrameId = Math.floor(Math.random() * 10000);
// Check that getFrame Promise is rejected with the expected error message on nonexistent frameId.
browser.webNavigation.getFrame({tabId, frameId: nonExistentFrameId, processId: 20}).then(() => {
// Increment the picked random nonExistentFrameId until it doesn't exists.
while (getAllFramesDetails.filter((details) => details.frameId == nonExistentFrameId).length > 0) {
nonExistentFrameId += 1;
}
// Check that getFrame Promise is rejected with the expected error message on nonexistent frameId.
await browser.webNavigation.getFrame({tabId, frameId: nonExistentFrameId, processId: 20}).then(
() => {
browser.test.fail("getFrame promise should be rejected for an unexistent frameId");
}, (error) => {
},
error => {
browser.test.assertEq(`No frame found with frameId: ${nonExistentFrameId}`, error.message,
"getFrame promise should be rejected with the expected error message on unexistent frameId");
}).then(() => {
browser.tabs.remove(tabId);
browser.test.sendMessage("webNavigationFrames.done");
});
});
await browser.tabs.remove(tabId);
browser.test.sendMessage("webNavigationFrames.done");
});
browser.tabs.create({url: "tab.html"}, (tab) => {
tabId = tab.id;
});
} + ")();",
let tab = await browser.tabs.create({url: "tab.html"});
tabId = tab.id;
},
manifest: {
permissions: ["webNavigation", "tabs"],
},

View File

@ -4,7 +4,7 @@
add_task(function* testWindowCreate() {
let extension = ExtensionTestUtils.loadExtension({
background() {
async background() {
let _checkWindowPromise;
browser.test.onMessage.addListener(msg => {
if (msg == "checked-window") {
@ -22,59 +22,61 @@ add_task(function* testWindowCreate() {
});
}
function createWindow(params, expected, keep = false) {
return browser.windows.create(params).then(window => {
for (let key of Object.keys(params)) {
if (key == "state" && os == "mac" && params.state == "normal") {
// OS-X doesn't have a hard distinction between "normal" and
// "maximized" states.
browser.test.assertTrue(window.state == "normal" || window.state == "maximized",
`Expected window.state (currently ${window.state}) to be "normal" but will accept "maximized"`);
} else {
browser.test.assertEq(params[key], window[key], `Got expected value for window.${key}`);
}
}
async function createWindow(params, expected, keep = false) {
let window = await browser.windows.create(params);
browser.test.assertEq(1, window.tabs.length, "tabs property got populated");
return checkWindow(expected).then(() => {
if (keep) {
return window;
}
if (params.state == "fullscreen" && os == "win") {
// FIXME: Closing a fullscreen window causes a window leak in
// Windows tests.
return browser.windows.update(window.id, {state: "normal"}).then(() => {
return browser.windows.remove(window.id);
});
}
return browser.windows.remove(window.id);
});
});
for (let key of Object.keys(params)) {
if (key == "state" && os == "mac" && params.state == "normal") {
// OS-X doesn't have a hard distinction between "normal" and
// "maximized" states.
browser.test.assertTrue(window.state == "normal" || window.state == "maximized",
`Expected window.state (currently ${window.state}) to be "normal" but will accept "maximized"`);
} else {
browser.test.assertEq(params[key], window[key], `Got expected value for window.${key}`);
}
}
browser.test.assertEq(1, window.tabs.length, "tabs property got populated");
await checkWindow(expected);
if (keep) {
return window;
}
if (params.state == "fullscreen" && os == "win") {
// FIXME: Closing a fullscreen window causes a window leak in
// Windows tests.
await browser.windows.update(window.id, {state: "normal"});
}
await browser.windows.remove(window.id);
}
browser.runtime.getPlatformInfo().then(info => { os = info.os; })
.then(() => createWindow({state: "maximized"}, {state: "STATE_MAXIMIZED"}))
.then(() => createWindow({state: "minimized"}, {state: "STATE_MINIMIZED"}))
.then(() => createWindow({state: "normal"}, {state: "STATE_NORMAL", hiddenChrome: []}))
.then(() => createWindow({state: "fullscreen"}, {state: "STATE_FULLSCREEN"}))
.then(() => {
return createWindow({type: "popup"},
{hiddenChrome: ["menubar", "toolbar", "location", "directories", "status", "extrachrome"],
chromeFlags: ["CHROME_OPENAS_DIALOG"]},
true);
}).then(window => {
return browser.tabs.query({windowType: "popup", active: true}).then(tabs => {
browser.test.assertEq(1, tabs.length, "Expected only one popup");
browser.test.assertEq(window.id, tabs[0].windowId, "Expected new window to be returned in query");
try {
({os} = await browser.runtime.getPlatformInfo());
await createWindow({state: "maximized"}, {state: "STATE_MAXIMIZED"});
await createWindow({state: "minimized"}, {state: "STATE_MINIMIZED"});
await createWindow({state: "normal"}, {state: "STATE_NORMAL", hiddenChrome: []});
await createWindow({state: "fullscreen"}, {state: "STATE_FULLSCREEN"});
let window = await createWindow(
{type: "popup"},
{hiddenChrome: ["menubar", "toolbar", "location", "directories", "status", "extrachrome"],
chromeFlags: ["CHROME_OPENAS_DIALOG"]},
true);
let tabs = await browser.tabs.query({windowType: "popup", active: true});
browser.test.assertEq(1, tabs.length, "Expected only one popup");
browser.test.assertEq(window.id, tabs[0].windowId, "Expected new window to be returned in query");
await browser.windows.remove(window.id);
return browser.windows.remove(window.id);
});
}).then(() => {
browser.test.notifyPass("window-create");
}).catch(e => {
} catch (e) {
browser.test.fail(`${e} :: ${e.stack}`);
browser.test.notifyFail("window-create");
});
}
},
});

View File

@ -6,7 +6,7 @@
// Tests that incompatible parameters can't be used together.
add_task(function* testWindowCreateParams() {
let extension = ExtensionTestUtils.loadExtension({
background() {
async background() {
function* getCalls() {
for (let state of ["minimized", "maximized", "fullscreen"]) {
for (let param of ["left", "top", "width", "height"]) {
@ -25,12 +25,14 @@ add_task(function* testWindowCreateParams() {
}
}
Promise.all(getCalls()).then(() => {
try {
await Promise.all(getCalls());
browser.test.notifyPass("window-create-params");
}).catch(e => {
} catch (e) {
browser.test.fail(`${e} :: ${e.stack}`);
browser.test.notifyFail("window-create-params");
});
}
},
});

View File

@ -3,7 +3,7 @@
"use strict";
add_task(function* testWindowCreate() {
function background() {
async function background() {
let promiseTabAttached = () => {
return new Promise(resolve => {
browser.tabs.onAttached.addListener(function listener() {
@ -24,96 +24,92 @@ add_task(function* testWindowCreate() {
});
};
let windowId, tabId;
browser.windows.getCurrent().then(window => {
windowId = window.id;
try {
let window = await browser.windows.getCurrent();
let windowId = window.id;
browser.test.log("Create additional tab in window 1");
return browser.tabs.create({windowId, url: "about:blank"});
}).then(tab => {
tabId = tab.id;
let tab = await browser.tabs.create({windowId, url: "about:blank"});
let tabId = tab.id;
browser.test.log("Create a new window, adopting the new tab");
// Note that we want to check against actual boolean values for
// all of the `incognito` property tests.
browser.test.assertEq(false, tab.incognito, "Tab is not private");
return Promise.all([
promiseTabAttached(),
browser.windows.create({tabId: tabId}),
]);
}).then(([, window]) => {
browser.test.assertEq(false, window.incognito, "New window is not private");
browser.test.assertEq(tabId, window.tabs[0].id, "tabs property populated correctly");
{
let [, window] = await Promise.all([
promiseTabAttached(),
browser.windows.create({tabId: tabId}),
]);
browser.test.assertEq(false, window.incognito, "New window is not private");
browser.test.assertEq(tabId, window.tabs[0].id, "tabs property populated correctly");
browser.test.log("Close the new window");
return browser.windows.remove(window.id);
}).then(() => {
browser.test.log("Create a new private window");
browser.test.log("Close the new window");
await browser.windows.remove(window.id);
}
return browser.windows.create({incognito: true});
}).then(privateWindow => {
browser.test.assertEq(true, privateWindow.incognito, "Private window is private");
{
browser.test.log("Create a new private window");
let privateWindow = await browser.windows.create({incognito: true});
browser.test.assertEq(true, privateWindow.incognito, "Private window is private");
browser.test.log("Create additional tab in private window");
return browser.tabs.create({windowId: privateWindow.id}).then(privateTab => {
browser.test.log("Create additional tab in private window");
let privateTab = await browser.tabs.create({windowId: privateWindow.id});
browser.test.assertEq(true, privateTab.incognito, "Private tab is private");
browser.test.log("Create a new window, adopting the new private tab");
return Promise.all([
let [, newWindow] = await Promise.all([
promiseTabAttached(),
browser.windows.create({tabId: privateTab.id}),
]);
}).then(([, newWindow]) => {
browser.test.assertEq(true, newWindow.incognito, "New private window is private");
browser.test.log("Close the new private window");
return browser.windows.remove(newWindow.id);
}).then(() => {
browser.test.log("Close the private window");
return browser.windows.remove(privateWindow.id);
});
}).then(() => {
return browser.tabs.query({windowId, active: true});
}).then(([tab]) => {
browser.test.log("Try to create a window with both a tab and a URL");
await browser.windows.remove(newWindow.id);
return browser.windows.create({tabId: tab.id, url: "http://example.com/"}).then(
browser.test.log("Close the private window");
await browser.windows.remove(privateWindow.id);
}
browser.test.log("Try to create a window with both a tab and a URL");
[tab] = await browser.tabs.query({windowId, active: true});
await browser.windows.create({tabId: tab.id, url: "http://example.com/"}).then(
window => {
browser.test.fail("Create call should have failed");
},
error => {
browser.test.assertTrue(/`tabId` may not be used in conjunction with `url`/.test(error.message),
"Create call failed as expected");
}).then(() => {
browser.test.log("Try to create a window with both a tab and an invalid incognito setting");
});
browser.test.log("Try to create a window with both a tab and an invalid incognito setting");
await browser.windows.create({tabId: tab.id, incognito: true}).then(
window => {
browser.test.fail("Create call should have failed");
},
error => {
browser.test.assertTrue(/`incognito` property must match the incognito state of tab/.test(error.message),
"Create call failed as expected");
});
return browser.windows.create({tabId: tab.id, incognito: true});
}).then(
window => {
browser.test.fail("Create call should have failed");
},
error => {
browser.test.assertTrue(/`incognito` property must match the incognito state of tab/.test(error.message),
"Create call failed as expected");
});
}).then(() => {
browser.test.log("Try to create a window with an invalid tabId");
return browser.windows.create({tabId: 0}).then(
await browser.windows.create({tabId: 0}).then(
window => {
browser.test.fail("Create call should have failed");
},
error => {
browser.test.assertTrue(/Invalid tab ID: 0/.test(error.message),
"Create call failed as expected");
}
);
}).then(() => {
browser.test.log("Try to create a window with two URLs");
});
return Promise.all([
browser.test.log("Try to create a window with two URLs");
[, , window] = await Promise.all([
// tabs.onUpdated can be invoked between the call of windows.create and
// the invocation of its callback/promise, so set up the listeners
// before creating the window.
@ -121,23 +117,23 @@ add_task(function* testWindowCreate() {
promiseTabUpdated("http://example.org/"),
browser.windows.create({url: ["http://example.com/", "http://example.org/"]}),
]);
}).then(([, , window]) => {
browser.test.assertEq(2, window.tabs.length, "2 tabs were opened in new window");
browser.test.assertEq("about:blank", window.tabs[0].url, "about:blank, page not loaded yet");
browser.test.assertEq("about:blank", window.tabs[1].url, "about:blank, page not loaded yet");
return browser.windows.get(window.id, {populate: true});
}).then(window => {
window = await browser.windows.get(window.id, {populate: true});
browser.test.assertEq(2, window.tabs.length, "2 tabs were opened in new window");
browser.test.assertEq("http://example.com/", window.tabs[0].url, "Correct URL was loaded in tab 1");
browser.test.assertEq("http://example.org/", window.tabs[1].url, "Correct URL was loaded in tab 2");
return browser.windows.remove(window.id);
}).then(() => {
await browser.windows.remove(window.id);
browser.test.notifyPass("window-create");
}).catch(e => {
} catch (e) {
browser.test.fail(`${e} :: ${e.stack}`);
browser.test.notifyFail("window-create");
});
}
}
let extension = ExtensionTestUtils.loadExtension({

View File

@ -8,7 +8,7 @@ add_task(function* testWindowCreate() {
permissions: ["tabs"],
},
background() {
background: async function() {
const EXTENSION_URL = browser.runtime.getURL("test.html");
const REMOTE_URL = browser.runtime.getURL("test.html");
@ -40,22 +40,22 @@ add_task(function* testWindowCreate() {
}
});
function create(options) {
return browser.windows.create(options).then(window => {
let win = windows.get(window.id);
async function create(options) {
let window = await browser.windows.create(options);
let win = windows.get(window.id);
win.expectedTabs = Array.isArray(options.url) ? options.url.length : 1;
win.expectedTabs = Array.isArray(options.url) ? options.url.length : 1;
return win.promise;
});
return win.promise;
}
Promise.all([
create({url: REMOTE_URL}),
create({url: "test.html"}),
create({url: EXTENSION_URL}),
create({url: [REMOTE_URL, "test.html", EXTENSION_URL]}),
]).then(windows => {
try {
let windows = await Promise.all([
create({url: REMOTE_URL}),
create({url: "test.html"}),
create({url: EXTENSION_URL}),
create({url: [REMOTE_URL, "test.html", EXTENSION_URL]}),
]);
browser.test.assertEq(REMOTE_URL, windows[0].tabs.get(0).url, "Single, absolute, remote URL");
browser.test.assertEq(REMOTE_URL, windows[1].tabs.get(0).url, "Single, relative URL");
@ -65,12 +65,12 @@ add_task(function* testWindowCreate() {
browser.test.assertEq(REMOTE_URL, windows[3].tabs.get(0).url, "url[0]: Absolute, remote URL");
browser.test.assertEq(EXTENSION_URL, windows[3].tabs.get(1).url, "url[1]: Relative URL");
browser.test.assertEq(EXTENSION_URL, windows[3].tabs.get(2).url, "url[2]: Absolute, extension URL");
}).then(() => {
browser.test.notifyPass("window-create-url");
}).catch(e => {
} catch (e) {
browser.test.fail(`${e} :: ${e.stack}`);
browser.test.notifyFail("window-create-url");
});
}
},
files: {

View File

@ -6,7 +6,7 @@ SimpleTest.requestCompleteLog();
add_task(function* testWindowsEvents() {
function background() {
browser.windows.onCreated.addListener(function listener(window) {
browser.windows.onCreated.addListener(window => {
browser.test.log(`onCreated: windowId=${window.id}`);
browser.test.assertTrue(Number.isInteger(window.id),
@ -17,7 +17,7 @@ add_task(function* testWindowsEvents() {
});
let lastWindowId, os;
browser.windows.onFocusChanged.addListener(function listener(windowId) {
browser.windows.onFocusChanged.addListener(async windowId => {
browser.test.log(`onFocusChange: windowId=${windowId} lastWindowId=${lastWindowId}`);
if (windowId === browser.windows.WINDOW_ID_NONE && os === "linux") {
@ -32,14 +32,14 @@ add_task(function* testWindowsEvents() {
browser.test.assertTrue(Number.isInteger(windowId),
"windowId is an integer");
browser.windows.getLastFocused().then(window => {
browser.test.assertEq(windowId, window.id,
"Last focused window has the correct id");
browser.test.sendMessage(`window-focus-changed`, window.id);
});
let window = await browser.windows.getLastFocused();
browser.test.assertEq(windowId, window.id,
"Last focused window has the correct id");
browser.test.sendMessage(`window-focus-changed`, window.id);
});
browser.windows.onRemoved.addListener(function listener(windowId) {
browser.windows.onRemoved.addListener(windowId => {
browser.test.log(`onRemoved: windowId=${windowId}`);
browser.test.assertTrue(Number.isInteger(windowId),

View File

@ -4,7 +4,7 @@
add_task(function* testWindowCreate() {
let extension = ExtensionTestUtils.loadExtension({
background() {
async background() {
let _checkWindowPromise;
browser.test.onMessage.addListener((msg, arg) => {
if (msg == "checked-window") {
@ -28,73 +28,63 @@ add_task(function* testWindowCreate() {
}
let windowId;
function checkWindow(expected, retries = 5) {
return getWindowSize().then(geom => {
if (retries && KEYS.some(key => expected[key] != geom[key])) {
browser.test.log(`Got mismatched size (${JSON.stringify(expected)} != ${JSON.stringify(geom)}). ` +
`Retrying after a short delay.`);
async function checkWindow(expected, retries = 5) {
let geom = await getWindowSize();
return new Promise(resolve => {
setTimeout(resolve, 200);
}).then(() => {
return checkWindow(expected, retries - 1);
});
}
if (retries && KEYS.some(key => expected[key] != geom[key])) {
browser.test.log(`Got mismatched size (${JSON.stringify(expected)} != ${JSON.stringify(geom)}). ` +
`Retrying after a short delay.`);
browser.test.log(`Check actual window size`);
checkGeom(expected, geom);
await new Promise(resolve => setTimeout(resolve, 200));
browser.test.log("Check API-reported window size");
return browser.windows.get(windowId).then(geom => {
checkGeom(expected, geom);
});
});
return checkWindow(expected, retries - 1);
}
browser.test.log(`Check actual window size`);
checkGeom(expected, geom);
browser.test.log("Check API-reported window size");
geom = await browser.windows.get(windowId);
checkGeom(expected, geom);
}
let geom = {left: 100, top: 100, width: 500, height: 300};
try {
let geom = {left: 100, top: 100, width: 500, height: 300};
return browser.windows.create(geom).then(window => {
let window = await browser.windows.create(geom);
windowId = window.id;
return checkWindow(geom);
}).then(() => {
await checkWindow(geom);
let update = {left: 150, width: 600};
Object.assign(geom, update);
await browser.windows.update(windowId, update);
await checkWindow(geom);
return browser.windows.update(windowId, update);
}).then(() => {
return checkWindow(geom);
}).then(() => {
let update = {top: 150, height: 400};
update = {top: 150, height: 400};
Object.assign(geom, update);
await browser.windows.update(windowId, update);
await checkWindow(geom);
return browser.windows.update(windowId, update);
}).then(() => {
return checkWindow(geom);
}).then(() => {
geom = {left: 200, top: 200, width: 800, height: 600};
await browser.windows.update(windowId, geom);
await checkWindow(geom);
return browser.windows.update(windowId, geom);
}).then(() => {
return checkWindow(geom);
}).then(() => {
return browser.runtime.getPlatformInfo();
}).then((platformInfo) => {
let platformInfo = await browser.runtime.getPlatformInfo();
if (platformInfo.os != "linux") {
geom = {left: -50, top: -50, width: 800, height: 600};
return browser.windows.update(windowId, geom).then(() => {
return checkWindow(geom);
});
await browser.windows.update(windowId, geom);
await checkWindow(geom);
}
}).then(() => {
return browser.windows.remove(windowId);
}).then(() => {
await browser.windows.remove(windowId);
browser.test.notifyPass("window-size");
}).catch(e => {
} catch (e) {
browser.test.fail(`${e} :: ${e.stack}`);
browser.test.notifyFail("window-size");
});
}
},
});

View File

@ -51,7 +51,7 @@ add_task(function* () {
add_task(function* testWindowUpdate() {
let extension = ExtensionTestUtils.loadExtension({
background() {
async background() {
let _checkWindowPromise;
browser.test.onMessage.addListener(msg => {
if (msg == "checked-window") {
@ -69,39 +69,43 @@ add_task(function* testWindowUpdate() {
}
let currentWindowId;
function updateWindow(windowId, params, expected) {
return browser.windows.update(windowId, params).then(window => {
browser.test.assertEq(currentWindowId, window.id, "Expected WINDOW_ID_CURRENT to refer to the same window");
for (let key of Object.keys(params)) {
if (key == "state" && os == "mac" && params.state == "normal") {
// OS-X doesn't have a hard distinction between "normal" and
// "maximized" states.
browser.test.assertTrue(window.state == "normal" || window.state == "maximized",
`Expected window.state (currently ${window.state}) to be "normal" but will accept "maximized"`);
} else {
browser.test.assertEq(params[key], window[key], `Got expected value for window.${key}`);
}
}
async function updateWindow(windowId, params, expected) {
let window = await browser.windows.update(windowId, params);
return checkWindow(expected);
});
browser.test.assertEq(currentWindowId, window.id, "Expected WINDOW_ID_CURRENT to refer to the same window");
for (let key of Object.keys(params)) {
if (key == "state" && os == "mac" && params.state == "normal") {
// OS-X doesn't have a hard distinction between "normal" and
// "maximized" states.
browser.test.assertTrue(window.state == "normal" || window.state == "maximized",
`Expected window.state (currently ${window.state}) to be "normal" but will accept "maximized"`);
} else {
browser.test.assertEq(params[key], window[key], `Got expected value for window.${key}`);
}
}
return checkWindow(expected);
}
let windowId = browser.windows.WINDOW_ID_CURRENT;
try {
let windowId = browser.windows.WINDOW_ID_CURRENT;
({os} = await browser.runtime.getPlatformInfo());
let window = await browser.windows.getCurrent();
currentWindowId = window.id;
await updateWindow(windowId, {state: "maximized"}, {state: "STATE_MAXIMIZED"});
await updateWindow(windowId, {state: "minimized"}, {state: "STATE_MINIMIZED"});
await updateWindow(windowId, {state: "normal"}, {state: "STATE_NORMAL"});
await updateWindow(windowId, {state: "fullscreen"}, {state: "STATE_FULLSCREEN"});
await updateWindow(windowId, {state: "normal"}, {state: "STATE_NORMAL"});
browser.runtime.getPlatformInfo().then(info => { os = info.os; })
.then(() => browser.windows.getCurrent().then(window => { currentWindowId = window.id; }))
.then(() => updateWindow(windowId, {state: "maximized"}, {state: "STATE_MAXIMIZED"}))
.then(() => updateWindow(windowId, {state: "minimized"}, {state: "STATE_MINIMIZED"}))
.then(() => updateWindow(windowId, {state: "normal"}, {state: "STATE_NORMAL"}))
.then(() => updateWindow(windowId, {state: "fullscreen"}, {state: "STATE_FULLSCREEN"}))
.then(() => updateWindow(windowId, {state: "normal"}, {state: "STATE_NORMAL"}))
.then(() => {
browser.test.notifyPass("window-update");
}).catch(e => {
} catch (e) {
browser.test.fail(`${e} :: ${e.stack}`);
browser.test.notifyFail("window-update");
});
}
},
});
@ -157,7 +161,7 @@ add_task(function* () {
// Tests that incompatible parameters can't be used together.
add_task(function* testWindowUpdateParams() {
let extension = ExtensionTestUtils.loadExtension({
background() {
async background() {
function* getCalls() {
for (let state of ["minimized", "maximized", "fullscreen"]) {
for (let param of ["left", "top", "width", "height"]) {
@ -177,12 +181,13 @@ add_task(function* testWindowUpdateParams() {
}
}
Promise.all(getCalls()).then(() => {
try {
await Promise.all(getCalls());
browser.test.notifyPass("window-update-params");
}).catch(e => {
} catch (e) {
browser.test.fail(`${e} :: ${e.stack}`);
browser.test.notifyFail("window-update-params");
});
}
},
});

View File

@ -3,6 +3,10 @@
module.exports = { // eslint-disable-line no-undef
"extends": "../../.eslintrc.js",
"parserOptions": {
"ecmaVersion": 8,
},
"globals": {
"Cc": true,
"Ci": true,
@ -32,7 +36,7 @@ module.exports = { // eslint-disable-line no-undef
"rules": {
// Rules from the mozilla plugin
"mozilla/balanced-listeners": 2,
"mozilla/no-aArgs": 1,
"mozilla/no-aArgs": 2,
"mozilla/no-cpows-in-tests": 1,
"mozilla/var-only-at-top-level": 1,
@ -80,7 +84,7 @@ module.exports = { // eslint-disable-line no-undef
"comma-style": 2,
// Don't require spaces around computed properties
"computed-property-spacing": [1, "never"],
"computed-property-spacing": [2, "never"],
// Functions are not required to consistently return something or nothing
"consistent-return": 0,

View File

@ -20,4 +20,8 @@ module.exports = { // eslint-disable-line no-undef
"webrequest_test": false,
"XPCOMUtils": true,
},
"rules": {
"no-shadow": 0,
},
};

View File

@ -64,7 +64,7 @@ add_task(function* () {
});
let addon = yield new Promise((resolve, reject) => {
AddonManager.getAddonByID(ID, aAddon => aAddon ? resolve(aAddon) : reject());
AddonManager.getAddonByID(ID, addon => addon ? resolve(addon) : reject());
});
ok(addon, `Got the addon wrapper for ${addon.id}`);

View File

@ -18,16 +18,15 @@ const BASE = "http://mochi.test:8888/chrome/toolkit/components/extensions/test/m
add_task(function* test_contentscript() {
function background() {
browser.runtime.onMessage.addListener((msg) => {
browser.runtime.onMessage.addListener(async (msg) => {
if (msg == "loaded") {
browser.tabs.query({active: true, currentWindow: true}).then((tabs) => {
// NOTE: we're removing the tab from here because doing a win.close()
// from the chrome test code is raising a "TypeError: can 't access
// dead object" exception.
browser.tabs.remove(tabs[0].id);
// NOTE: we're removing the tab from here because doing a win.close()
// from the chrome test code is raising a "TypeError: can't access
// dead object" exception.
let tabs = await browser.tabs.query({active: true, currentWindow: true});
await browser.tabs.remove(tabs[0].id);
browser.test.notifyPass("content-script-loaded");
});
browser.test.notifyPass("content-script-loaded");
}
});
}

View File

@ -15,15 +15,18 @@
add_task(function* test_downloads_saveAs() {
function background() {
const url = URL.createObjectURL(new Blob(["file content"]));
browser.test.onMessage.addListener(() =>
browser.downloads.download({url, saveAs: true})
.then(id => browser.downloads.onChanged.addListener(delta => {
browser.test.onMessage.addListener(async () => {
try {
let id = await browser.downloads.download({url, saveAs: true});
browser.downloads.onChanged.addListener(delta => {
if (delta.state.current === "complete") {
browser.test.sendMessage("done", {ok: true, id});
}
})).catch(({message}) => {
browser.test.sendMessage("done", {ok: false, message});
}));
});
} catch ({message}) {
browser.test.sendMessage("done", {ok: false, message});
}
});
browser.test.sendMessage("ready");
}

View File

@ -100,13 +100,12 @@ add_task(function* test_sdk_hybrid_addon_with_jpm_module_loader() {
});
}
function sdkMainScript() {
async function sdkMainScript() {
/* globals require */
const webext = require("sdk/webextension");
webext.startup().then(({browser}) => {
browser.runtime.onMessage.addListener((msg, sender, sendReply) => {
sendReply(`sdk received message: ${msg}`);
});
let {browser} = await webext.startup();
browser.runtime.onMessage.addListener((msg, sender, sendReply) => {
sendReply(`sdk received message: ${msg}`);
});
}

View File

@ -18,13 +18,12 @@ add_task(function* webnav_unresolved_uri_on_expected_URI_scheme() {
function background() {
let checkURLs;
browser.webNavigation.onCompleted.addListener((msg) => {
browser.webNavigation.onCompleted.addListener(async msg => {
if (checkURLs.length > 0) {
let expectedURL = checkURLs.shift();
browser.test.assertEq(expectedURL, msg.url, "Got the expected URL");
browser.tabs.remove(msg.tabId).then(() => {
browser.test.sendMessage("next");
});
await browser.tabs.remove(msg.tabId);
browser.test.sendMessage("next");
}
});

View File

@ -14,7 +14,7 @@
"use strict";
add_task(function* test_cookies() {
function background() {
async function background() {
function assertExpected(expected, cookie) {
for (let key of Object.keys(cookie)) {
browser.test.assertTrue(key in expected, `found property ${key}`);
@ -45,171 +45,175 @@ add_task(function* test_cookies() {
storeId: STORE_ID,
};
browser.cookies.set({url: TEST_URL, name: "name1", value: "value1", expirationDate: THE_FUTURE}).then(cookie => {
assertExpected(expected, cookie);
return browser.cookies.get({url: TEST_URL, name: "name1"});
}).then(cookie => {
assertExpected(expected, cookie);
return browser.cookies.getAll({name: "name1"});
}).then(cookies => {
browser.test.assertEq(cookies.length, 1, "one cookie found for matching name");
assertExpected(expected, cookies[0]);
return browser.cookies.getAll({domain: "example.org"});
}).then(cookies => {
browser.test.assertEq(cookies.length, 1, "one cookie found for matching domain");
assertExpected(expected, cookies[0]);
return browser.cookies.getAll({domain: "example.net"});
}).then(cookies => {
browser.test.assertEq(cookies.length, 0, "no cookies found for non-matching domain");
return browser.cookies.getAll({secure: false});
}).then(cookies => {
browser.test.assertEq(cookies.length, 1, "one non-secure cookie found");
assertExpected(expected, cookies[0]);
return browser.cookies.getAll({secure: true});
}).then(cookies => {
browser.test.assertEq(cookies.length, 0, "no secure cookies found");
return browser.cookies.getAll({storeId: STORE_ID});
}).then(cookies => {
browser.test.assertEq(cookies.length, 1, "one cookie found for valid storeId");
assertExpected(expected, cookies[0]);
return browser.cookies.getAll({storeId: "invalid_id"});
}).then(cookies => {
browser.test.assertEq(cookies.length, 0, "no cookies found for invalid storeId");
return browser.cookies.remove({url: TEST_URL, name: "name1"});
}).then(details => {
assertExpected({url: TEST_URL, name: "name1", storeId: STORE_ID}, details);
return browser.cookies.get({url: TEST_URL, name: "name1"});
}).then(cookie => {
browser.test.assertEq(null, cookie, "removed cookie not found");
return browser.cookies.getAllCookieStores();
}).then(stores => {
browser.test.assertEq(1, stores.length, "expected number of stores returned");
let cookie = await browser.cookies.set({url: TEST_URL, name: "name1", value: "value1", expirationDate: THE_FUTURE});
assertExpected(expected, cookie);
cookie = await browser.cookies.get({url: TEST_URL, name: "name1"});
assertExpected(expected, cookie);
let cookies = await browser.cookies.getAll({name: "name1"});
browser.test.assertEq(cookies.length, 1, "one cookie found for matching name");
assertExpected(expected, cookies[0]);
cookies = await browser.cookies.getAll({domain: "example.org"});
browser.test.assertEq(cookies.length, 1, "one cookie found for matching domain");
assertExpected(expected, cookies[0]);
cookies = await browser.cookies.getAll({domain: "example.net"});
browser.test.assertEq(cookies.length, 0, "no cookies found for non-matching domain");
cookies = await browser.cookies.getAll({secure: false});
browser.test.assertEq(cookies.length, 1, "one non-secure cookie found");
assertExpected(expected, cookies[0]);
cookies = await browser.cookies.getAll({secure: true});
browser.test.assertEq(cookies.length, 0, "no secure cookies found");
cookies = await browser.cookies.getAll({storeId: STORE_ID});
browser.test.assertEq(cookies.length, 1, "one cookie found for valid storeId");
assertExpected(expected, cookies[0]);
cookies = await browser.cookies.getAll({storeId: "invalid_id"});
browser.test.assertEq(cookies.length, 0, "no cookies found for invalid storeId");
let details = await browser.cookies.remove({url: TEST_URL, name: "name1"});
assertExpected({url: TEST_URL, name: "name1", storeId: STORE_ID}, details);
cookie = await browser.cookies.get({url: TEST_URL, name: "name1"});
browser.test.assertEq(null, cookie, "removed cookie not found");
let stores = await browser.cookies.getAllCookieStores();
browser.test.assertEq(1, stores.length, "expected number of stores returned");
browser.test.assertEq(STORE_ID, stores[0].id, "expected store id returned");
browser.test.assertEq(1, stores[0].tabIds.length, "one tab returned for store");
{
let privateWindow = await browser.windows.create({incognito: true});
let stores = await browser.cookies.getAllCookieStores();
browser.test.assertEq(2, stores.length, "expected number of stores returned");
browser.test.assertEq(STORE_ID, stores[0].id, "expected store id returned");
browser.test.assertEq(1, stores[0].tabIds.length, "one tab returned for store");
return browser.windows.create({incognito: true});
}).then(privateWindow => {
return browser.cookies.getAllCookieStores().then(stores => {
browser.test.assertEq(2, stores.length, "expected number of stores returned");
browser.test.assertEq(STORE_ID, stores[0].id, "expected store id returned");
browser.test.assertEq(1, stores[0].tabIds.length, "one tab returned for store");
browser.test.assertEq(PRIVATE_STORE_ID, stores[1].id, "expected private store id returned");
browser.test.assertEq(1, stores[0].tabIds.length, "one tab returned for private store");
return browser.windows.remove(privateWindow.id);
});
}).then(() => {
return browser.cookies.set({url: TEST_URL, name: "name2", domain: ".example.org", expirationDate: THE_FUTURE});
}).then(cookie => {
browser.test.assertEq(false, cookie.hostOnly, "cookie is not a hostOnly cookie");
return browser.cookies.remove({url: TEST_URL, name: "name2"});
}).then(details => {
assertExpected({url: TEST_URL, name: "name2", storeId: STORE_ID}, details);
// Create a session cookie.
return browser.cookies.set({url: TEST_URL, name: "name1", value: "value1"});
}).then(cookie => {
browser.test.assertEq(true, cookie.session, "session cookie set");
return browser.cookies.get({url: TEST_URL, name: "name1"});
}).then(cookie => {
browser.test.assertEq(true, cookie.session, "got session cookie");
return browser.cookies.getAll({session: true});
}).then(cookies => {
browser.test.assertEq(cookies.length, 1, "one session cookie found");
browser.test.assertEq(true, cookies[0].session, "found session cookie");
return browser.cookies.getAll({session: false});
}).then(cookies => {
browser.test.assertEq(cookies.length, 0, "no non-session cookies found");
return browser.cookies.remove({url: TEST_URL, name: "name1"});
}).then(details => {
assertExpected({url: TEST_URL, name: "name1", storeId: STORE_ID}, details);
return browser.cookies.get({url: TEST_URL, name: "name1"});
}).then(cookie => {
browser.test.assertEq(null, cookie, "removed cookie not found");
return browser.cookies.set({url: TEST_SECURE_URL, name: "name1", value: "value1", secure: true});
}).then(cookie => {
browser.test.assertEq(true, cookie.secure, "secure cookie set");
return browser.cookies.get({url: TEST_SECURE_URL, name: "name1"});
}).then(cookie => {
browser.test.assertEq(true, cookie.session, "got secure cookie");
return browser.cookies.getAll({secure: true});
}).then(cookies => {
browser.test.assertEq(cookies.length, 1, "one secure cookie found");
browser.test.assertEq(true, cookies[0].secure, "found secure cookie");
return browser.cookies.getAll({secure: false});
}).then(cookies => {
browser.test.assertEq(cookies.length, 0, "no non-secure cookies found");
return browser.cookies.remove({url: TEST_SECURE_URL, name: "name1"});
}).then(details => {
assertExpected({url: TEST_SECURE_URL, name: "name1", storeId: STORE_ID}, details);
return browser.cookies.get({url: TEST_SECURE_URL, name: "name1"});
}).then(cookie => {
browser.test.assertEq(null, cookie, "removed cookie not found");
return browser.cookies.set({url: TEST_URL_WITH_PATH, path: TEST_COOKIE_PATH, name: "name1", value: "value1", expirationDate: THE_FUTURE});
}).then(cookie => {
browser.test.assertEq(TEST_COOKIE_PATH, cookie.path, "created cookie with path");
return browser.cookies.get({url: TEST_URL_WITH_PATH, name: "name1"});
}).then(cookie => {
browser.test.assertEq(TEST_COOKIE_PATH, cookie.path, "got cookie with path");
return browser.cookies.getAll({path: TEST_COOKIE_PATH});
}).then(cookies => {
browser.test.assertEq(cookies.length, 1, "one cookie with path found");
browser.test.assertEq(TEST_COOKIE_PATH, cookies[0].path, "found cookie with path");
return browser.cookies.get({url: TEST_URL + "invalid_path", name: "name1"});
}).then(cookie => {
browser.test.assertEq(null, cookie, "get with invalid path returns null");
return browser.cookies.getAll({path: "/invalid_path"});
}).then(cookies => {
browser.test.assertEq(cookies.length, 0, "getAll with invalid path returns 0 cookies");
return browser.cookies.remove({url: TEST_URL_WITH_PATH, name: "name1"});
}).then(details => {
assertExpected({url: TEST_URL_WITH_PATH, name: "name1", storeId: STORE_ID}, details);
return browser.cookies.set({url: TEST_URL, name: "name1", value: "value1", httpOnly: true});
}).then(cookie => {
browser.test.assertEq(true, cookie.httpOnly, "httpOnly cookie set");
return browser.cookies.set({url: TEST_URL, name: "name1", value: "value1", httpOnly: false});
}).then(cookie => {
browser.test.assertEq(false, cookie.httpOnly, "non-httpOnly cookie set");
return browser.cookies.remove({url: TEST_URL, name: "name1"});
}).then(details => {
assertExpected({url: TEST_URL, name: "name1", storeId: STORE_ID}, details);
return browser.cookies.set({url: TEST_URL});
}).then(cookie => {
browser.test.assertEq("", cookie.name, "default name set");
browser.test.assertEq("", cookie.value, "default value set");
browser.test.assertEq(true, cookie.session, "no expiry date created session cookie");
return browser.windows.create({incognito: true});
}).then(privateWindow => {
browser.test.assertEq(PRIVATE_STORE_ID, stores[1].id, "expected private store id returned");
browser.test.assertEq(1, stores[0].tabIds.length, "one tab returned for private store");
await browser.windows.remove(privateWindow.id);
}
cookie = await browser.cookies.set({url: TEST_URL, name: "name2", domain: ".example.org", expirationDate: THE_FUTURE});
browser.test.assertEq(false, cookie.hostOnly, "cookie is not a hostOnly cookie");
details = await browser.cookies.remove({url: TEST_URL, name: "name2"});
assertExpected({url: TEST_URL, name: "name2", storeId: STORE_ID}, details);
// Create a session cookie.
cookie = await browser.cookies.set({url: TEST_URL, name: "name1", value: "value1"});
browser.test.assertEq(true, cookie.session, "session cookie set");
cookie = await browser.cookies.get({url: TEST_URL, name: "name1"});
browser.test.assertEq(true, cookie.session, "got session cookie");
cookies = await browser.cookies.getAll({session: true});
browser.test.assertEq(cookies.length, 1, "one session cookie found");
browser.test.assertEq(true, cookies[0].session, "found session cookie");
cookies = await browser.cookies.getAll({session: false});
browser.test.assertEq(cookies.length, 0, "no non-session cookies found");
details = await browser.cookies.remove({url: TEST_URL, name: "name1"});
assertExpected({url: TEST_URL, name: "name1", storeId: STORE_ID}, details);
cookie = await browser.cookies.get({url: TEST_URL, name: "name1"});
browser.test.assertEq(null, cookie, "removed cookie not found");
cookie = await browser.cookies.set({url: TEST_SECURE_URL, name: "name1", value: "value1", secure: true});
browser.test.assertEq(true, cookie.secure, "secure cookie set");
cookie = await browser.cookies.get({url: TEST_SECURE_URL, name: "name1"});
browser.test.assertEq(true, cookie.session, "got secure cookie");
cookies = await browser.cookies.getAll({secure: true});
browser.test.assertEq(cookies.length, 1, "one secure cookie found");
browser.test.assertEq(true, cookies[0].secure, "found secure cookie");
cookies = await browser.cookies.getAll({secure: false});
browser.test.assertEq(cookies.length, 0, "no non-secure cookies found");
details = await browser.cookies.remove({url: TEST_SECURE_URL, name: "name1"});
assertExpected({url: TEST_SECURE_URL, name: "name1", storeId: STORE_ID}, details);
cookie = await browser.cookies.get({url: TEST_SECURE_URL, name: "name1"});
browser.test.assertEq(null, cookie, "removed cookie not found");
cookie = await browser.cookies.set({url: TEST_URL_WITH_PATH, path: TEST_COOKIE_PATH, name: "name1", value: "value1", expirationDate: THE_FUTURE});
browser.test.assertEq(TEST_COOKIE_PATH, cookie.path, "created cookie with path");
cookie = await browser.cookies.get({url: TEST_URL_WITH_PATH, name: "name1"});
browser.test.assertEq(TEST_COOKIE_PATH, cookie.path, "got cookie with path");
cookies = await browser.cookies.getAll({path: TEST_COOKIE_PATH});
browser.test.assertEq(cookies.length, 1, "one cookie with path found");
browser.test.assertEq(TEST_COOKIE_PATH, cookies[0].path, "found cookie with path");
cookie = await browser.cookies.get({url: TEST_URL + "invalid_path", name: "name1"});
browser.test.assertEq(null, cookie, "get with invalid path returns null");
cookies = await browser.cookies.getAll({path: "/invalid_path"});
browser.test.assertEq(cookies.length, 0, "getAll with invalid path returns 0 cookies");
details = await browser.cookies.remove({url: TEST_URL_WITH_PATH, name: "name1"});
assertExpected({url: TEST_URL_WITH_PATH, name: "name1", storeId: STORE_ID}, details);
cookie = await browser.cookies.set({url: TEST_URL, name: "name1", value: "value1", httpOnly: true});
browser.test.assertEq(true, cookie.httpOnly, "httpOnly cookie set");
cookie = await browser.cookies.set({url: TEST_URL, name: "name1", value: "value1", httpOnly: false});
browser.test.assertEq(false, cookie.httpOnly, "non-httpOnly cookie set");
details = await browser.cookies.remove({url: TEST_URL, name: "name1"});
assertExpected({url: TEST_URL, name: "name1", storeId: STORE_ID}, details);
cookie = await browser.cookies.set({url: TEST_URL});
browser.test.assertEq("", cookie.name, "default name set");
browser.test.assertEq("", cookie.value, "default value set");
browser.test.assertEq(true, cookie.session, "no expiry date created session cookie");
{
let privateWindow = await browser.windows.create({incognito: true});
// Hacky work-around for bugzil.la/1309637
return new Promise(resolve => setTimeout(resolve, 700, privateWindow));
}).then(privateWindow => {
return browser.cookies.set({url: TEST_URL, name: "store", value: "private", expirationDate: THE_FUTURE, storeId: PRIVATE_STORE_ID}).then(cookie => {
browser.test.assertEq("private", cookie.value, "set the private cookie");
return browser.cookies.set({url: TEST_URL, name: "store", value: "default", expirationDate: THE_FUTURE, storeId: STORE_ID});
}).then(cookie => {
browser.test.assertEq("default", cookie.value, "set the default cookie");
return browser.cookies.get({url: TEST_URL, name: "store", storeId: PRIVATE_STORE_ID});
}).then(cookie => {
browser.test.assertEq("private", cookie.value, "get the private cookie");
browser.test.assertEq(PRIVATE_STORE_ID, cookie.storeId, "get the private cookie storeId");
return browser.cookies.get({url: TEST_URL, name: "store", storeId: STORE_ID});
}).then(cookie => {
browser.test.assertEq("default", cookie.value, "get the default cookie");
browser.test.assertEq(STORE_ID, cookie.storeId, "get the default cookie storeId");
return browser.cookies.remove({url: TEST_URL, name: "store", storeId: STORE_ID});
}).then(details => {
assertExpected({url: TEST_URL, name: "store", storeId: STORE_ID}, details);
return browser.cookies.get({url: TEST_URL, name: "store", storeId: STORE_ID});
}).then(cookie => {
browser.test.assertEq(null, cookie, "deleted the default cookie");
return browser.cookies.remove({url: TEST_URL, name: "store", storeId: PRIVATE_STORE_ID});
}).then(details => {
assertExpected({url: TEST_URL, name: "store", storeId: PRIVATE_STORE_ID}, details);
return browser.cookies.get({url: TEST_URL, name: "store", storeId: PRIVATE_STORE_ID});
}).then(cookie => {
browser.test.assertEq(null, cookie, "deleted the private cookie");
return browser.windows.remove(privateWindow.id);
});
}).then(() => {
browser.test.notifyPass("cookies");
});
await new Promise(resolve => setTimeout(resolve, 700));
let cookie = await browser.cookies.set({url: TEST_URL, name: "store", value: "private", expirationDate: THE_FUTURE, storeId: PRIVATE_STORE_ID});
browser.test.assertEq("private", cookie.value, "set the private cookie");
cookie = await browser.cookies.set({url: TEST_URL, name: "store", value: "default", expirationDate: THE_FUTURE, storeId: STORE_ID});
browser.test.assertEq("default", cookie.value, "set the default cookie");
cookie = await browser.cookies.get({url: TEST_URL, name: "store", storeId: PRIVATE_STORE_ID});
browser.test.assertEq("private", cookie.value, "get the private cookie");
browser.test.assertEq(PRIVATE_STORE_ID, cookie.storeId, "get the private cookie storeId");
cookie = await browser.cookies.get({url: TEST_URL, name: "store", storeId: STORE_ID});
browser.test.assertEq("default", cookie.value, "get the default cookie");
browser.test.assertEq(STORE_ID, cookie.storeId, "get the default cookie storeId");
let details = await browser.cookies.remove({url: TEST_URL, name: "store", storeId: STORE_ID});
assertExpected({url: TEST_URL, name: "store", storeId: STORE_ID}, details);
cookie = await browser.cookies.get({url: TEST_URL, name: "store", storeId: STORE_ID});
browser.test.assertEq(null, cookie, "deleted the default cookie");
details = await browser.cookies.remove({url: TEST_URL, name: "store", storeId: PRIVATE_STORE_ID});
assertExpected({url: TEST_URL, name: "store", storeId: PRIVATE_STORE_ID}, details);
cookie = await browser.cookies.get({url: TEST_URL, name: "store", storeId: PRIVATE_STORE_ID});
browser.test.assertEq(null, cookie, "deleted the private cookie");
await browser.windows.remove(privateWindow.id);
}
browser.test.notifyPass("cookies");
}
let extension = ExtensionTestUtils.loadExtension({
@ -220,10 +224,8 @@ add_task(function* test_cookies() {
});
yield extension.startup();
info("extension loaded");
yield extension.awaitFinish("cookies");
yield extension.unload();
info("extension unloaded");
});
</script>

View File

@ -22,7 +22,7 @@ add_task(function* setup() {
});
add_task(function* test_cookie_containers() {
function background() {
async function background() {
function assertExpected(expected, cookie) {
for (let key of Object.keys(cookie)) {
browser.test.assertTrue(key in expected, `found property ${key}`);
@ -47,39 +47,32 @@ add_task(function* test_cookie_containers() {
storeId: "firefox-container-1",
};
browser.cookies.set({url: TEST_URL, name: "name1", value: "value1",
expirationDate: THE_FUTURE, storeId: "firefox-container-1"})
.then(cookie => {
browser.test.assertEq("firefox-container-1", cookie.storeId, "the cookie has the correct storeId");
return browser.cookies.get({url: TEST_URL, name: "name1"});
})
.then(cookie => {
browser.test.assertEq(null, cookie, "get() without storeId returns null");
return browser.cookies.get({url: TEST_URL, name: "name1", storeId: "firefox-container-1"});
})
.then(cookie => {
assertExpected(expected, cookie);
return browser.cookies.getAll({storeId: "firefox-default"});
})
.then(cookies => {
browser.test.assertEq(0, cookies.length, "getAll() with default storeId returns an empty array");
return browser.cookies.getAll({storeId: "firefox-container-1"});
})
.then(cookies => {
browser.test.assertEq(1, cookies.length, "one cookie found for matching domain");
assertExpected(expected, cookies[0]);
return browser.cookies.remove({url: TEST_URL, name: "name1", storeId: "firefox-container-1"});
})
.then(details => {
assertExpected({url: TEST_URL, name: "name1", storeId: "firefox-container-1"}, details);
return browser.cookies.get({url: TEST_URL, name: "name1", storeId: "firefox-container-1"});
})
.then(cookie => {
browser.test.assertEq(null, cookie, "removed cookie not found");
})
.then(() => {
browser.test.notifyPass("cookies");
let cookie = await browser.cookies.set({
url: TEST_URL, name: "name1", value: "value1",
expirationDate: THE_FUTURE, storeId: "firefox-container-1",
});
browser.test.assertEq("firefox-container-1", cookie.storeId, "the cookie has the correct storeId");
cookie = await browser.cookies.get({url: TEST_URL, name: "name1"});
browser.test.assertEq(null, cookie, "get() without storeId returns null");
cookie = await browser.cookies.get({url: TEST_URL, name: "name1", storeId: "firefox-container-1"});
assertExpected(expected, cookie);
let cookies = await browser.cookies.getAll({storeId: "firefox-default"});
browser.test.assertEq(0, cookies.length, "getAll() with default storeId returns an empty array");
cookies = await browser.cookies.getAll({storeId: "firefox-container-1"});
browser.test.assertEq(1, cookies.length, "one cookie found for matching domain");
assertExpected(expected, cookies[0]);
let details = await browser.cookies.remove({url: TEST_URL, name: "name1", storeId: "firefox-container-1"});
assertExpected({url: TEST_URL, name: "name1", storeId: "firefox-container-1"}, details);
cookie = await browser.cookies.get({url: TEST_URL, name: "name1", storeId: "firefox-container-1"});
browser.test.assertEq(null, cookie, "removed cookie not found");
browser.test.notifyPass("cookies");
}
let extension = ExtensionTestUtils.loadExtension({

View File

@ -19,7 +19,7 @@ function* testCookies(options) {
// pass an expiration date to the background script.
options.expiry = Date.now() / 1000 + 3600;
function background(backgroundOptions) {
async function background(backgroundOptions) {
// Ask the parent scope to change some cookies we may or may not have
// permission for.
let awaitChanges = new Promise(resolve => {
@ -44,25 +44,25 @@ function* testCookies(options) {
failures++;
};
awaitChanges.then(() => {
return browser.cookies.get({url, name: "foo"});
}).then(cookie => {
try {
await awaitChanges;
let cookie = await browser.cookies.get({url, name: "foo"});
browser.test.assertEq(backgroundOptions.shouldPass, cookie != null, "should pass == get cookie");
return browser.cookies.getAll({domain});
}).then(cookies => {
let cookies = await browser.cookies.getAll({domain});
if (backgroundOptions.shouldPass) {
browser.test.assertEq(2, cookies.length, "expected number of cookies");
} else {
browser.test.assertEq(0, cookies.length, "expected number of cookies");
}
return Promise.all([
await Promise.all([
browser.cookies.set({url, domain, secure, name: "foo", "value": "baz", expirationDate: backgroundOptions.expiry}).catch(tallyFailure),
browser.cookies.set({url, domain, secure, name: "bar", "value": "quux", expirationDate: backgroundOptions.expiry}).catch(tallyFailure),
browser.cookies.remove({url, name: "deleted"}),
]);
}).then(() => {
if (backgroundOptions.shouldPass) {
// The order of eviction events isn't guaranteed, so just check that
// it's there somewhere.
@ -80,16 +80,17 @@ function* testCookies(options) {
browser.test.assertEq("", changed.join(","), "expected no changes");
}
browser.test.notifyPass("cookie-permissions");
}).then(() => {
if (!(backgroundOptions.shouldPass || backgroundOptions.shouldWrite)) {
browser.test.assertEq(2, failures, "Expected failures");
} else {
browser.test.assertEq(0, failures, "Expected no failures");
}
}).catch(error => {
browser.test.notifyPass("cookie-permissions");
} catch (error) {
browser.test.fail(`Error: ${error} :: ${error.stack}`);
});
browser.test.notifyFail("cookie-permissions");
}
}
let extension = ExtensionTestUtils.loadExtension({

View File

@ -183,17 +183,14 @@ add_task(function* test_get_accept_languages() {
browser.test.sendMessage("ready");
});
browser.test.onMessage.addListener(([msg, expected]) => {
Promise.all([
new Promise(
resolve => browser.tabs.sendMessage(tabId, "get-results", resolve)),
browser.i18n.getAcceptLanguages(),
]).then(([contentResults, backgroundResults]) => {
checkResults("contentScript", contentResults, expected);
checkResults("background", backgroundResults, expected);
browser.test.onMessage.addListener(async ([msg, expected]) => {
let contentResults = await browser.tabs.sendMessage(tabId, "get-results");
let backgroundResults = await browser.i18n.getAcceptLanguages();
browser.test.sendMessage("done");
});
checkResults("contentScript", contentResults, expected);
checkResults("background", backgroundResults, expected);
browser.test.sendMessage("done");
});
}
@ -357,17 +354,14 @@ add_task(function* test_detect_language() {
browser.test.sendMessage("ready");
});
browser.test.onMessage.addListener(([msg, expected]) => {
Promise.all([
browser.i18n.detectLanguage(msg),
new Promise(
resolve => browser.tabs.sendMessage(tabId, msg, resolve)),
]).then(([backgroundResults, contentResults]) => {
checkResult("background", backgroundResults, expected);
checkResult("contentScript", contentResults, expected);
browser.test.onMessage.addListener(async ([msg, expected]) => {
let backgroundResults = await browser.i18n.detectLanguage(msg);
let contentResults = await browser.tabs.sendMessage(tabId, msg);
browser.test.sendMessage("done");
});
checkResult("background", backgroundResults, expected);
checkResult("contentScript", contentResults, expected);
browser.test.sendMessage("done");
});
}

View File

@ -19,17 +19,17 @@ let image = atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAA" +
const IMAGE_ARRAYBUFFER = Uint8Array.from(image, byte => byte.charCodeAt(0)).buffer;
add_task(function* test_notification() {
function background() {
async function background() {
let opts = {
type: "basic",
title: "Testing Notification",
message: "Carry on",
};
browser.notifications.create(opts).then(id => {
browser.test.sendMessage("running", id);
browser.test.notifyPass("background test passed");
});
let id = await browser.notifications.create(opts);
browser.test.sendMessage("running", id);
browser.test.notifyPass("background test passed");
}
let extension = ExtensionTestUtils.loadExtension({
@ -46,7 +46,7 @@ add_task(function* test_notification() {
});
add_task(function* test_notification_events() {
function background() {
async function background() {
let opts = {
type: "basic",
title: "Testing Notification",
@ -66,11 +66,9 @@ add_task(function* test_notification_events() {
browser.test.notifyPass("background test passed");
});
browser.notifications.create("5", opts).then(id => {
return browser.notifications.create("5", opts);
}).then(id => {
browser.test.sendMessage("running", id);
});
await browser.notifications.create("5", opts);
let id = await browser.notifications.create("5", opts);
browser.test.sendMessage("running", id);
}
let extension = ExtensionTestUtils.loadExtension({
@ -89,7 +87,7 @@ add_task(function* test_notification_events() {
});
add_task(function* test_notification_clear() {
function background() {
async function background() {
let opts = {
type: "basic",
title: "Testing Notification",
@ -100,12 +98,12 @@ add_task(function* test_notification_clear() {
browser.test.sendMessage("closed", id);
});
browser.notifications.create("99", opts).then(id => {
return browser.notifications.clear(id);
}).then(wasCleared => {
browser.test.sendMessage("cleared", wasCleared);
browser.test.notifyPass("background test passed");
});
let id = await browser.notifications.create("99", opts);
let wasCleared = await browser.notifications.clear(id);
browser.test.sendMessage("cleared", wasCleared);
browser.test.notifyPass("background test passed");
}
let extension = ExtensionTestUtils.loadExtension({
@ -124,12 +122,12 @@ add_task(function* test_notification_clear() {
});
add_task(function* test_notifications_empty_getAll() {
function background() {
browser.notifications.getAll().then(notifications => {
browser.test.assertEq("object", typeof notifications, "getAll() returned an object");
browser.test.assertEq(0, Object.keys(notifications).length, "the object has no properties");
browser.test.notifyPass("getAll empty");
});
async function background() {
let notifications = await browser.notifications.getAll();
browser.test.assertEq("object", typeof notifications, "getAll() returned an object");
browser.test.assertEq(0, Object.keys(notifications).length, "the object has no properties");
browser.test.notifyPass("getAll empty");
}
let extension = ExtensionTestUtils.loadExtension({
@ -144,7 +142,7 @@ add_task(function* test_notifications_empty_getAll() {
});
add_task(function* test_notifications_populated_getAll() {
function background() {
async function background() {
let opts = {
type: "basic",
iconUrl: "a.png",
@ -152,24 +150,24 @@ add_task(function* test_notifications_populated_getAll() {
message: "Carry on",
};
browser.notifications.create("p1", opts).then(() => {
return browser.notifications.create("p2", opts);
}).then(() => {
return browser.notifications.getAll();
}).then(notifications => {
browser.test.assertEq("object", typeof notifications, "getAll() returned an object");
browser.test.assertEq(2, Object.keys(notifications).length, "the object has 2 properties");
for (let notificationId of ["p1", "p2"]) {
for (let key of Object.keys(opts)) {
browser.test.assertEq(
opts[key],
notifications[notificationId][key],
`the notification has the expected value for option: ${key}`
);
}
await browser.notifications.create("p1", opts);
await browser.notifications.create("p2", opts);
let notifications = await browser.notifications.getAll();
browser.test.assertEq("object", typeof notifications, "getAll() returned an object");
browser.test.assertEq(2, Object.keys(notifications).length, "the object has 2 properties");
for (let notificationId of ["p1", "p2"]) {
for (let key of Object.keys(opts)) {
browser.test.assertEq(
opts[key],
notifications[notificationId][key],
`the notification has the expected value for option: ${key}`
);
}
browser.test.notifyPass("getAll populated");
});
}
browser.test.notifyPass("getAll populated");
}
let extension = ExtensionTestUtils.loadExtension({

View File

@ -16,7 +16,7 @@
/* eslint-disable mozilla/balanced-listeners */
add_task(function* test_simple() {
function runTests(cx) {
async function runTests(cx) {
function xhr(XMLHttpRequest) {
return (url) => {
return new Promise((resolve, reject) => {
@ -47,24 +47,24 @@ add_task(function* test_simple() {
/* eslint-enable no-else-return */
}
return run(true, xhr(XMLHttpRequest))
.then(() => run(false, xhr(XMLHttpRequest)))
.then(() => run(true, xhr(window.XMLHttpRequest)))
.then(() => run(false, xhr(window.XMLHttpRequest)))
.then(() => run(true, fetch))
.then(() => run(false, fetch))
.then(() => run(true, window.fetch))
.then(() => run(false, window.fetch))
.catch(err => {
browser.test.fail(`Error: ${err} :: ${err.stack}`);
browser.test.notifyFail("permission_xhr");
});
try {
await run(true, xhr(XMLHttpRequest));
await run(false, xhr(XMLHttpRequest));
await run(true, xhr(window.XMLHttpRequest));
await run(false, xhr(window.XMLHttpRequest));
await run(true, fetch);
await run(false, fetch);
await run(true, window.fetch);
await run(false, window.fetch);
} catch (err) {
browser.test.fail(`Error: ${err} :: ${err.stack}`);
browser.test.notifyFail("permission_xhr");
}
}
function background(runTestsFn) {
runTestsFn("bg").then(() => {
browser.test.notifyPass("permission_xhr");
});
async function background(runTestsFn) {
await runTestsFn("bg");
browser.test.notifyPass("permission_xhr");
}
let extensionData = {
@ -77,29 +77,29 @@ add_task(function* test_simple() {
}],
},
files: {
"content.js": "new " + function(runTestsFn) {
runTestsFn("content").then(() => {
window.wrappedJSObject.privilegedFetch = fetch;
window.wrappedJSObject.privilegedXHR = XMLHttpRequest;
"content.js": `(${async runTestsFn => {
await runTestsFn("content");
window.addEventListener("message", function rcv({data}) {
switch (data.msg) {
case "test":
break;
window.wrappedJSObject.privilegedFetch = fetch;
window.wrappedJSObject.privilegedXHR = XMLHttpRequest;
case "assertTrue":
browser.test.assertTrue(data.condition, data.description);
break;
window.addEventListener("message", function rcv({data}) {
switch (data.msg) {
case "test":
break;
case "finish":
window.removeEventListener("message", rcv, false);
browser.test.sendMessage("content-script-finished");
break;
}
}, false);
window.postMessage("test", "*");
});
} + `(${runTests})`,
case "assertTrue":
browser.test.assertTrue(data.condition, data.description);
break;
case "finish":
window.removeEventListener("message", rcv, false);
browser.test.sendMessage("content-script-finished");
break;
}
}, false);
window.postMessage("test", "*");
}})(${runTests})`,
},
};

View File

@ -16,28 +16,27 @@
// Copied from toolkit/components/extensions/test/xpcshell/test_ext_storage.js.
// The storage API in content scripts should behave identical to the storage API
// in background pages.
function contentScript() {
async function contentScript() {
let storage = browser.storage.local;
function check(prop, value) {
return storage.get(null).then(data => {
browser.test.assertEq(value, data[prop], "null getter worked for " + prop);
return storage.get(prop);
}).then(data => {
browser.test.assertEq(value, data[prop], "string getter worked for " + prop);
return storage.get([prop]);
}).then(data => {
browser.test.assertEq(value, data[prop], "array getter worked for " + prop);
return storage.get({[prop]: undefined});
}).then(data => {
browser.test.assertEq(value, data[prop], "object getter worked for " + prop);
});
async function check(prop, value) {
let data = await storage.get(null);
browser.test.assertEq(value, data[prop], "null getter worked for " + prop);
data = await storage.get(prop);
browser.test.assertEq(value, data[prop], "string getter worked for " + prop);
data = await storage.get([prop]);
browser.test.assertEq(value, data[prop], "array getter worked for " + prop);
data = await storage.get({[prop]: undefined});
browser.test.assertEq(value, data[prop], "object getter worked for " + prop);
}
let globalChanges = {};
browser.storage.onChanged.addListener((aChanges, aStorage) => {
browser.test.assertEq("local", aStorage, "storage is local");
Object.assign(globalChanges, aChanges);
browser.storage.onChanged.addListener((changes, storage) => {
browser.test.assertEq("local", storage, "storage is local");
Object.assign(globalChanges, changes);
});
function checkChanges(changes) {
@ -56,80 +55,72 @@ function contentScript() {
/* eslint-disable dot-notation */
// Set some data and then test getters.
storage.set({"test-prop1": "value1", "test-prop2": "value2"}).then(() => {
try {
await storage.set({"test-prop1": "value1", "test-prop2": "value2"});
checkChanges({"test-prop1": {newValue: "value1"}, "test-prop2": {newValue: "value2"}});
return check("test-prop1", "value1");
}).then(() => {
return check("test-prop2", "value2");
}).then(() => {
return storage.get({"test-prop1": undefined, "test-prop2": undefined, "other": "default"});
}).then(data => {
await check("test-prop1", "value1");
await check("test-prop2", "value2");
let data = await storage.get({"test-prop1": undefined, "test-prop2": undefined, "other": "default"});
browser.test.assertEq("value1", data["test-prop1"], "prop1 correct");
browser.test.assertEq("value2", data["test-prop2"], "prop2 correct");
browser.test.assertEq("default", data["other"], "other correct");
return storage.get(["test-prop1", "test-prop2", "other"]);
}).then(data => {
data = await storage.get(["test-prop1", "test-prop2", "other"]);
browser.test.assertEq("value1", data["test-prop1"], "prop1 correct");
browser.test.assertEq("value2", data["test-prop2"], "prop2 correct");
browser.test.assertFalse("other" in data, "other correct");
// Remove data in various ways.
}).then(() => {
return storage.remove("test-prop1");
}).then(() => {
// Remove data in various ways.
await storage.remove("test-prop1");
checkChanges({"test-prop1": {oldValue: "value1"}});
return storage.get(["test-prop1", "test-prop2"]);
}).then(data => {
data = await storage.get(["test-prop1", "test-prop2"]);
browser.test.assertFalse("test-prop1" in data, "prop1 absent");
browser.test.assertTrue("test-prop2" in data, "prop2 present");
return storage.set({"test-prop1": "value1"});
}).then(() => {
await storage.set({"test-prop1": "value1"});
checkChanges({"test-prop1": {newValue: "value1"}});
return storage.get(["test-prop1", "test-prop2"]);
}).then(data => {
data = await storage.get(["test-prop1", "test-prop2"]);
browser.test.assertEq("value1", data["test-prop1"], "prop1 correct");
browser.test.assertEq("value2", data["test-prop2"], "prop2 correct");
}).then(() => {
return storage.remove(["test-prop1", "test-prop2"]);
}).then(() => {
await storage.remove(["test-prop1", "test-prop2"]);
checkChanges({"test-prop1": {oldValue: "value1"}, "test-prop2": {oldValue: "value2"}});
return storage.get(["test-prop1", "test-prop2"]);
}).then(data => {
data = await storage.get(["test-prop1", "test-prop2"]);
browser.test.assertFalse("test-prop1" in data, "prop1 absent");
browser.test.assertFalse("test-prop2" in data, "prop2 absent");
// test storage.clear
}).then(() => {
return storage.set({"test-prop1": "value1", "test-prop2": "value2"});
}).then(() => {
return storage.clear();
}).then(() => {
// test storage.clear
await storage.set({"test-prop1": "value1", "test-prop2": "value2"});
await storage.clear();
checkChanges({"test-prop1": {oldValue: "value1"}, "test-prop2": {oldValue: "value2"}});
return storage.get(["test-prop1", "test-prop2"]);
}).then(data => {
data = await storage.get(["test-prop1", "test-prop2"]);
browser.test.assertFalse("test-prop1" in data, "prop1 absent");
browser.test.assertFalse("test-prop2" in data, "prop2 absent");
// Test cache invalidation.
}).then(() => {
return storage.set({"test-prop1": "value1", "test-prop2": "value2"});
}).then(() => {
// Test cache invalidation.
await storage.set({"test-prop1": "value1", "test-prop2": "value2"});
globalChanges = {};
// Schedule sendMessage after onMessage because the other end immediately
// sends a message.
Promise.resolve().then(() => {
browser.test.sendMessage("invalidate");
});
return new Promise(resolve => browser.test.onMessage.addListener(resolve));
}).then(() => {
return check("test-prop1", "value1");
}).then(() => {
return check("test-prop2", "value2");
// Make sure we can store complex JSON data.
}).then(() => {
return storage.set({
await new Promise(resolve => browser.test.onMessage.addListener(resolve));
await check("test-prop1", "value1");
await check("test-prop2", "value2");
// Make sure we can store complex JSON data.
await storage.set({
"test-prop1": {
str: "hello",
bool: true,
@ -143,14 +134,13 @@ function contentScript() {
window,
},
});
}).then(() => {
return storage.set({"test-prop2": function func() {}});
}).then(() => {
await storage.set({"test-prop2": function func() {}});
browser.test.assertEq("value1", globalChanges["test-prop1"].oldValue, "oldValue correct");
browser.test.assertEq("object", typeof(globalChanges["test-prop1"].newValue), "newValue is obj");
globalChanges = {};
return storage.get({"test-prop1": undefined, "test-prop2": undefined});
}).then(data => {
data = await storage.get({"test-prop1": undefined, "test-prop2": undefined});
let obj = data["test-prop1"];
browser.test.assertEq("hello", obj.str, "string part correct");
@ -171,12 +161,12 @@ function contentScript() {
browser.test.assertEq("[object Object]", {}.toString.call(obj), "function serialized as a plain object");
browser.test.assertEq(0, Object.keys(obj).length, "function serialized as an empty object");
}).then(() => {
browser.test.notifyPass("storage");
}).catch(e => {
} catch (e) {
browser.test.fail(`Error: ${e} :: ${e.stack}`);
browser.test.notifyFail("storage");
});
}
}
let extensionData = {

View File

@ -14,7 +14,7 @@
"use strict";
add_task(function* test_multiple_pages() {
function background() {
async function background() {
let tabReady = new Promise(resolve => {
browser.runtime.onMessage.addListener(function listener(msg) {
browser.test.log("onMessage " + msg);
@ -37,41 +37,42 @@ add_task(function* test_multiple_pages() {
});
});
let storage = browser.storage.local;
try {
let storage = browser.storage.local;
browser.test.log("create");
browser.tabs.create({url: "tab.html"}).then(tabObj => {
tabId = tabObj.id;
browser.test.log("create");
let tab = await browser.tabs.create({url: "tab.html"});
tabId = tab.id;
return tabReady;
}).then(() => {
return storage.get("key");
}).then(result => {
await tabReady;
let result = await storage.get("key");
browser.test.assertEq(undefined, result.key, "Key should be undefined");
return browser.runtime.sendMessage("tab-set-key");
}).then(() => {
return storage.get("key");
}).then(result => {
await browser.runtime.sendMessage("tab-set-key");
result = await storage.get("key");
browser.test.assertEq(JSON.stringify({foo: {bar: "baz"}}),
JSON.stringify(result.key),
"Key should be set to the value from the tab");
}).then(() => {
browser.test.log("Remove tab");
return Promise.all([browser.tabs.remove(tabId),
tabRemoved]);
}).then(() => {
return storage.get("key");
}).then(result => {
await Promise.all([
browser.tabs.remove(tabId),
tabRemoved,
]);
result = await storage.get("key");
browser.test.assertEq(JSON.stringify({foo: {bar: "baz"}}),
JSON.stringify(result.key),
"Key should still be set to the value from the tab");
}).then(() => {
browser.test.notifyPass("storage-multiple");
}).catch(e => {
} catch (e) {
browser.test.fail(`Error: ${e} :: ${e.stack}`);
browser.test.notifyFail("storage-multiple");
});
}
}
function tab() {

View File

@ -15,38 +15,39 @@
add_task(function* test_webext_tab_subframe_privileges() {
function background() {
browser.runtime.onMessage.addListener(({msg, success, tabId, error}) => {
browser.runtime.onMessage.addListener(async ({msg, success, tabId, error}) => {
if (msg == "webext-tab-subframe-privileges") {
if (success) {
browser.tabs.remove(tabId)
.then(() => browser.test.notifyPass(msg));
await browser.tabs.remove(tabId);
browser.test.notifyPass(msg);
} else {
browser.test.log(`Got an unexpected error: ${error}`);
browser.tabs.query({active: true})
.then(tabs => browser.tabs.remove(tabs[0].id))
.then(() => browser.test.notifyFail(msg));
let tabs = await browser.tabs.query({active: true});
await browser.tabs.remove(tabs[0].id);
browser.test.notifyFail(msg);
}
}
});
browser.tabs.create({url: browser.runtime.getURL("/tab.html")});
}
function tabSubframeScript() {
async function tabSubframeScript() {
browser.test.assertTrue(browser.tabs != undefined,
"Subframe of a privileged page has access to privileged APIs");
if (browser.tabs) {
browser.tabs.getCurrent()
.then(tab => {
browser.runtime.sendMessage({
msg: "webext-tab-subframe-privileges",
success: true,
tabId: tab.id,
}, () => {
// NOTE: this empty callback prevents the promise returned from runtime.sendmessage
// to be reported as resolved after context unloaded.
});
})
.catch(e => browser.runtime.sendMessage({msg: "webext-tab-subframe-privileges", success: false, error: `${e}`}));
try {
let tab = await browser.tabs.getCurrent();
browser.runtime.sendMessage({
msg: "webext-tab-subframe-privileges",
success: true,
tabId: tab.id,
});
} catch (e) {
browser.runtime.sendMessage({msg: "webext-tab-subframe-privileges", success: false, error: `${e}`});
}
} else {
browser.runtime.sendMessage({
msg: "webext-tab-subframe-privileges",

View File

@ -23,7 +23,7 @@ let image = atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAA" +
"ACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=");
const IMAGE_ARRAYBUFFER = Uint8Array.from(image, byte => byte.charCodeAt(0)).buffer;
function testImageLoading(src, expectedAction) {
async function testImageLoading(src, expectedAction) {
let imageLoadingPromise = new Promise((resolve, reject) => {
let cleanupListeners;
let testImage = document.createElement("img");
@ -50,9 +50,8 @@ function testImageLoading(src, expectedAction) {
document.body.appendChild(testImage);
});
imageLoadingPromise.then(success => {
browser.runtime.sendMessage({name: "image-loading", expectedAction, success});
});
let success = await imageLoadingPromise;
browser.runtime.sendMessage({name: "image-loading", expectedAction, success});
}
add_task(function* test_web_accessible_resources() {
@ -77,14 +76,10 @@ add_task(function* test_web_accessible_resources() {
[browser.extension.getURL("wild2.htm"), false],
];
function runTest() {
if (!urls.length) {
browser.test.notifyPass("web-accessible-resources");
return;
}
async function runTests() {
for (let [url, shouldLoad] of urls) {
let success = await loadFrame(url);
let [url, shouldLoad] = urls.shift();
return loadFrame(url).then(success => {
browser.test.assertEq(shouldLoad, success, "Load was successful");
if (shouldLoad) {
browser.test.assertEq(url, gotURL, "Got expected url");
@ -92,15 +87,15 @@ add_task(function* test_web_accessible_resources() {
browser.test.assertEq(undefined, gotURL, "Got no url");
}
gotURL = undefined;
}
return runTest();
});
browser.test.notifyPass("web-accessible-resources");
}
browser.runtime.onMessage.addListener(([msg, url], sender) => {
if (msg == "content-script-ready") {
tabId = sender.tab.id;
runTest();
runTests();
} else if (msg == "page-script") {
browser.test.assertEq(undefined, gotURL, "Should have gotten only one message");
browser.test.assertEq("string", typeof(url), "URL should be a string");

View File

@ -35,11 +35,10 @@ add_task(function* test_alarm_fires() {
browser.alarms.create(ALARM_NAME, {delayInMinutes: 0.02});
timer = setTimeout(() => {
timer = setTimeout(async () => {
browser.test.fail("alarm fired within expected time");
browser.alarms.clear(ALARM_NAME).then(wasCleared => {
browser.test.assertTrue(wasCleared, "alarm was cleared");
});
let wasCleared = await browser.alarms.clear(ALARM_NAME);
browser.test.assertTrue(wasCleared, "alarm was cleared");
browser.test.notifyFail("alarm-fires");
}, 10000);
}
@ -70,11 +69,10 @@ add_task(function* test_alarm_fires_with_when() {
browser.alarms.create(ALARM_NAME, {when: Date.now() + 1000});
timer = setTimeout(() => {
timer = setTimeout(async () => {
browser.test.fail("alarm fired within expected time");
browser.alarms.clear(ALARM_NAME).then(wasCleared => {
browser.test.assertTrue(wasCleared, "alarm was cleared");
});
let wasCleared = await browser.alarms.clear(ALARM_NAME);
browser.test.assertTrue(wasCleared, "alarm was cleared");
browser.test.notifyFail("alarm-when");
}, 10000);
}
@ -93,18 +91,17 @@ add_task(function* test_alarm_fires_with_when() {
add_task(function* test_alarm_clear_non_matching_name() {
function backgroundScript() {
async function backgroundScript() {
let ALARM_NAME = "test_ext_alarms";
browser.alarms.create(ALARM_NAME, {when: Date.now() + 2000});
browser.alarms.clear(ALARM_NAME + "1").then(wasCleared => {
browser.test.assertFalse(wasCleared, "alarm was not cleared");
return browser.alarms.getAll();
}).then(alarms => {
browser.test.assertEq(1, alarms.length, "alarm was not removed");
browser.test.notifyPass("alarm-clear");
});
let wasCleared = await browser.alarms.clear(ALARM_NAME + "1");
browser.test.assertFalse(wasCleared, "alarm was not cleared");
let alarms = await browser.alarms.getAll();
browser.test.assertEq(1, alarms.length, "alarm was not removed");
browser.test.notifyPass("alarm-clear");
}
let extension = ExtensionTestUtils.loadExtension({
@ -121,19 +118,19 @@ add_task(function* test_alarm_clear_non_matching_name() {
add_task(function* test_alarm_get_and_clear_single_argument() {
function backgroundScript() {
async function backgroundScript() {
browser.alarms.create({when: Date.now() + 2000});
browser.alarms.get().then(alarm => {
browser.test.assertEq("", alarm.name, "expected alarm returned");
return browser.alarms.clear();
}).then(wasCleared => {
browser.test.assertTrue(wasCleared, "alarm was cleared");
return browser.alarms.getAll();
}).then(alarms => {
browser.test.assertEq(0, alarms.length, "alarm was removed");
browser.test.notifyPass("alarm-single-arg");
});
let alarm = await browser.alarms.get();
browser.test.assertEq("", alarm.name, "expected alarm returned");
let wasCleared = await browser.alarms.clear();
browser.test.assertTrue(wasCleared, "alarm was cleared");
let alarms = await browser.alarms.getAll();
browser.test.assertEq(0, alarms.length, "alarm was removed");
browser.test.notifyPass("alarm-single-arg");
}
let extension = ExtensionTestUtils.loadExtension({
@ -150,7 +147,7 @@ add_task(function* test_alarm_get_and_clear_single_argument() {
add_task(function* test_get_get_all_clear_all_alarms() {
function backgroundScript() {
async function backgroundScript() {
const ALARM_NAME = "test_alarm";
let suffixes = [0, 1, 2];
@ -159,45 +156,37 @@ add_task(function* test_get_get_all_clear_all_alarms() {
browser.alarms.create(ALARM_NAME + suffix, {when: Date.now() + (suffix + 1) * 10000});
}
browser.alarms.getAll().then(alarms => {
browser.test.assertEq(suffixes.length, alarms.length, "expected number of alarms were found");
alarms.forEach((alarm, index) => {
browser.test.assertEq(ALARM_NAME + index, alarm.name, "alarm has the expected name");
});
return Promise.all(
suffixes.map(suffix => {
return browser.alarms.get(ALARM_NAME + suffix).then(alarm => {
browser.test.assertEq(ALARM_NAME + suffix, alarm.name, "alarm has the expected name");
browser.test.sendMessage(`get-${suffix}`);
});
})
);
}).then(() => {
return browser.alarms.clear(ALARM_NAME + suffixes[0]);
}).then(wasCleared => {
browser.test.assertTrue(wasCleared, "alarm was cleared");
return browser.alarms.getAll();
}).then(alarms => {
browser.test.assertEq(2, alarms.length, "alarm was removed");
return browser.alarms.get(ALARM_NAME + suffixes[0]);
}).then(alarm => {
browser.test.assertEq(undefined, alarm, "non-existent alarm is undefined");
browser.test.sendMessage(`get-invalid`);
return browser.alarms.clearAll();
}).then(wasCleared => {
browser.test.assertTrue(wasCleared, "alarms were cleared");
return browser.alarms.getAll();
}).then(alarms => {
browser.test.assertEq(0, alarms.length, "no alarms exist");
browser.test.sendMessage("clearAll");
browser.test.sendMessage("clear");
browser.test.sendMessage("getAll");
let alarms = await browser.alarms.getAll();
browser.test.assertEq(suffixes.length, alarms.length, "expected number of alarms were found");
alarms.forEach((alarm, index) => {
browser.test.assertEq(ALARM_NAME + index, alarm.name, "alarm has the expected name");
});
for (let suffix of suffixes) {
let alarm = await browser.alarms.get(ALARM_NAME + suffix);
browser.test.assertEq(ALARM_NAME + suffix, alarm.name, "alarm has the expected name");
browser.test.sendMessage(`get-${suffix}`);
}
let wasCleared = await browser.alarms.clear(ALARM_NAME + suffixes[0]);
browser.test.assertTrue(wasCleared, "alarm was cleared");
alarms = await browser.alarms.getAll();
browser.test.assertEq(2, alarms.length, "alarm was removed");
let alarm = await browser.alarms.get(ALARM_NAME + suffixes[0]);
browser.test.assertEq(undefined, alarm, "non-existent alarm is undefined");
browser.test.sendMessage(`get-invalid`);
wasCleared = await browser.alarms.clearAll();
browser.test.assertTrue(wasCleared, "alarms were cleared");
alarms = await browser.alarms.getAll();
browser.test.assertEq(0, alarms.length, "no alarms exist");
browser.test.sendMessage("clearAll");
browser.test.sendMessage("clear");
browser.test.sendMessage("getAll");
}
let extension = ExtensionTestUtils.loadExtension({

View File

@ -3,7 +3,7 @@
"use strict";
add_task(function* test_cleared_alarm_does_not_fire() {
function backgroundScript() {
async function backgroundScript() {
let ALARM_NAME = "test_ext_alarms";
browser.alarms.onAlarm.addListener(alarm => {
@ -12,12 +12,12 @@ add_task(function* test_cleared_alarm_does_not_fire() {
});
browser.alarms.create(ALARM_NAME, {when: Date.now() + 1000});
browser.alarms.clear(ALARM_NAME).then(wasCleared => {
browser.test.assertTrue(wasCleared, "alarm was cleared");
setTimeout(() => {
browser.test.notifyPass("alarm-cleared");
}, 2000);
});
let wasCleared = await browser.alarms.clear(ALARM_NAME);
browser.test.assertTrue(wasCleared, "alarm was cleared");
await new Promise(resolve => setTimeout(resolve, 2000));
browser.test.notifyPass("alarm-cleared");
}
let extension = ExtensionTestUtils.loadExtension({

View File

@ -8,24 +8,25 @@ add_task(function* test_periodic_alarm_fires() {
let count = 0;
let timer;
browser.alarms.onAlarm.addListener(alarm => {
browser.alarms.onAlarm.addListener(async alarm => {
browser.test.assertEq(alarm.name, ALARM_NAME, "alarm has the expected name");
if (count++ === 3) {
clearTimeout(timer);
browser.alarms.clear(ALARM_NAME).then(wasCleared => {
browser.test.assertTrue(wasCleared, "alarm was cleared");
browser.test.notifyPass("alarm-periodic");
});
let wasCleared = await browser.alarms.clear(ALARM_NAME);
browser.test.assertTrue(wasCleared, "alarm was cleared");
browser.test.notifyPass("alarm-periodic");
}
});
browser.alarms.create(ALARM_NAME, {periodInMinutes: 0.02});
timer = setTimeout(() => {
timer = setTimeout(async () => {
browser.test.fail("alarm fired expected number of times");
browser.alarms.clear(ALARM_NAME).then(wasCleared => {
browser.test.assertTrue(wasCleared, "alarm was cleared");
});
let wasCleared = await browser.alarms.clear(ALARM_NAME);
browser.test.assertTrue(wasCleared, "alarm was cleared");
browser.test.notifyFail("alarm-periodic");
}, 30000);
}

View File

@ -7,22 +7,21 @@ add_task(function* test_duplicate_alarm_name_replaces_alarm() {
function backgroundScript() {
let count = 0;
browser.alarms.onAlarm.addListener(alarm => {
browser.alarms.onAlarm.addListener(async alarm => {
if (alarm.name === "master alarm") {
browser.alarms.create("child alarm", {delayInMinutes: 0.05});
browser.alarms.getAll().then(results => {
browser.test.assertEq(2, results.length, "exactly two alarms exist");
browser.test.assertEq("master alarm", results[0].name, "first alarm has the expected name");
browser.test.assertEq("child alarm", results[1].name, "second alarm has the expected name");
}).then(() => {
if (count++ === 3) {
browser.alarms.clear("master alarm").then(wasCleared => {
return browser.alarms.clear("child alarm");
}).then(wasCleared => {
browser.test.notifyPass("alarm-duplicate");
});
}
});
let results = await browser.alarms.getAll();
browser.test.assertEq(2, results.length, "exactly two alarms exist");
browser.test.assertEq("master alarm", results[0].name, "first alarm has the expected name");
browser.test.assertEq("child alarm", results[1].name, "second alarm has the expected name");
if (count++ === 3) {
await browser.alarms.clear("master alarm");
await browser.alarms.clear("child alarm");
browser.test.notifyPass("alarm-duplicate");
}
} else {
browser.test.fail("duplicate named alarm replaced existing alarm");
browser.test.notifyFail("alarm-duplicate");

View File

@ -45,7 +45,7 @@ function setup() {
function backgroundScript() {
let blobUrl;
browser.test.onMessage.addListener((msg, ...args) => {
browser.test.onMessage.addListener(async (msg, ...args) => {
if (msg == "download.request") {
let options = args[0];
@ -55,15 +55,12 @@ function backgroundScript() {
blobUrl = options.url = window.URL.createObjectURL(blob);
}
// download() throws on bad arguments, we can remove the extra
// promise when bug 1250223 is fixed.
return Promise.resolve().then(() => browser.downloads.download(options))
.then(id => {
browser.test.sendMessage("download.done", {status: "success", id});
})
.catch(error => {
browser.test.sendMessage("download.done", {status: "error", errmsg: error.message});
});
try {
let id = await browser.downloads.download(options);
browser.test.sendMessage("download.done", {status: "success", id});
} catch (error) {
browser.test.sendMessage("download.done", {status: "error", errmsg: error.message});
}
} else if (msg == "killTheBlob") {
window.URL.revokeObjectURL(blobUrl);
blobUrl = null;
@ -77,13 +74,12 @@ function backgroundScript() {
// the browser knows about and waits for all active downloads to complete.
// But we only start one at a time and only do a handful in total, so
// this lets us test download() without depending on anything else.
function waitForDownloads() {
return Downloads.getList(Downloads.ALL)
.then(list => list.getAll())
.then(downloads => {
let inprogress = downloads.filter(dl => !dl.stopped);
return Promise.all(inprogress.map(dl => dl.whenSucceeded()));
});
async function waitForDownloads() {
let list = await Downloads.getList(Downloads.ALL);
let downloads = await list.getAll();
let inprogress = downloads.filter(dl => !dl.stopped);
return Promise.all(inprogress.map(dl => dl.whenSucceeded()));
}
// Create a file in the downloads directory.
@ -115,17 +111,18 @@ add_task(function* test_downloads() {
return extension.awaitMessage("download.done");
}
function testDownload(options, localFile, expectedSize, description) {
return download(options).then(msg => {
equal(msg.status, "success", `downloads.download() works with ${description}`);
return waitForDownloads();
}).then(() => {
let localPath = downloadDir.clone();
let parts = Array.isArray(localFile) ? localFile : [localFile];
parts.map(p => localPath.append(p));
equal(localPath.fileSize, expectedSize, "Downloaded file has expected size");
localPath.remove(false);
});
async function testDownload(options, localFile, expectedSize, description) {
let msg = await download(options);
equal(msg.status, "success", `downloads.download() works with ${description}`);
await waitForDownloads();
let localPath = downloadDir.clone();
let parts = Array.isArray(localFile) ? localFile : [localFile];
parts.map(p => localPath.append(p));
equal(localPath.fileSize, expectedSize, "Downloaded file has expected size");
localPath.remove(false);
}
yield extension.startup();
@ -282,10 +279,12 @@ add_task(function* test_download_post() {
}
function background() {
browser.test.onMessage.addListener(options => {
Promise.resolve()
.then(() => browser.downloads.download(options))
.catch(err => browser.test.sendMessage("done", {err: err.message}));
browser.test.onMessage.addListener(async options => {
try {
await browser.downloads.download(options);
} catch (err) {
browser.test.sendMessage("done", {err: err.message});
}
});
browser.downloads.onChanged.addListener(({state}) => {
if (state && state.current === "complete") {

View File

@ -166,31 +166,30 @@ function backgroundScript() {
});
}
browser.test.onMessage.addListener(function(msg, ...args) {
browser.test.onMessage.addListener(async (msg, ...args) => {
let match = msg.match(/(\w+).request$/);
if (!match) {
return;
}
let what = match[1];
if (what == "waitForEvents") {
waitForEvents(...args).then(() => {
try {
await waitForEvents(...args);
browser.test.sendMessage("waitForEvents.done", {status: "success"});
}).catch(error => {
} catch (error) {
browser.test.sendMessage("waitForEvents.done", {status: "error", errmsg: error.message});
});
}
} else if (what == "clearEvents") {
events = new Set();
browser.test.sendMessage("clearEvents.done", {status: "success"});
} else {
// extension functions throw on bad arguments, we can remove the extra
// promise when bug 1250223 is fixed.
Promise.resolve().then(() => {
return browser.downloads[what](...args);
}).then(result => {
try {
let result = await browser.downloads[what](...args);
browser.test.sendMessage(`${what}.done`, {status: "success", result});
}).catch(error => {
} catch (error) {
browser.test.sendMessage(`${what}.done`, {status: "error", errmsg: error.message});
});
}
}
});
@ -200,13 +199,13 @@ function backgroundScript() {
let downloadDir;
let extension;
function clearDownloads(callback) {
return Downloads.getList(Downloads.ALL).then(list => {
return list.getAll().then(downloads => {
return Promise.all(downloads.map(download => list.remove(download)))
.then(() => downloads);
});
});
async function clearDownloads(callback) {
let list = await Downloads.getList(Downloads.ALL);
let downloads = await list.getAll();
await Promise.all(downloads.map(download => list.remove(download)));
return downloads;
}
function runInExtension(what, ...args) {
@ -218,19 +217,20 @@ function runInExtension(what, ...args) {
// download of the given url in which the total bytes are exactly equal
// to the given value. Unless you know exactly how data will arrive from
// the server (eg see interruptible.sjs), it probably isn't very useful.
function waitForProgress(url, bytes) {
return Downloads.getList(Downloads.ALL)
.then(list => new Promise(resolve => {
const view = {
onDownloadChanged(download) {
if (download.source.url == url && download.currentBytes == bytes) {
list.removeView(view);
resolve();
}
},
};
list.addView(view);
}));
async function waitForProgress(url, bytes) {
let list = await Downloads.getList(Downloads.ALL);
return new Promise(resolve => {
const view = {
onDownloadChanged(download) {
if (download.source.url == url && download.currentBytes == bytes) {
list.removeView(view);
resolve();
}
},
};
list.addView(view);
});
}
add_task(function* setup() {

View File

@ -39,42 +39,37 @@ function backgroundScript() {
}
});
browser.test.onMessage.addListener(function(msg) {
// extension functions throw on bad arguments, we can remove the extra
// promise when bug 1250223 is fixed.
browser.test.onMessage.addListener(async (msg, ...args) => {
if (msg == "download.request") {
Promise.resolve().then(() => browser.downloads.download(arguments[1]))
.then(id => {
browser.test.sendMessage("download.done", {status: "success", id});
})
.catch(error => {
browser.test.sendMessage("download.done", {status: "error", errmsg: error.message});
});
try {
let id = await browser.downloads.download(args[0]);
browser.test.sendMessage("download.done", {status: "success", id});
} catch (error) {
browser.test.sendMessage("download.done", {status: "error", errmsg: error.message});
}
} else if (msg == "search.request") {
Promise.resolve().then(() => browser.downloads.search(arguments[1]))
.then(downloads => {
browser.test.sendMessage("search.done", {status: "success", downloads});
})
.catch(error => {
browser.test.sendMessage("search.done", {status: "error", errmsg: error.message});
});
try {
let downloads = await browser.downloads.search(args[0]);
browser.test.sendMessage("search.done", {status: "success", downloads});
} catch (error) {
browser.test.sendMessage("search.done", {status: "error", errmsg: error.message});
}
} else if (msg == "waitForComplete.request") {
waitForComplete(arguments[1]).then(() => {
browser.test.sendMessage("waitForComplete.done");
});
await waitForComplete(args[0]);
browser.test.sendMessage("waitForComplete.done");
}
});
browser.test.sendMessage("ready");
}
function clearDownloads(callback) {
return Downloads.getList(Downloads.ALL).then(list => {
return list.getAll().then(downloads => {
return Promise.all(downloads.map(download => list.remove(download)))
.then(() => downloads);
});
});
async function clearDownloads(callback) {
let list = await Downloads.getList(Downloads.ALL);
let downloads = await list.getAll();
await Promise.all(downloads.map(download => list.remove(download)));
return downloads;
}
add_task(function* test_search() {
@ -92,10 +87,11 @@ add_task(function* test_search() {
Services.prefs.setIntPref("browser.download.folderList", 2);
Services.prefs.setComplexValue("browser.download.dir", nsIFile, downloadDir);
do_register_cleanup(() => {
do_register_cleanup(async () => {
Services.prefs.clearUserPref("browser.download.folderList");
Services.prefs.clearUserPref("browser.download.dir");
return cleanupDir(downloadDir).then(clearDownloads);
await cleanupDir(downloadDir);
await clearDownloads();
});
yield clearDownloads().then(downloads => {
@ -109,19 +105,18 @@ add_task(function* test_search() {
},
});
function download(options) {
async function download(options) {
extension.sendMessage("download.request", options);
return extension.awaitMessage("download.done").then(result => {
let promise;
if (result.status == "success") {
do_print(`wait for onChanged event to indicate ${result.id} is complete`);
extension.sendMessage("waitForComplete.request", result.id);
promise = extension.awaitMessage("waitForComplete.done");
} else {
promise = Promise.resolve();
}
return promise.then(() => result);
});
let result = await extension.awaitMessage("download.done");
if (result.status == "success") {
do_print(`wait for onChanged event to indicate ${result.id} is complete`);
extension.sendMessage("waitForComplete.request", result.id);
await extension.awaitMessage("waitForComplete.done");
}
return result;
}
function search(query) {

View File

@ -3,11 +3,11 @@
"use strict";
add_task(function* test_is_allowed_incognito_access() {
function background() {
browser.extension.isAllowedIncognitoAccess().then(isAllowedIncognitoAccess => {
browser.test.assertEq(true, isAllowedIncognitoAccess, "isAllowedIncognitoAccess is true");
browser.test.notifyPass("isAllowedIncognitoAccess");
});
async function background() {
let allowed = await browser.extension.isAllowedIncognitoAccess();
browser.test.assertEq(true, allowed, "isAllowedIncognitoAccess is true");
browser.test.notifyPass("isAllowedIncognitoAccess");
}
let extension = ExtensionTestUtils.loadExtension({
@ -37,11 +37,11 @@ add_task(function* test_in_incognito_context_false() {
});
add_task(function* test_is_allowed_file_scheme_access() {
function background() {
browser.extension.isAllowedFileSchemeAccess().then(isAllowedFileSchemeAccess => {
browser.test.assertEq(false, isAllowedFileSchemeAccess, "isAllowedFileSchemeAccess is false");
browser.test.notifyPass("isAllowedFileSchemeAccess");
});
async function background() {
let allowed = await browser.extension.isAllowedFileSchemeAccess();
browser.test.assertEq(false, allowed, "isAllowedFileSchemeAccess is false");
browser.test.notifyPass("isAllowedFileSchemeAccess");
}
let extension = ExtensionTestUtils.loadExtension({

View File

@ -31,13 +31,13 @@ add_task(function* test_legacy_extension_context() {
let port;
browser.test.onMessage.addListener(msg => {
browser.test.onMessage.addListener(async msg => {
if (msg == "do-send-message") {
browser.runtime.sendMessage("webextension -> legacy_extension message").then(reply => {
browser.test.assertEq("legacy_extension -> webextension reply", reply,
"Got the expected message from the LegacyExtensionContext");
browser.test.sendMessage("got-reply-message");
});
let reply = await browser.runtime.sendMessage("webextension -> legacy_extension message");
browser.test.assertEq("legacy_extension -> webextension reply", reply,
"Got the expected message from the LegacyExtensionContext");
browser.test.sendMessage("got-reply-message");
} else if (msg == "do-connect") {
port = browser.runtime.connect();

View File

@ -175,23 +175,24 @@ if (AppConstants.platform == "win") {
// Test sendNativeMessage()
add_task(function* test_sendNativeMessage() {
function background() {
async function background() {
let MSG = {test: "hello world"};
// Check error handling
browser.runtime.sendNativeMessage("nonexistent", MSG).then(() => {
await browser.runtime.sendNativeMessage("nonexistent", MSG).then(() => {
browser.test.fail("sendNativeMessage() to a nonexistent app should have failed");
}, err => {
browser.test.succeed("sendNativeMessage() to a nonexistent app failed");
}).then(() => {
// Check regular message exchange
return browser.runtime.sendNativeMessage("echo", MSG);
}).then(reply => {
let expected = JSON.stringify(MSG);
let received = JSON.stringify(reply);
browser.test.assertEq(expected, received, "Received echoed native message");
browser.test.sendMessage("finished");
});
// Check regular message exchange
let reply = await browser.runtime.sendNativeMessage("echo", MSG);
let expected = JSON.stringify(MSG);
let received = JSON.stringify(reply);
browser.test.assertEq(expected, received, "Received echoed native message");
browser.test.sendMessage("finished");
}
let extension = ExtensionTestUtils.loadExtension({

View File

@ -8,15 +8,15 @@ add_task(function* setup() {
});
add_task(function* test_getBrowserInfo() {
function background() {
browser.runtime.getBrowserInfo().then(info => {
browser.test.assertEq(info.name, "XPCShell", "name is valid");
browser.test.assertEq(info.vendor, "Mozilla", "vendor is Mozilla");
browser.test.assertEq(info.version, "48", "version is correct");
browser.test.assertEq(info.buildID, "20160315", "buildID is correct");
async function background() {
let info = await browser.runtime.getBrowserInfo();
browser.test.notifyPass("runtime.getBrowserInfo");
});
browser.test.assertEq(info.name, "XPCShell", "name is valid");
browser.test.assertEq(info.vendor, "Mozilla", "vendor is Mozilla");
browser.test.assertEq(info.version, "48", "version is correct");
browser.test.assertEq(info.buildID, "20160315", "buildID is correct");
browser.test.notifyPass("runtime.getBrowserInfo");
}
const extension = ExtensionTestUtils.loadExtension({background});

View File

@ -3,7 +3,7 @@
"use strict";
add_task(function* test_sendMessage_error() {
function background() {
async function background() {
let circ = {};
circ.circ = circ;
let testCases = [
@ -35,21 +35,18 @@ add_task(function* test_sendMessage_error() {
testCases.push([args, expectedError]);
}
function next() {
if (!testCases.length) {
browser.test.notifyPass("sendMessage parameter validation");
return;
}
let [args, expectedError] = testCases.shift();
for (let [args, expectedError] of testCases) {
let description = `runtime.sendMessage(${args.map(String).join(", ")})`;
return browser.runtime.sendMessage(...args)
await browser.runtime.sendMessage(...args)
.then(() => {
browser.test.fail(`Unexpectedly got no error for ${description}`);
}, err => {
browser.test.assertEq(expectedError, err.message, `expected error message for ${description}`);
}).then(next);
});
}
next();
browser.test.notifyPass("sendMessage parameter validation");
}
let extensionData = {
background,

View File

@ -2,21 +2,20 @@
/* vim: set sts=2 sw=2 et tw=80: */
"use strict";
function backgroundScript() {
async function backgroundScript() {
let storage = browser.storage.local;
function check(prop, value) {
return storage.get(null).then(data => {
browser.test.assertEq(value, data[prop], "null getter worked for " + prop);
return storage.get(prop);
}).then(data => {
browser.test.assertEq(value, data[prop], "string getter worked for " + prop);
return storage.get([prop]);
}).then(data => {
browser.test.assertEq(value, data[prop], "array getter worked for " + prop);
return storage.get({[prop]: undefined});
}).then(data => {
browser.test.assertEq(value, data[prop], "object getter worked for " + prop);
});
async function check(prop, value) {
let data = await storage.get(null);
browser.test.assertEq(value, data[prop], "null getter worked for " + prop);
data = await storage.get(prop);
browser.test.assertEq(value, data[prop], "string getter worked for " + prop);
data = await storage.get([prop]);
browser.test.assertEq(value, data[prop], "array getter worked for " + prop);
data = await storage.get({[prop]: undefined});
browser.test.assertEq(value, data[prop], "object getter worked for " + prop);
}
let globalChanges = {};
@ -42,80 +41,70 @@ function backgroundScript() {
/* eslint-disable dot-notation */
// Set some data and then test getters.
storage.set({"test-prop1": "value1", "test-prop2": "value2"}).then(() => {
try {
await storage.set({"test-prop1": "value1", "test-prop2": "value2"});
checkChanges({"test-prop1": {newValue: "value1"}, "test-prop2": {newValue: "value2"}});
return check("test-prop1", "value1");
}).then(() => {
return check("test-prop2", "value2");
}).then(() => {
return storage.get({"test-prop1": undefined, "test-prop2": undefined, "other": "default"});
}).then(data => {
await check("test-prop1", "value1");
await check("test-prop2", "value2");
let data = await storage.get({"test-prop1": undefined, "test-prop2": undefined, "other": "default"});
browser.test.assertEq("value1", data["test-prop1"], "prop1 correct");
browser.test.assertEq("value2", data["test-prop2"], "prop2 correct");
browser.test.assertEq("default", data["other"], "other correct");
return storage.get(["test-prop1", "test-prop2", "other"]);
}).then(data => {
data = await storage.get(["test-prop1", "test-prop2", "other"]);
browser.test.assertEq("value1", data["test-prop1"], "prop1 correct");
browser.test.assertEq("value2", data["test-prop2"], "prop2 correct");
browser.test.assertFalse("other" in data, "other correct");
// Remove data in various ways.
}).then(() => {
return storage.remove("test-prop1");
}).then(() => {
// Remove data in various ways.
await storage.remove("test-prop1");
checkChanges({"test-prop1": {oldValue: "value1"}});
return storage.get(["test-prop1", "test-prop2"]);
}).then(data => {
data = await storage.get(["test-prop1", "test-prop2"]);
browser.test.assertFalse("test-prop1" in data, "prop1 absent");
browser.test.assertTrue("test-prop2" in data, "prop2 present");
return storage.set({"test-prop1": "value1"});
}).then(() => {
await storage.set({"test-prop1": "value1"});
checkChanges({"test-prop1": {newValue: "value1"}});
return storage.get(["test-prop1", "test-prop2"]);
}).then(data => {
data = await storage.get(["test-prop1", "test-prop2"]);
browser.test.assertEq("value1", data["test-prop1"], "prop1 correct");
browser.test.assertEq("value2", data["test-prop2"], "prop2 correct");
}).then(() => {
return storage.remove(["test-prop1", "test-prop2"]);
}).then(() => {
await storage.remove(["test-prop1", "test-prop2"]);
checkChanges({"test-prop1": {oldValue: "value1"}, "test-prop2": {oldValue: "value2"}});
return storage.get(["test-prop1", "test-prop2"]);
}).then(data => {
data = await storage.get(["test-prop1", "test-prop2"]);
browser.test.assertFalse("test-prop1" in data, "prop1 absent");
browser.test.assertFalse("test-prop2" in data, "prop2 absent");
// test storage.clear
}).then(() => {
return storage.set({"test-prop1": "value1", "test-prop2": "value2"});
}).then(() => {
return storage.clear();
}).then(() => {
// test storage.clear
await storage.set({"test-prop1": "value1", "test-prop2": "value2"});
await storage.clear();
checkChanges({"test-prop1": {oldValue: "value1"}, "test-prop2": {oldValue: "value2"}});
return storage.get(["test-prop1", "test-prop2"]);
}).then(data => {
data = await storage.get(["test-prop1", "test-prop2"]);
browser.test.assertFalse("test-prop1" in data, "prop1 absent");
browser.test.assertFalse("test-prop2" in data, "prop2 absent");
// Test cache invalidation.
}).then(() => {
return storage.set({"test-prop1": "value1", "test-prop2": "value2"});
}).then(() => {
// Test cache invalidation.
await storage.set({"test-prop1": "value1", "test-prop2": "value2"});
globalChanges = {};
// Schedule sendMessage after onMessage because the other end immediately
// sends a message.
Promise.resolve().then(() => {
browser.test.sendMessage("invalidate");
});
return new Promise(resolve => browser.test.onMessage.addListener(resolve));
}).then(() => {
return check("test-prop1", "value1");
}).then(() => {
return check("test-prop2", "value2");
await new Promise(resolve => browser.test.onMessage.addListener(resolve));
// Make sure we can store complex JSON data.
}).then(() => {
return storage.set({
await check("test-prop1", "value1");
await check("test-prop2", "value2");
// Make sure we can store complex JSON data.
await storage.set({
"test-prop1": {
str: "hello",
bool: true,
@ -129,14 +118,13 @@ function backgroundScript() {
window,
},
});
}).then(() => {
return storage.set({"test-prop2": function func() {}});
}).then(() => {
await storage.set({"test-prop2": function func() {}});
browser.test.assertEq("value1", globalChanges["test-prop1"].oldValue, "oldValue correct");
browser.test.assertEq("object", typeof(globalChanges["test-prop1"].newValue), "newValue is obj");
globalChanges = {};
return storage.get({"test-prop1": undefined, "test-prop2": undefined});
}).then(data => {
data = await storage.get({"test-prop1": undefined, "test-prop2": undefined});
let obj = data["test-prop1"];
browser.test.assertEq("hello", obj.str, "string part correct");
@ -157,12 +145,12 @@ function backgroundScript() {
browser.test.assertEq("[object Object]", {}.toString.call(obj), "function serialized as a plain object");
browser.test.assertEq(0, Object.keys(obj).length, "function serialized as an empty object");
}).then(() => {
browser.test.notifyPass("storage");
}).catch(e => {
} catch (e) {
browser.test.fail(`Error: ${e} :: ${e.stack}`);
browser.test.notifyFail("storage");
});
}
}
let extensionData = {