Remove browser tests - Part 1: The Tests (except for experiments)

This commit is contained in:
NTD 2018-02-03 06:00:38 -05:00 • committed by Roy Tam
commit 261374f310
1697 changed files with 0 additions and 144364 deletions

View file

@ -1,7 +0,0 @@
"use strict";
module.exports = {
"extends": [
"../../../../../testing/mochitest/browser.eslintrc.js"
]
};

View file

@ -1,12 +0,0 @@
[DEFAULT]
support-files =
head.js
file_dom_notifications.html
[browser_notification_close.js]
[browser_notification_do_not_disturb.js]
[browser_notification_open_settings.js]
[browser_notification_remove_permission.js]
[browser_notification_permission_migration.js]
[browser_notification_replace.js]
[browser_notification_tab_switching.js]

View file

@ -1,71 +0,0 @@
"use strict";
const {PlacesTestUtils} =
Cu.import("resource://testing-common/PlacesTestUtils.jsm", {});
let notificationURL = "http://example.org/browser/browser/base/content/test/alerts/file_dom_notifications.html";
let oldShowFavicons;
add_task(function* test_notificationClose() {
let pm = Services.perms;
let notificationURI = makeURI(notificationURL);
pm.add(notificationURI, "desktop-notification", pm.ALLOW_ACTION);
oldShowFavicons = Services.prefs.getBoolPref("alerts.showFavicons");
Services.prefs.setBoolPref("alerts.showFavicons", true);
yield PlacesTestUtils.addVisits(notificationURI);
let faviconURI = yield new Promise(resolve => {
let faviconURI = makeURI("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVQI12P4//8/AAX+Av7czFnnAAAAAElFTkSuQmCC");
PlacesUtils.favicons.setAndFetchFaviconForPage(notificationURI, faviconURI,
true, PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
(faviconURI, iconSize, iconData, mimeType) => resolve(faviconURI),
Services.scriptSecurityManager.getSystemPrincipal());
});
yield BrowserTestUtils.withNewTab({
gBrowser,
url: notificationURL
}, function* dummyTabTask(aBrowser) {
yield openNotification(aBrowser, "showNotification2");
info("Notification alert showing");
let alertWindow = Services.wm.getMostRecentWindow("alert:alert");
if (!alertWindow) {
ok(true, "Notifications don't use XUL windows on all platforms.");
yield closeNotification(aBrowser);
return;
}
let alertTitleLabel = alertWindow.document.getElementById("alertTitleLabel");
is(alertTitleLabel.value, "Test title", "Title text of notification should be present");
let alertTextLabel = alertWindow.document.getElementById("alertTextLabel");
is(alertTextLabel.textContent, "Test body 2", "Body text of notification should be present");
let alertIcon = alertWindow.document.getElementById("alertIcon");
is(alertIcon.src, faviconURI.spec, "Icon of notification should be present");
let alertCloseButton = alertWindow.document.querySelector(".alertCloseButton");
is(alertCloseButton.localName, "toolbarbutton", "close button found");
let promiseBeforeUnloadEvent =
BrowserTestUtils.waitForEvent(alertWindow, "beforeunload");
let closedTime = alertWindow.Date.now();
alertCloseButton.click();
info("Clicked on close button");
yield promiseBeforeUnloadEvent;
ok(true, "Alert should close when the close button is clicked");
let currentTime = alertWindow.Date.now();
// The notification will self-close at 12 seconds, so this checks
// that the notification closed before the timeout.
ok(currentTime - closedTime < 5000,
"Close requested at " + closedTime + ", actually closed at " + currentTime);
});
});
add_task(function* cleanup() {
Services.perms.remove(makeURI(notificationURL), "desktop-notification");
if (typeof oldShowFavicons == "boolean") {
Services.prefs.setBoolPref("alerts.showFavicons", oldShowFavicons);
}
});

View file

@ -1,80 +0,0 @@
"use strict";
var tab;
var notificationURL = "http://example.org/browser/browser/base/content/test/alerts/file_dom_notifications.html";
const ALERT_SERVICE = Cc["@mozilla.org/alerts-service;1"]
.getService(Ci.nsIAlertsService)
.QueryInterface(Ci.nsIAlertsDoNotDisturb);
function test () {
waitForExplicitFinish();
try {
// Only run the test if the do-not-disturb
// interface has been implemented.
ALERT_SERVICE.manualDoNotDisturb;
ok(true, "Alert service implements do-not-disturb interface");
} catch (e) {
ok(true, "Alert service doesn't implement do-not-disturb interface, exiting test");
finish();
return;
}
let pm = Services.perms;
registerCleanupFunction(function() {
ALERT_SERVICE.manualDoNotDisturb = false;
pm.remove(makeURI(notificationURL), "desktop-notification");
gBrowser.removeTab(tab);
window.restore();
});
pm.add(makeURI(notificationURL), "desktop-notification", pm.ALLOW_ACTION);
// Make sure that do-not-disturb is not enabled.
ok(!ALERT_SERVICE.manualDoNotDisturb, "Alert service should not be disabled when test starts");
ALERT_SERVICE.manualDoNotDisturb = false;
tab = gBrowser.addTab(notificationURL);
gBrowser.selectedTab = tab;
tab.linkedBrowser.addEventListener("load", onLoad, true);
}
function onLoad() {
tab.linkedBrowser.removeEventListener("load", onLoad, true);
openNotification(tab.linkedBrowser, "showNotification2").then(onAlertShowing);
}
function onAlertShowing() {
info("Notification alert showing");
let alertWindow = Services.wm.getMostRecentWindow("alert:alert");
if (!alertWindow) {
ok(true, "Notifications don't use XUL windows on all platforms.");
closeNotification(tab.linkedBrowser).then(finish);
return;
}
let doNotDisturbMenuItem = alertWindow.document.getElementById("doNotDisturbMenuItem");
is(doNotDisturbMenuItem.localName, "menuitem", "menuitem found");
alertWindow.addEventListener("beforeunload", onAlertClosing);
doNotDisturbMenuItem.click();
info("Clicked on do-not-disturb menuitem");
}
function onAlertClosing(event) {
event.target.removeEventListener("beforeunload", onAlertClosing);
ok(ALERT_SERVICE.manualDoNotDisturb, "Alert service should be disabled after clicking menuitem");
// The notification should not appear, but there is
// no way from the client-side to know that it was
// blocked, except for waiting some time and realizing
// that the "onshow" event never fired.
openNotification(tab.linkedBrowser, "showNotification2", 2000)
.then(onAlert2Showing, finish);
}
function onAlert2Showing() {
ok(false, "the second alert should not have been shown");
closeNotification(tab.linkedBrowser).then(finish);
}

View file

@ -1,58 +0,0 @@
"use strict";
var notificationURL = "http://example.org/browser/browser/base/content/test/alerts/file_dom_notifications.html";
add_task(function* test_settingsOpen_observer() {
info("Opening a dummy tab so openPreferences=>switchToTabHavingURI doesn't use the blank tab.");
yield BrowserTestUtils.withNewTab({
gBrowser,
url: "about:robots"
}, function* dummyTabTask(aBrowser) {
let tabPromise = BrowserTestUtils.waitForNewTab(gBrowser, "about:preferences#content");
info("simulate a notifications-open-settings notification");
let uri = NetUtil.newURI("https://example.com");
let principal = Services.scriptSecurityManager.createCodebasePrincipal(uri, {});
Services.obs.notifyObservers(principal, "notifications-open-settings", null);
let tab = yield tabPromise;
ok(tab, "The notification settings tab opened");
yield BrowserTestUtils.removeTab(tab);
});
});
add_task(function* test_settingsOpen_button() {
let pm = Services.perms;
info("Adding notification permission");
pm.add(makeURI(notificationURL), "desktop-notification", pm.ALLOW_ACTION);
try {
yield BrowserTestUtils.withNewTab({
gBrowser,
url: notificationURL
}, function* tabTask(aBrowser) {
info("Waiting for notification");
yield openNotification(aBrowser, "showNotification2");
let alertWindow = Services.wm.getMostRecentWindow("alert:alert");
if (!alertWindow) {
ok(true, "Notifications don't use XUL windows on all platforms.");
yield closeNotification(aBrowser);
return;
}
let closePromise = promiseWindowClosed(alertWindow);
let tabPromise = BrowserTestUtils.waitForNewTab(gBrowser, "about:preferences#content");
let openSettingsMenuItem = alertWindow.document.getElementById("openSettingsMenuItem");
openSettingsMenuItem.click();
info("Waiting for notification settings tab");
let tab = yield tabPromise;
ok(tab, "The notification settings tab opened");
yield closePromise;
yield BrowserTestUtils.removeTab(tab);
});
} finally {
info("Removing notification permission");
pm.remove(makeURI(notificationURL), "desktop-notification");
}
});

View file

@ -1,45 +0,0 @@
const UI_VERSION = 32;
var gBrowserGlue = Cc["@mozilla.org/browser/browserglue;1"]
.getService(Ci.nsIObserver);
var notificationURI = makeURI("http://example.org");
var pm = Services.perms;
var currentUIVersion;
add_task(function* setup() {
currentUIVersion = Services.prefs.getIntPref("browser.migration.version");
Services.prefs.setIntPref("browser.migration.version", UI_VERSION - 1);
pm.add(notificationURI, "desktop-notification", pm.ALLOW_ACTION);
});
add_task(function* test_permissionMigration() {
if ("@mozilla.org/system-alerts-service;1" in Cc) {
ok(true, "Notifications don't use XUL windows on all platforms.");
return;
}
info("Waiting for migration notification");
let alertWindowPromise = promiseAlertWindow();
gBrowserGlue.observe(null, "browser-glue-test", "force-ui-migration");
let alertWindow = yield alertWindowPromise;
info("Clicking on notification");
let url =
Services.urlFormatter.formatURLPref("app.support.baseURL") +
"push#w_upgraded-notifications";
let closePromise = promiseWindowClosed(alertWindow);
let tabPromise = BrowserTestUtils.waitForNewTab(gBrowser, url);
EventUtils.synthesizeMouseAtCenter(alertWindow.document.getElementById("alertTitleLabel"), {}, alertWindow);
info("Waiting for migration info tab");
let tab = yield tabPromise;
ok(tab, "The migration info tab opened");
yield closePromise;
yield BrowserTestUtils.removeTab(tab);
});
add_task(function* cleanup() {
Services.prefs.setIntPref("browser.migration.version", currentUIVersion);
pm.remove(notificationURI, "desktop-notification");
});

View file

@ -1,72 +0,0 @@
"use strict";
var tab;
var notificationURL = "http://example.org/browser/browser/base/content/test/alerts/file_dom_notifications.html";
var alertWindowClosed = false;
var permRemoved = false;
function test () {
waitForExplicitFinish();
let pm = Services.perms;
registerCleanupFunction(function() {
pm.remove(makeURI(notificationURL), "desktop-notification");
gBrowser.removeTab(tab);
window.restore();
});
pm.add(makeURI(notificationURL), "desktop-notification", pm.ALLOW_ACTION);
tab = gBrowser.addTab(notificationURL);
gBrowser.selectedTab = tab;
tab.linkedBrowser.addEventListener("load", onLoad, true);
}
function onLoad() {
tab.linkedBrowser.removeEventListener("load", onLoad, true);
openNotification(tab.linkedBrowser, "showNotification2").then(onAlertShowing);
}
function onAlertShowing() {
info("Notification alert showing");
let alertWindow = Services.wm.getMostRecentWindow("alert:alert");
if (!alertWindow) {
ok(true, "Notifications don't use XUL windows on all platforms.");
closeNotification(tab.linkedBrowser).then(finish);
return;
}
ok(Services.perms.testExactPermission(makeURI(notificationURL), "desktop-notification"),
"Permission should exist prior to removal");
let disableForOriginMenuItem = alertWindow.document.getElementById("disableForOriginMenuItem");
is(disableForOriginMenuItem.localName, "menuitem", "menuitem found");
Services.obs.addObserver(permObserver, "perm-changed", false);
alertWindow.addEventListener("beforeunload", onAlertClosing);
disableForOriginMenuItem.click();
info("Clicked on disable-for-origin menuitem")
}
function permObserver(subject, topic, data) {
if (topic != "perm-changed") {
return;
}
let permission = subject.QueryInterface(Ci.nsIPermission);
is(permission.type, "desktop-notification", "desktop-notification permission changed");
is(data, "deleted", "desktop-notification permission deleted");
Services.obs.removeObserver(permObserver, "perm-changed");
permRemoved = true;
if (alertWindowClosed) {
finish();
}
}
function onAlertClosing(event) {
event.target.removeEventListener("beforeunload", onAlertClosing);
alertWindowClosed = true;
if (permRemoved) {
finish();
}
}

View file

@ -1,38 +0,0 @@
"use strict";
let notificationURL = "http://example.org/browser/browser/base/content/test/alerts/file_dom_notifications.html";
add_task(function* test_notificationReplace() {
let pm = Services.perms;
pm.add(makeURI(notificationURL), "desktop-notification", pm.ALLOW_ACTION);
yield BrowserTestUtils.withNewTab({
gBrowser,
url: notificationURL
}, function* dummyTabTask(aBrowser) {
yield ContentTask.spawn(aBrowser, {}, function* () {
let win = content.window.wrappedJSObject;
let notification = win.showNotification1();
let promiseCloseEvent = ContentTaskUtils.waitForEvent(notification, "close");
let showEvent = yield ContentTaskUtils.waitForEvent(notification, "show");
Assert.equal(showEvent.target.body, "Test body 1", "Showed tagged notification");
let newNotification = win.showNotification2();
let newShowEvent = yield ContentTaskUtils.waitForEvent(newNotification, "show");
Assert.equal(newShowEvent.target.body, "Test body 2", "Showed new notification with same tag");
let closeEvent = yield promiseCloseEvent;
Assert.equal(closeEvent.target.body, "Test body 1", "Closed previous tagged notification");
let promiseNewCloseEvent = ContentTaskUtils.waitForEvent(newNotification, "close");
newNotification.close();
let newCloseEvent = yield promiseNewCloseEvent;
Assert.equal(newCloseEvent.target.body, "Test body 2", "Closed new notification");
});
});
});
add_task(function* cleanup() {
Services.perms.remove(makeURI(notificationURL), "desktop-notification");
});

View file

@ -1,80 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/
*/
"use strict";
var tab;
var notification;
var notificationURL = "http://example.org/browser/browser/base/content/test/alerts/file_dom_notifications.html";
var newWindowOpenedFromTab;
add_task(function* test_notificationPreventDefaultAndSwitchTabs() {
let pm = Services.perms;
pm.add(makeURI(notificationURL), "desktop-notification", pm.ALLOW_ACTION);
let originalTab = gBrowser.selectedTab;
yield BrowserTestUtils.withNewTab({
gBrowser,
url: notificationURL
}, function* dummyTabTask(aBrowser) {
// Put new tab in background so it is obvious when it is re-focused.
yield BrowserTestUtils.switchTab(gBrowser, originalTab);
isnot(gBrowser.selectedBrowser, aBrowser, "Notification page loaded as a background tab");
// First, show a notification that will be have the tab-switching prevented.
function promiseNotificationEvent(evt) {
return ContentTask.spawn(aBrowser, evt, function* (evt) {
return yield new Promise(resolve => {
let notification = content.wrappedJSObject._notification;
notification.addEventListener(evt, function l(event) {
notification.removeEventListener(evt, l);
resolve({ defaultPrevented: event.defaultPrevented });
});
});
});
}
yield openNotification(aBrowser, "showNotification1");
info("Notification alert showing");
let alertWindow = Services.wm.getMostRecentWindow("alert:alert");
if (!alertWindow) {
ok(true, "Notifications don't use XUL windows on all platforms.");
yield closeNotification(aBrowser);
return;
}
info("Clicking on notification");
let promiseClickEvent = promiseNotificationEvent("click");
// NB: This executeSoon is needed to allow the non-e10s runs of this test
// a chance to set the event listener on the page. Otherwise, we
// synchronously fire the click event before we listen for the event.
executeSoon(() => {
EventUtils.synthesizeMouseAtCenter(alertWindow.document.getElementById("alertTitleLabel"),
{}, alertWindow);
});
let clickEvent = yield promiseClickEvent;
ok(clickEvent.defaultPrevented, "The event handler for the first notification cancels the event");
isnot(gBrowser.selectedBrowser, aBrowser, "Notification page still a background tab");
let notificationClosed = promiseNotificationEvent("close");
yield closeNotification(aBrowser);
yield notificationClosed;
// Second, show a notification that will cause the tab to get switched.
yield openNotification(aBrowser, "showNotification2");
alertWindow = Services.wm.getMostRecentWindow("alert:alert");
let promiseTabSelect = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "TabSelect");
EventUtils.synthesizeMouseAtCenter(alertWindow.document.getElementById("alertTitleLabel"),
{},
alertWindow);
yield promiseTabSelect;
is(gBrowser.selectedBrowser.currentURI.spec, notificationURL,
"Clicking on the second notification should select its originating tab");
notificationClosed = promiseNotificationEvent("close");
yield closeNotification(aBrowser);
yield notificationClosed;
});
});
add_task(function* cleanup() {
Services.perms.remove(makeURI(notificationURL), "desktop-notification");
});

View file

@ -1,39 +0,0 @@
<html>
<head>
<meta charset="utf-8">
<script>
"use strict";
function showNotification1() {
var options = {
dir: undefined,
lang: undefined,
body: "Test body 1",
tag: "Test tag",
icon: undefined,
};
var n = new Notification("Test title", options);
n.addEventListener("click", function(event) {
event.preventDefault();
});
return n;
}
function showNotification2() {
var options = {
dir: undefined,
lang: undefined,
body: "Test body 2",
tag: "Test tag",
icon: undefined,
};
return new Notification("Test title", options);
}
</script>
</head>
<body>
<form id="notificationForm" onsubmit="showNotification();">
<input type="submit" value="Show notification" id="submit"/>
</form>
</body>
</html>

View file

@ -1,71 +0,0 @@
function promiseAlertWindow() {
return new Promise(function(resolve) {
let listener = {
onOpenWindow(window) {
let alertWindow = window.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindow);
alertWindow.addEventListener("load", function onLoad() {
alertWindow.removeEventListener("load", onLoad);
let windowType = alertWindow.document.documentElement.getAttribute("windowtype");
if (windowType != "alert:alert") {
return;
}
Services.wm.removeListener(listener);
resolve(alertWindow);
});
},
};
Services.wm.addListener(listener);
});
}
/**
* Similar to `BrowserTestUtils.closeWindow`, but
* doesn't call `window.close()`.
*/
function promiseWindowClosed(window) {
return new Promise(function(resolve) {
Services.ww.registerNotification(function observer(subject, topic, data) {
if (topic == "domwindowclosed" && subject == window) {
Services.ww.unregisterNotification(observer);
resolve();
}
});
});
}
/**
* These two functions work with file_dom_notifications.html to open the
* notification and close it.
*
* |fn| can be showNotification1 or showNotification2.
* if |timeout| is passed, then the promise returned from this function is
* rejected after the requested number of miliseconds.
*/
function openNotification(aBrowser, fn, timeout) {
return ContentTask.spawn(aBrowser, { fn, timeout }, function* ({ fn, timeout }) {
let win = content.wrappedJSObject;
let notification = win[fn]();
win._notification = notification;
yield new Promise((resolve, reject) => {
function listener() {
notification.removeEventListener("show", listener);
resolve();
}
notification.addEventListener("show", listener);
if (timeout) {
content.setTimeout(() => {
notification.removeEventListener("show", listener);
reject("timed out");
}, timeout);
}
});
});
}
function closeNotification(aBrowser) {
return ContentTask.spawn(aBrowser, null, function() {
content.wrappedJSObject._notification.close();
});
}

View file

@ -1,9 +0,0 @@
[DEFAULT]
support-files =
head.js
[browser_CaptivePortalWatcher.js]
skip-if = os == "win" # Bug 1313894
[browser_CaptivePortalWatcher_1.js]
skip-if = os == "win" # Bug 1313894
[browser_captivePortal_certErrorUI.js]

View file

@ -1,119 +0,0 @@
"use strict";
add_task(setupPrefsAndRecentWindowBehavior);
// Each of the test cases below is run twice: once for login-success and once
// for login-abort (aSuccess set to true and false respectively).
let testCasesForBothSuccessAndAbort = [
/**
* A portal is detected when there's no browser window, then a browser
* window is opened, then the portal is freed.
* The portal tab should be added and focused when the window is
* opened, and closed automatically when the success event is fired.
* The captive portal notification should be shown when the window is
* opened, and closed automatically when the success event is fired.
*/
function* test_detectedWithNoBrowserWindow_Open(aSuccess) {
yield portalDetected();
let win = yield focusWindowAndWaitForPortalUI();
yield freePortal(aSuccess);
ensureNoPortalTab(win);
ensureNoPortalNotification(win);
yield closeWindowAndWaitForXulWindowVisible(win);
},
/**
* A portal is detected when multiple browser windows are open but none
* have focus. A brower window is focused, then the portal is freed.
* The portal tab should be added and focused when the window is
* focused, and closed automatically when the success event is fired.
* The captive portal notification should be shown in all windows upon
* detection, and closed automatically when the success event is fired.
*/
function* test_detectedWithNoBrowserWindow_Focused(aSuccess) {
let win1 = yield openWindowAndWaitForFocus();
let win2 = yield openWindowAndWaitForFocus();
// Defocus both windows.
yield SimpleTest.promiseFocus(window);
yield portalDetected();
// Notification should be shown in both windows.
ensurePortalNotification(win1);
ensureNoPortalTab(win1);
ensurePortalNotification(win2);
ensureNoPortalTab(win2);
yield focusWindowAndWaitForPortalUI(false, win2);
yield freePortal(aSuccess);
ensureNoPortalNotification(win1);
ensureNoPortalTab(win2);
ensureNoPortalNotification(win2);
yield closeWindowAndWaitForXulWindowVisible(win2);
// No need to wait for xul-window-visible: after win2 is closed, focus
// is restored to the default window and win1 remains in the background.
yield BrowserTestUtils.closeWindow(win1);
},
/**
* A portal is detected when there's no browser window, then a browser
* window is opened, then the portal is freed.
* The recheck triggered when the browser window is opened takes a
* long time. No portal tab should be added.
* The captive portal notification should be shown when the window is
* opened, and closed automatically when the success event is fired.
*/
function* test_detectedWithNoBrowserWindow_LongRecheck(aSuccess) {
yield portalDetected();
let win = yield focusWindowAndWaitForPortalUI(true);
yield freePortal(aSuccess);
ensureNoPortalTab(win);
ensureNoPortalNotification(win);
yield closeWindowAndWaitForXulWindowVisible(win);
},
/**
* A portal is detected when there's no browser window, and the
* portal is freed before a browser window is opened. No portal
* UI should be shown when a browser window is opened.
*/
function* test_detectedWithNoBrowserWindow_GoneBeforeOpen(aSuccess) {
yield portalDetected();
yield freePortal(aSuccess);
let win = yield openWindowAndWaitForFocus();
// Wait for a while to make sure no UI is shown.
yield new Promise(resolve => {
setTimeout(resolve, 1000);
});
ensureNoPortalTab(win);
ensureNoPortalNotification(win);
yield closeWindowAndWaitForXulWindowVisible(win);
},
/**
* A portal is detected when a browser window has focus. No portal tab should
* be opened. A notification bar should be displayed in all browser windows.
*/
function* test_detectedWithFocus(aSuccess) {
let win1 = yield openWindowAndWaitForFocus();
let win2 = yield openWindowAndWaitForFocus();
yield portalDetected();
ensureNoPortalTab(win1);
ensureNoPortalTab(win2);
ensurePortalNotification(win1);
ensurePortalNotification(win2);
yield freePortal(aSuccess);
ensureNoPortalNotification(win1);
ensureNoPortalNotification(win2);
yield closeWindowAndWaitForXulWindowVisible(win2);
yield closeWindowAndWaitForXulWindowVisible(win1);
},
];
for (let testcase of testCasesForBothSuccessAndAbort) {
add_task(testcase.bind(null, true));
add_task(testcase.bind(null, false));
}

View file

@ -1,91 +0,0 @@
"use strict";
add_task(setupPrefsAndRecentWindowBehavior);
let testcases = [
/**
* A portal is detected when there's no browser window,
* then a browser window is opened, and the portal is logged into
* and redirects to a different page. The portal tab should be added
* and focused when the window is opened, and left open after login
* since it redirected.
*/
function* test_detectedWithNoBrowserWindow_Redirect() {
yield portalDetected();
let win = yield focusWindowAndWaitForPortalUI();
let browser = win.gBrowser.selectedTab.linkedBrowser;
let loadPromise =
BrowserTestUtils.browserLoaded(browser, false, CANONICAL_URL_REDIRECTED);
BrowserTestUtils.loadURI(browser, CANONICAL_URL_REDIRECTED);
yield loadPromise;
yield freePortal(true);
ensurePortalTab(win);
ensureNoPortalNotification(win);
yield closeWindowAndWaitForXulWindowVisible(win);
},
/**
* Test the various expected behaviors of the "Show Login Page" button
* in the captive portal notification. The button should be visible for
* all tabs except the captive portal tab, and when clicked, should
* ensure a captive portal tab is open and select it.
*/
function* test_showLoginPageButton() {
let win = yield openWindowAndWaitForFocus();
yield portalDetected();
let notification = ensurePortalNotification(win);
testShowLoginPageButtonVisibility(notification, "visible");
function testPortalTabSelectedAndButtonNotVisible() {
is(win.gBrowser.selectedTab, tab, "The captive portal tab should be selected.");
testShowLoginPageButtonVisibility(notification, "hidden");
}
let button = notification.querySelector("button.notification-button");
function* clickButtonAndExpectNewPortalTab() {
let p = BrowserTestUtils.waitForNewTab(win.gBrowser, CANONICAL_URL);
button.click();
let tab = yield p;
is(win.gBrowser.selectedTab, tab, "The captive portal tab should be selected.");
return tab;
}
// Simulate clicking the button. The portal tab should be opened and
// selected and the button should hide.
let tab = yield clickButtonAndExpectNewPortalTab();
testPortalTabSelectedAndButtonNotVisible();
// Close the tab. The button should become visible.
yield BrowserTestUtils.removeTab(tab);
ensureNoPortalTab(win);
testShowLoginPageButtonVisibility(notification, "visible");
// When the button is clicked, a new portal tab should be opened and
// selected.
tab = yield clickButtonAndExpectNewPortalTab();
// Open another arbitrary tab. The button should become visible. When it's clicked,
// the portal tab should be selected.
let anotherTab = yield BrowserTestUtils.openNewForegroundTab(win.gBrowser);
testShowLoginPageButtonVisibility(notification, "visible");
button.click();
is(win.gBrowser.selectedTab, tab, "The captive portal tab should be selected.");
// Close the portal tab and select the arbitrary tab. The button should become
// visible and when it's clicked, a new portal tab should be opened.
yield BrowserTestUtils.removeTab(tab);
win.gBrowser.selectedTab = anotherTab;
testShowLoginPageButtonVisibility(notification, "visible");
tab = yield clickButtonAndExpectNewPortalTab();
yield BrowserTestUtils.removeTab(anotherTab);
yield freePortal(true);
ensureNoPortalTab(win);
ensureNoPortalNotification(win);
yield closeWindowAndWaitForXulWindowVisible(win);
},
];
for (let testcase of testcases) {
add_task(testcase);
}

View file

@ -1,82 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
const BAD_CERT_PAGE = "https://expired.example.com/";
// This tests the alternate cert error UI when we are behind a captive portal.
add_task(function* checkCaptivePortalCertErrorUI() {
yield SpecialPowers.pushPrefEnv({
set: [["captivedetect.canonicalURL", CANONICAL_URL],
["captivedetect.canonicalContent", CANONICAL_CONTENT]],
});
let captivePortalStatePropagated = TestUtils.topicObserved("ipc:network:captive-portal-set-state");
info("Checking that the alternate about:certerror UI is shown when we are behind a captive portal.");
Services.obs.notifyObservers(null, "captive-portal-login", null);
info("Waiting for captive portal state to be propagated to the content process.");
yield captivePortalStatePropagated;
// Open a page with a cert error.
let browser;
let certErrorLoaded;
let errorTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => {
let tab = gBrowser.addTab(BAD_CERT_PAGE);
gBrowser.selectedTab = tab;
browser = gBrowser.selectedBrowser;
certErrorLoaded = waitForCertErrorLoad(browser);
return tab;
}, false);
info("Waiting for cert error page to load.")
yield certErrorLoaded;
let portalTabPromise = BrowserTestUtils.waitForNewTab(gBrowser, CANONICAL_URL);
yield ContentTask.spawn(browser, null, () => {
let doc = content.document;
ok(doc.body.classList.contains("captiveportal"),
"Captive portal error page UI is visible.");
info("Clicking the Open Login Page button.");
let loginButton = doc.getElementById("openPortalLoginPageButton");
is(loginButton.getAttribute("autofocus"), "true", "openPortalLoginPageButton has autofocus");
loginButton.click();
});
let portalTab = yield portalTabPromise;
is(gBrowser.selectedTab, portalTab, "Login page should be open in a new foreground tab.");
// Make sure clicking the "Open Login Page" button again focuses the existing portal tab.
yield BrowserTestUtils.switchTab(gBrowser, errorTab);
// Passing an empty function to BrowserTestUtils.switchTab lets us wait for an arbitrary
// tab switch.
portalTabPromise = BrowserTestUtils.switchTab(gBrowser, () => {});
yield ContentTask.spawn(browser, null, () => {
info("Clicking the Open Login Page button.");
content.document.getElementById("openPortalLoginPageButton").click();
});
let portalTab2 = yield portalTabPromise;
is(portalTab2, portalTab, "The existing portal tab should be focused.");
let portalTabRemoved = BrowserTestUtils.removeTab(portalTab, {dontRemove: true});
let errorTabReloaded = waitForCertErrorLoad(browser);
Services.obs.notifyObservers(null, "captive-portal-login-success", null);
yield portalTabRemoved;
info("Waiting for error tab to be reloaded after the captive portal was freed.");
yield errorTabReloaded;
yield ContentTask.spawn(browser, null, () => {
let doc = content.document;
ok(!doc.body.classList.contains("captiveportal"),
"Captive portal error page UI is not visible.");
});
yield BrowserTestUtils.removeTab(errorTab);
});

View file

@ -1,181 +0,0 @@
Components.utils.import("resource:///modules/RecentWindow.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "CaptivePortalWatcher",
"resource:///modules/CaptivePortalWatcher.jsm");
XPCOMUtils.defineLazyServiceGetter(this, "cps",
"@mozilla.org/network/captive-portal-service;1",
"nsICaptivePortalService");
const CANONICAL_CONTENT = "success";
const CANONICAL_URL = "data:text/plain;charset=utf-8," + CANONICAL_CONTENT;
const CANONICAL_URL_REDIRECTED = "data:text/plain;charset=utf-8,redirected";
const PORTAL_NOTIFICATION_VALUE = "captive-portal-detected";
function* setupPrefsAndRecentWindowBehavior() {
yield SpecialPowers.pushPrefEnv({
set: [["captivedetect.canonicalURL", CANONICAL_URL],
["captivedetect.canonicalContent", CANONICAL_CONTENT]],
});
// We need to test behavior when a portal is detected when there is no browser
// window, but we can't close the default window opened by the test harness.
// Instead, we deactivate CaptivePortalWatcher in the default window and
// exclude it from RecentWindow.getMostRecentBrowserWindow in an attempt to
// mask its presence.
window.CaptivePortalWatcher.uninit();
let getMostRecentBrowserWindowCopy = RecentWindow.getMostRecentBrowserWindow;
let defaultWindow = window;
RecentWindow.getMostRecentBrowserWindow = () => {
let win = getMostRecentBrowserWindowCopy();
if (win == defaultWindow) {
return null;
}
return win;
};
registerCleanupFunction(function* cleanUp() {
RecentWindow.getMostRecentBrowserWindow = getMostRecentBrowserWindowCopy;
window.CaptivePortalWatcher.init();
});
}
function* portalDetected() {
Services.obs.notifyObservers(null, "captive-portal-login", null);
yield BrowserTestUtils.waitForCondition(() => {
return cps.state == cps.LOCKED_PORTAL;
}, "Waiting for Captive Portal Service to update state after portal detected.");
}
function* freePortal(aSuccess) {
Services.obs.notifyObservers(null,
"captive-portal-login-" + (aSuccess ? "success" : "abort"), null);
yield BrowserTestUtils.waitForCondition(() => {
return cps.state != cps.LOCKED_PORTAL;
}, "Waiting for Captive Portal Service to update state after portal freed.");
}
// If a window is provided, it will be focused. Otherwise, a new window
// will be opened and focused.
function* focusWindowAndWaitForPortalUI(aLongRecheck, win) {
// CaptivePortalWatcher triggers a recheck when a window gains focus. If
// the time taken for the check to complete is under PORTAL_RECHECK_DELAY_MS,
// a tab with the login page is opened and selected. If it took longer,
// no tab is opened. It's not reliable to time things in an async test,
// so use a delay threshold of -1 to simulate a long recheck (so that any
// amount of time is considered excessive), and a very large threshold to
// simulate a short recheck.
Preferences.set("captivedetect.portalRecheckDelayMS", aLongRecheck ? -1 : 1000000);
if (!win) {
win = yield BrowserTestUtils.openNewBrowserWindow();
}
yield SimpleTest.promiseFocus(win);
// After a new window is opened, CaptivePortalWatcher asks for a recheck, and
// waits for it to complete. We need to manually tell it a recheck completed.
yield BrowserTestUtils.waitForCondition(() => {
return win.CaptivePortalWatcher._waitingForRecheck;
}, "Waiting for CaptivePortalWatcher to trigger a recheck.");
Services.obs.notifyObservers(null, "captive-portal-check-complete", null);
let notification = ensurePortalNotification(win);
if (aLongRecheck) {
ensureNoPortalTab(win);
testShowLoginPageButtonVisibility(notification, "visible");
return win;
}
let tab = win.gBrowser.tabs[1];
if (tab.linkedBrowser.currentURI.spec != CANONICAL_URL) {
// The tab should load the canonical URL, wait for it.
yield BrowserTestUtils.waitForLocationChange(win.gBrowser, CANONICAL_URL);
}
is(win.gBrowser.selectedTab, tab,
"The captive portal tab should be open and selected in the new window.");
testShowLoginPageButtonVisibility(notification, "hidden");
return win;
}
function ensurePortalTab(win) {
// For the tests that call this function, it's enough to ensure there
// are two tabs in the window - the default tab and the portal tab.
is(win.gBrowser.tabs.length, 2,
"There should be a captive portal tab in the window.");
}
function ensurePortalNotification(win) {
let notificationBox =
win.document.getElementById("high-priority-global-notificationbox");
let notification = notificationBox.getNotificationWithValue(PORTAL_NOTIFICATION_VALUE)
isnot(notification, null,
"There should be a captive portal notification in the window.");
return notification;
}
// Helper to test whether the "Show Login Page" is visible in the captive portal
// notification (it should be hidden when the portal tab is selected).
function testShowLoginPageButtonVisibility(notification, visibility) {
let showLoginPageButton = notification.querySelector("button.notification-button");
// If the visibility property was never changed from default, it will be
// an empty string, so we pretend it's "visible" (effectively the same).
is(showLoginPageButton.style.visibility || "visible", visibility,
"The \"Show Login Page\" button should be " + visibility + ".");
}
function ensureNoPortalTab(win) {
is(win.gBrowser.tabs.length, 1,
"There should be no captive portal tab in the window.");
}
function ensureNoPortalNotification(win) {
let notificationBox =
win.document.getElementById("high-priority-global-notificationbox");
is(notificationBox.getNotificationWithValue(PORTAL_NOTIFICATION_VALUE), null,
"There should be no captive portal notification in the window.");
}
/**
* Some tests open a new window and close it later. When the window is closed,
* the original window opened by mochitest gains focus, generating a
* xul-window-visible notification. If the next test also opens a new window
* before this notification has a chance to fire, CaptivePortalWatcher picks
* up the first one instead of the one from the new window. To avoid this
* unfortunate intermittent timing issue, we wait for the notification from
* the original window every time we close a window that we opened.
*/
function waitForXulWindowVisible() {
return new Promise(resolve => {
Services.obs.addObserver(function observe() {
Services.obs.removeObserver(observe, "xul-window-visible");
resolve();
}, "xul-window-visible", false);
});
}
function* closeWindowAndWaitForXulWindowVisible(win) {
let p = waitForXulWindowVisible();
yield BrowserTestUtils.closeWindow(win);
yield p;
}
/**
* BrowserTestUtils.openNewBrowserWindow() does not guarantee the newly
* opened window has received focus when the promise resolves, so we
* have to manually wait every time.
*/
function* openWindowAndWaitForFocus() {
let win = yield BrowserTestUtils.openNewBrowserWindow();
yield SimpleTest.promiseFocus(win);
return win;
}
function waitForCertErrorLoad(browser) {
return new Promise(resolve => {
info("Waiting for DOMContentLoaded event");
browser.addEventListener("DOMContentLoaded", function load() {
browser.removeEventListener("DOMContentLoaded", load, false, true);
resolve();
}, false, true);
});
}

View file

@ -1,7 +0,0 @@
"use strict";
module.exports = {
"extends": [
"../../../../../testing/mochitest/chrome.eslintrc.js"
]
};

View file

@ -1,3 +0,0 @@
[DEFAULT]
[test_aboutCrashed.xul]

View file

@ -1,86 +0,0 @@
<?xml version="1.0"?>
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/javascript"
src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
<iframe type="content" id="frame1"/>
<iframe type="content" id="frame2" onload="doTest()"/>
<script type="application/javascript"><![CDATA[
const Ci = Components.interfaces;
const Cu = Components.utils;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://gre/modules/Promise.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
SimpleTest.waitForExplicitFinish();
// Load error pages do not fire "load" events, so let's use a progressListener.
function waitForErrorPage(frame) {
let errorPageDeferred = Promise.defer();
let progressListener = {
onLocationChange: function(aWebProgress, aRequest, aLocation, aFlags) {
if (aFlags & Ci.nsIWebProgressListener.LOCATION_CHANGE_ERROR_PAGE) {
frame.docShell.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebProgress)
.removeProgressListener(progressListener,
Ci.nsIWebProgress.NOTIFY_LOCATION);
errorPageDeferred.resolve();
}
},
QueryInterface: XPCOMUtils.generateQI([Ci.nsIWebProgressListener,
Ci.nsISupportsWeakReference])
};
frame.docShell.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebProgress)
.addProgressListener(progressListener,
Ci.nsIWebProgress.NOTIFY_LOCATION);
return errorPageDeferred.promise;
}
function doTest() {
Task.spawn(function test_aboutCrashed() {
let frame1 = document.getElementById("frame1");
let frame2 = document.getElementById("frame2");
let uri1 = Services.io.newURI("http://www.example.com/1", null, null);
let uri2 = Services.io.newURI("http://www.example.com/2", null, null);
let errorPageReady = waitForErrorPage(frame1);
frame1.docShell.chromeEventHandler.setAttribute("crashedPageTitle", "pageTitle");
frame1.docShell.displayLoadError(Components.results.NS_ERROR_CONTENT_CRASHED, uri1, null);
yield errorPageReady;
frame1.docShell.chromeEventHandler.removeAttribute("crashedPageTitle");
SimpleTest.is(frame1.contentDocument.documentURI,
"about:tabcrashed?e=tabcrashed&u=http%3A//www.example.com/1&c=UTF-8&f=regular&d=pageTitle",
"Correct about:tabcrashed displayed for page with title.");
errorPageReady = waitForErrorPage(frame2);
frame2.docShell.displayLoadError(Components.results.NS_ERROR_CONTENT_CRASHED, uri2, null);
yield errorPageReady;
SimpleTest.is(frame2.contentDocument.documentURI,
"about:tabcrashed?e=tabcrashed&u=http%3A//www.example.com/2&c=UTF-8&f=regular&d=%20",
"Correct about:tabcrashed displayed for page with no title.");
SimpleTest.finish();
});
}
]]></script>
<body xmlns="http://www.w3.org/1999/xhtml" style="height: 300px; overflow: auto;" />
</window>

View file

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

View file

@ -1,6 +0,0 @@
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
<ShortName>POST Search</ShortName>
<Url type="text/html" method="POST" template="http://mochi.test:8888/browser/browser/base/content/test/general/print_postdata.sjs">
<Param name="searchterms" value="{searchTerms}"/>
</Url>
</OpenSearchDescription>

View file

@ -1,6 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
addMessageListener("AboutHome:SearchTriggered", function (msg) {
sendAsyncMessage("AboutHomeTest:CheckRecordedSearch", msg.data);
});

View file

@ -1,83 +0,0 @@
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript;version=1.8">
function init() {
window.addEventListener("message", function process(e) {doTest(e)}, false);
// unless we relinquish the eventloop,
// tests will run before the chrome event handlers are ready
setTimeout(doTest, 0);
}
function checkStatusValue(payload, expectedValue) {
return payload.status == expectedValue;
}
let tests = [
{
info: "Check account log in",
event: "login",
data: {
email: "foo@example.com",
uid: "1234@lcip.org",
assertion: "foobar",
sessionToken: "dead",
kA: "beef",
kB: "cafe",
verified: true
},
payloadType: "message",
validateResponse: function(payload) {
return checkStatusValue(payload, "login");
},
},
];
let currentTest = -1;
function doTest(evt) {
if (evt) {
if (currentTest < 0 || !evt.data.content)
return; // not yet testing
let test = tests[currentTest];
if (evt.data.type != test.payloadType)
return; // skip unrequested events
let error = JSON.stringify(evt.data.content);
let pass = false;
try {
pass = test.validateResponse(evt.data.content)
} catch (e) {}
reportResult(test.info, pass, error);
}
// start the next test if there are any left
if (tests[++currentTest])
sendToBrowser(tests[currentTest].event, tests[currentTest].data);
else
reportFinished();
}
function reportResult(info, pass, error) {
let data = {type: "testResult", info: info, pass: pass, error: error};
let event = new CustomEvent("FirefoxAccountsTestResponse", {detail: {data: data}, bubbles: true});
document.dispatchEvent(event);
}
function reportFinished(cmd) {
let data = {type: "testsComplete", count: tests.length};
let event = new CustomEvent("FirefoxAccountsTestResponse", {detail: {data: data}, bubbles: true});
document.dispatchEvent(event);
}
function sendToBrowser(type, data) {
let event = new CustomEvent("FirefoxAccountsCommand", {detail: {command: type, data: data}, bubbles: true});
document.dispatchEvent(event);
}
</script>
</head>
<body onload="init()">
</body>
</html>

View file

@ -1,8 +0,0 @@
<html>
<head>
<title>Test page for bug 463387</title>
</head>
<body>
<p>Test page for bug 463387</p>
</body>
</html>

View file

@ -1,18 +0,0 @@
<!DOCTYPE HTML>
<html>
<!--
https://bugzilla.mozilla.org/show_bug.cgi?id=575561
-->
<head>
<title>Test for links in app tabs</title>
</head>
<body>
<a href="http://example.com/browser/browser/base/content/test/general/dummy_page.html">same domain</a>
<a href="http://test1.example.com/browser/browser/base/content/test/general/dummy_page.html">same domain (different subdomain)</a>
<a href="http://example.org/browser/browser/base/content/test/general/dummy_page.html">different domain</a>
<a href="http://example.org/browser/browser/base/content/test/general/dummy_page.html" target="foo">different domain (with target)</a>
<a href="http://www.example.com/browser/browser/base/content/test/general/dummy_page.html">same domain (www prefix)</a>
<a href="data:text/html,<!DOCTYPE html><html><body>Another Page</body></html>">data: URI</a>
<iframe src="app_subframe_bug575561.html"></iframe>
</body>
</html>

View file

@ -1,12 +0,0 @@
<!DOCTYPE HTML>
<html>
<!--
https://bugzilla.mozilla.org/show_bug.cgi?id=575561
-->
<head>
<title>Test for links in app tab subframes</title>
</head>
<body>
<a href="http://example.org/browser/browser/base/content/test/general/dummy_page.html">different domain</a>
</body>
</html>

View file

@ -1,12 +0,0 @@
<!DOCTYPE HTML>
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<html dir="ltr" xml:lang="en-US" lang="en-US">
<head>
<meta charset="utf8">
</head>
<body>
<iframe src="http://not-tracking.example.com/"></iframe>
</body>
</html>

View file

@ -1,494 +0,0 @@
[DEFAULT]
support-files =
POSTSearchEngine.xml
accounts_testRemoteCommands.html
alltabslistener.html
app_bug575561.html
app_subframe_bug575561.html
aboutHome_content_script.js
audio.ogg
browser_bug479408_sample.html
browser_bug678392-1.html
browser_bug678392-2.html
browser_bug970746.xhtml
browser_fxa_oauth.html
browser_fxa_oauth_with_keys.html
browser_fxa_web_channel.html
browser_registerProtocolHandler_notification.html
browser_star_hsts.sjs
browser_tab_dragdrop2_frame1.xul
browser_web_channel.html
browser_web_channel_iframe.html
bug1262648_string_with_newlines.dtd
bug592338.html
bug792517-2.html
bug792517.html
bug792517.sjs
bug839103.css
clipboard_pastefile.html
contextmenu_common.js
ctxmenu-image.png
discovery.html
download_page.html
dummy_page.html
feed_tab.html
file_generic_favicon.ico
file_with_favicon.html
file_bug822367_1.html
file_bug822367_1.js
file_bug822367_2.html
file_bug822367_3.html
file_bug822367_4.html
file_bug822367_4.js
file_bug822367_4B.html
file_bug822367_5.html
file_bug822367_6.html
file_bug902156.js
file_bug902156_1.html
file_bug902156_2.html
file_bug902156_3.html
file_bug906190_1.html
file_bug906190_2.html
file_bug906190_3_4.html
file_bug906190_redirected.html
file_bug906190.js
file_bug906190.sjs
file_mediaPlayback.html
file_mixedContentFromOnunload.html
file_mixedContentFromOnunload_test1.html
file_mixedContentFromOnunload_test2.html
file_mixedContentFramesOnHttp.html
file_mixedPassiveContent.html
file_bug970276_popup1.html
file_bug970276_popup2.html
file_bug970276_favicon1.ico
file_bug970276_favicon2.ico
file_documentnavigation_frameset.html
file_double_close_tab.html
file_favicon_change.html
file_favicon_change_not_in_document.html
file_fullscreen-window-open.html
head.js
healthreport_pingData.js
healthreport_testRemoteCommands.html
moz.png
navigating_window_with_download.html
offlineQuotaNotification.cacheManifest
offlineQuotaNotification.html
page_style_sample.html
parsingTestHelpers.jsm
pinning_headers.sjs
ssl_error_reports.sjs
print_postdata.sjs
searchSuggestionEngine.sjs
searchSuggestionEngine.xml
searchSuggestionEngine2.xml
subtst_contextmenu.html
subtst_contextmenu_input.html
subtst_contextmenu_xul.xul
test-mixedcontent-securityerrors.html
test_bug435035.html
test_bug462673.html
test_bug628179.html
test_bug839103.html
test_bug959531.html
test_process_flags_chrome.html
title_test.svg
unknownContentType_file.pif
unknownContentType_file.pif^headers^
video.ogg
web_video.html
web_video1.ogv
web_video1.ogv^headers^
zoom_test.html
test_no_mcb_on_http_site_img.html
test_no_mcb_on_http_site_img.css
test_no_mcb_on_http_site_font.html
test_no_mcb_on_http_site_font.css
test_no_mcb_on_http_site_font2.html
test_no_mcb_on_http_site_font2.css
test_mcb_redirect.html
test_mcb_redirect_image.html
test_mcb_double_redirect_image.html
test_mcb_redirect.js
test_mcb_redirect.sjs
file_bug1045809_1.html
file_bug1045809_2.html
file_csp_block_all_mixedcontent.html
file_csp_block_all_mixedcontent.js
!/image/test/mochitest/blue.png
!/toolkit/components/passwordmgr/test/browser/form_basic.html
!/toolkit/components/passwordmgr/test/browser/insecure_test.html
!/toolkit/components/passwordmgr/test/browser/insecure_test_subframe.html
!/toolkit/content/tests/browser/common/mockTransfer.js
!/toolkit/modules/tests/browser/metadata_*.html
!/toolkit/mozapps/extensions/test/xpinstall/amosigned.xpi
!/toolkit/mozapps/extensions/test/xpinstall/corrupt.xpi
!/toolkit/mozapps/extensions/test/xpinstall/incompatible.xpi
!/toolkit/mozapps/extensions/test/xpinstall/installtrigger.html
!/toolkit/mozapps/extensions/test/xpinstall/redirect.sjs
!/toolkit/mozapps/extensions/test/xpinstall/restartless-unsigned.xpi
!/toolkit/mozapps/extensions/test/xpinstall/restartless.xpi
!/toolkit/mozapps/extensions/test/xpinstall/theme.xpi
!/toolkit/mozapps/extensions/test/xpinstall/slowinstall.sjs
[browser_aboutAccounts.js]
skip-if = os == "linux" # Bug 958026
support-files =
content_aboutAccounts.js
[browser_aboutCertError.js]
[browser_aboutNetError.js]
[browser_aboutSupport_newtab_security_state.js]
[browser_aboutHealthReport.js]
skip-if = os == "linux" # Bug 924307
[browser_aboutHome.js]
[browser_aboutHome_wrapsCorrectly.js]
[browser_addKeywordSearch.js]
[browser_alltabslistener.js]
[browser_audioTabIcon.js]
tags = audiochannel
[browser_backButtonFitts.js]
skip-if = os == "mac" # The Fitt's Law back button is not supported on OS X
[browser_beforeunload_duplicate_dialogs.js]
[browser_blob-channelname.js]
[browser_bookmark_popup.js]
skip-if = (os == "linux" && debug) # mouseover not reliable on linux debug builds
[browser_bookmark_titles.js]
skip-if = toolkit == "windows" # Disabled on Windows due to frequent failures (bugs 825739, 841341)
[browser_bug321000.js]
subsuite = clipboard
skip-if = true # browser_bug321000.js is disabled because newline handling is shaky (bug 592528)
[browser_bug356571.js]
[browser_bug380960.js]
[browser_bug386835.js]
[browser_bug406216.js]
[browser_bug408415.js]
[browser_bug409481.js]
[browser_bug409624.js]
[browser_bug413915.js]
[browser_bug416661.js]
[browser_bug417483.js]
[browser_bug419612.js]
[browser_bug422590.js]
[browser_bug423833.js]
skip-if = true # bug 428712
[browser_bug424101.js]
[browser_bug427559.js]
[browser_bug431826.js]
[browser_bug432599.js]
[browser_bug435035.js]
[browser_bug435325.js]
[browser_bug441778.js]
[browser_bug455852.js]
[browser_bug460146.js]
[browser_bug462289.js]
skip-if = toolkit == "cocoa"
[browser_bug462673.js]
[browser_bug477014.js]
[browser_bug479408.js]
[browser_bug481560.js]
[browser_bug484315.js]
[browser_bug491431.js]
[browser_bug495058.js]
[browser_bug517902.js]
skip-if = (os == 'linux' && e10s) # bug 1161699
[browser_bug519216.js]
[browser_bug520538.js]
[browser_bug521216.js]
[browser_bug533232.js]
[browser_bug537013.js]
subsuite = clipboard
skip-if = e10s # Bug 1134458 - Find bar doesn't work correctly in a detached tab
[browser_bug537474.js]
[browser_bug550565.js]
[browser_bug553455.js]
[browser_bug555224.js]
[browser_bug555767.js]
[browser_bug559991.js]
[browser_bug561636.js]
skip-if = true # bug 1057615
[browser_bug563588.js]
[browser_bug565575.js]
[browser_bug567306.js]
subsuite = clipboard
[browser_bug1261299.js]
subsuite = clipboard
skip-if = toolkit != "cocoa" # Because of tests for supporting Service Menu of macOS, bug 1261299
[browser_bug1297539.js]
skip-if = toolkit != "cocoa" # Because of tests for supporting pasting from Service Menu of macOS, bug 1297539
[browser_bug575561.js]
[browser_bug575830.js]
[browser_bug577121.js]
[browser_bug578534.js]
[browser_bug579872.js]
[browser_bug580638.js]
[browser_bug580956.js]
[browser_bug581242.js]
[browser_bug581253.js]
[browser_bug585558.js]
[browser_bug585785.js]
[browser_bug585830.js]
[browser_bug590206.js]
[browser_bug592338.js]
[browser_bug594131.js]
[browser_bug595507.js]
skip-if = true # bug 1057615
[browser_bug596687.js]
[browser_bug597218.js]
[browser_bug609700.js]
[browser_bug623893.js]
[browser_bug624734.js]
[browser_bug633691.js]
[browser_bug647886.js]
[browser_bug655584.js]
[browser_bug664672.js]
[browser_bug676619.js]
skip-if = os == "mac" # mac: Intermittent failures, bug 925225
[browser_bug678392.js]
skip-if = os == "mac" # Bug 1102331 - does focus things on the content window which break in e10s mode (still causes orange on Mac 10.10)
[browser_bug710878.js]
[browser_bug719271.js]
[browser_bug724239.js]
[browser_bug734076.js]
[browser_bug735471.js]
[browser_bug749738.js]
[browser_bug763468_perwindowpb.js]
[browser_bug767836_perwindowpb.js]
[browser_bug817947.js]
[browser_bug822367.js]
tags = mcb
[browser_bug832435.js]
[browser_bug839103.js]
[browser_bug882977.js]
[browser_bug902156.js]
tags = mcb
[browser_bug906190.js]
tags = mcb
[browser_mixedContentFromOnunload.js]
tags = mcb
[browser_mixedContentFramesOnHttp.js]
tags = mcb
[browser_bug970746.js]
[browser_bug1015721.js]
skip-if = os == 'win'
[browser_bug1064280_changeUrlInPinnedTab.js]
[browser_accesskeys.js]
[browser_clipboard.js]
subsuite = clipboard
[browser_clipboard_pastefile.js]
skip-if = true # Disabled due to the clipboard not supporting real file types yet (bug 1288773)
[browser_contentAreaClick.js]
skip-if = e10s # Clicks in content don't go through contentAreaClick with e10s.
[browser_contentAltClick.js]
[browser_contextmenu.js]
subsuite = clipboard
tags = fullscreen
skip-if = toolkit == "gtk2" || toolkit == "gtk3" # disabled on Linux due to bug 513558
[browser_contextmenu_input.js]
skip-if = toolkit == "gtk2" || toolkit == "gtk3" # disabled on Linux due to bug 513558
[browser_ctrlTab.js]
[browser_datachoices_notification.js]
skip-if = !datareporting
[browser_decoderDoctor.js]
skip-if = os == "mac" # decoder doctor isn't implemented on osx
[browser_devedition.js]
[browser_discovery.js]
[browser_double_close_tab.js]
[browser_documentnavigation.js]
[browser_duplicateIDs.js]
[browser_drag.js]
skip-if = true # browser_drag.js is disabled, as it needs to be updated for the new behavior from bug 320638.
[browser_favicon_change.js]
[browser_favicon_change_not_in_document.js]
[browser_findbarClose.js]
[browser_focusonkeydown.js]
[browser_fullscreen-window-open.js]
tags = fullscreen
skip-if = os == "linux" # Linux: Intermittent failures - bug 941575.
[browser_fxaccounts.js]
support-files = fxa_profile_handler.sjs
[browser_fxa_migrate.js]
[browser_fxa_oauth.js]
[browser_fxa_web_channel.js]
[browser_gestureSupport.js]
skip-if = e10s # Bug 863514 - no gesture support.
[browser_getshortcutoruri.js]
[browser_hide_removing.js]
[browser_homeDrop.js]
[browser_identity_UI.js]
[browser_insecureLoginForms.js]
support-files = insecure_opener.html
[browser_invalid_uri_back_forward_manipulation.js]
[browser_keywordBookmarklets.js]
[browser_keywordSearch.js]
[browser_keywordSearch_postData.js]
[browser_lastAccessedTab.js]
skip-if = toolkit == "windows" # Disabled on Windows due to frequent failures (bug 969405)
[browser_menuButtonFitts.js]
skip-if = os != "win" # The Fitts Law menu button is only supported on Windows (bug 969376)
[browser_middleMouse_noJSPaste.js]
subsuite = clipboard
[browser_minimize.js]
[browser_misused_characters_in_strings.js]
[browser_mixed_content_cert_override.js]
[browser_mixedcontent_securityflags.js]
tags = mcb
[browser_modifiedclick_inherit_principal.js]
[browser_offlineQuotaNotification.js]
skip-if = os == "linux" && !debug # bug 1304273
[browser_feed_discovery.js]
support-files = feed_discovery.html
[browser_gZipOfflineChild.js]
support-files = test_offline_gzip.html gZipOfflineChild.cacheManifest gZipOfflineChild.cacheManifest^headers^ gZipOfflineChild.html gZipOfflineChild.html^headers^
[browser_overflowScroll.js]
[browser_pageInfo.js]
[browser_pageinfo_svg_image.js]
support-files =
svg_image.html
[browser_page_style_menu.js]
[browser_page_style_menu_update.js]
[browser_parsable_css.js]
skip-if = (debug || asan) # no point in running on both opt and debug, and will likely intermittently timeout on debug
[browser_parsable_script.js]
skip-if = asan || (os == 'linux' && !debug && (bits == 32)) # disabled on asan because of timeouts, and bug 1172468 for the linux 32-bit pgo issue.
[browser_permissions.js]
support-files =
permissions.html
[browser_pinnedTabs.js]
[browser_plainTextLinks.js]
[browser_printpreview.js]
[browser_private_browsing_window.js]
[browser_private_no_prompt.js]
[browser_purgehistory_clears_sh.js]
[browser_PageMetaData_pushstate.js]
[browser_refreshBlocker.js]
support-files =
refresh_header.sjs
refresh_meta.sjs
[browser_relatedTabs.js]
[browser_remoteTroubleshoot.js]
support-files =
test_remoteTroubleshoot.html
[browser_remoteWebNavigation_postdata.js]
[browser_removeTabsToTheEnd.js]
[browser_restore_isAppTab.js]
[browser_sanitize-passwordDisabledHosts.js]
[browser_sanitize-sitepermissions.js]
[browser_sanitize-timespans.js]
[browser_sanitizeDialog.js]
[browser_save_link-perwindowpb.js]
skip-if = e10s && debug && os == "win" # Bug 1280505
[browser_save_private_link_perwindowpb.js]
[browser_save_link_when_window_navigates.js]
[browser_save_video.js]
[browser_save_video_frame.js]
[browser_scope.js]
[browser_contentSearchUI.js]
support-files =
contentSearchUI.html
contentSearchUI.js
[browser_selectpopup.js]
run-if = e10s
[browser_selectTabAtIndex.js]
[browser_ssl_error_reports.js]
[browser_star_hsts.js]
[browser_subframe_favicons_not_used.js]
[browser_syncui.js]
[browser_tab_close_dependent_window.js]
[browser_tabDrop.js]
[browser_tabReorder.js]
[browser_tab_detach_restore.js]
[browser_tab_drag_drop_perwindow.js]
[browser_tab_dragdrop.js]
skip-if = buildapp == 'mulet' || (e10s && (debug || os == 'linux')) # Bug 1312436
[browser_tab_dragdrop2.js]
[browser_tabbar_big_widgets.js]
skip-if = os == "linux" || os == "mac" # No tabs in titlebar on linux
# Disabled on OS X because of bug 967917
[browser_tabfocus.js]
[browser_tabkeynavigation.js]
skip-if = (os == "mac" && !e10s) # Bug 1237713 - OSX eats keypresses for some reason
[browser_tabopen_reflows.js]
[browser_tabs_close_beforeunload.js]
support-files =
close_beforeunload_opens_second_tab.html
close_beforeunload.html
[browser_tabs_isActive.js]
[browser_tabs_owner.js]
[browser_testOpenNewRemoteTabsFromNonRemoteBrowsers.js]
run-if = e10s
[browser_trackingUI_1.js]
tags = trackingprotection
support-files =
trackingPage.html
benignPage.html
[browser_trackingUI_2.js]
tags = trackingprotection
support-files =
trackingPage.html
benignPage.html
[browser_trackingUI_3.js]
tags = trackingprotection
[browser_trackingUI_4.js]
tags = trackingprotection
support-files =
trackingPage.html
benignPage.html
[browser_trackingUI_5.js]
tags = trackingprotection
support-files =
trackingPage.html
[browser_trackingUI_6.js]
tags = trackingprotection
support-files =
file_trackingUI_6.html
file_trackingUI_6.js
file_trackingUI_6.js^headers^
[browser_trackingUI_telemetry.js]
tags = trackingprotection
support-files =
trackingPage.html
[browser_typeAheadFind.js]
[browser_unknownContentType_title.js]
[browser_unloaddialogs.js]
[browser_utilityOverlay.js]
[browser_viewSourceInTabOnViewSource.js]
[browser_visibleFindSelection.js]
[browser_visibleTabs.js]
[browser_visibleTabs_bookmarkAllPages.js]
skip-if = true # Bug 1005420 - fails intermittently. also with e10s enabled: bizarre problem with hidden tab having _mouseenter called, via _setPositionalAttributes, and tab not being found resulting in 'candidate is undefined'
[browser_visibleTabs_bookmarkAllTabs.js]
[browser_visibleTabs_contextMenu.js]
[browser_visibleTabs_tabPreview.js]
skip-if = (os == "win" && !debug)
[browser_web_channel.js]
[browser_windowopen_reflows.js]
[browser_zbug569342.js]
skip-if = e10s || debug # Bug 1094240 - has findbar-related failures
[browser_registerProtocolHandler_notification.js]
[browser_no_mcb_on_http_site.js]
tags = mcb
[browser_addCertException.js]
[browser_bug1045809.js]
tags = mcb
[browser_e10s_switchbrowser.js]
[browser_e10s_about_process.js]
[browser_e10s_chrome_process.js]
[browser_e10s_javascript.js]
[browser_blockHPKP.js]
tags = psm
[browser_mcb_redirect.js]
tags = mcb
[browser_windowactivation.js]
[browser_contextmenu_childprocess.js]
[browser_bug963945.js]
[browser_domFullscreen_fullscreenMode.js]
tags = fullscreen
[browser_menuButtonBadgeManager.js]
[browser_newTabDrop.js]
[browser_newWindowDrop.js]
[browser_csp_block_all_mixedcontent.js]
tags = mcb
[browser_newwindow_focus.js]
skip-if = (os == "linux" && !e10s) # Bug 1263254 - Perma fails on Linux without e10s for some reason.
[browser_bug1299667.js]

View file

@ -1,29 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/
*/
add_task(function* () {
let rooturi = "https://example.com/browser/toolkit/modules/tests/browser/";
yield BrowserTestUtils.openNewForegroundTab(gBrowser, rooturi + "metadata_simple.html");
yield ContentTask.spawn(gBrowser.selectedBrowser, { rooturi }, function* (args) {
let result = PageMetadata.getData(content.document);
// Result should have description.
Assert.equal(result.url, args.rooturi + "metadata_simple.html", "metadata url is correct");
Assert.equal(result.title, "Test Title", "metadata title is correct");
Assert.equal(result.description, "A very simple test page", "description is correct");
content.history.pushState({}, "2", "2.html");
result = PageMetadata.getData(content.document);
// Result should not have description.
Assert.equal(result.url, args.rooturi + "2.html", "metadata url is correct");
Assert.equal(result.title, "Test Title", "metadata title is correct");
Assert.ok(!result.description, "description is undefined");
Assert.equal(content.document.documentURI, args.rooturi + "2.html",
"content.document has correct url");
});
is(gBrowser.currentURI.spec, rooturi + "2.html", "gBrowser has correct url");
gBrowser.removeTab(gBrowser.selectedTab);
});

View file

@ -1,499 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/
*/
//
// Whitelisting this test.
// As part of bug 1077403, the leaking uncaught rejection should be fixed.
//
thisTestLeaksUncaughtRejectionsAndShouldBeFixed("TypeError: window.location is null");
XPCOMUtils.defineLazyModuleGetter(this, "Promise",
"resource://gre/modules/Promise.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Task",
"resource://gre/modules/Task.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "fxAccounts",
"resource://gre/modules/FxAccounts.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
"resource://gre/modules/FileUtils.jsm");
const CHROME_BASE = "chrome://mochitests/content/browser/browser/base/content/test/general/";
// Preference helpers.
var changedPrefs = new Set();
function setPref(name, value) {
changedPrefs.add(name);
Services.prefs.setCharPref(name, value);
}
registerCleanupFunction(function() {
// Ensure we don't pollute prefs for next tests.
for (let name of changedPrefs) {
Services.prefs.clearUserPref(name);
}
});
var gTests = [
{
desc: "Test the remote commands",
teardown: function* () {
gBrowser.removeCurrentTab();
yield signOut();
},
run: function* ()
{
setPref("identity.fxaccounts.remote.signup.uri",
"https://example.com/browser/browser/base/content/test/general/accounts_testRemoteCommands.html");
let tab = yield promiseNewTabLoadEvent("about:accounts");
let mm = tab.linkedBrowser.messageManager;
let deferred = Promise.defer();
// We'll get a message when openPrefs() is called, which this test should
// arrange.
let promisePrefsOpened = promiseOneMessage(tab, "test:openPrefsCalled");
let results = 0;
try {
mm.addMessageListener("test:response", function responseHandler(msg) {
let data = msg.data.data;
if (data.type == "testResult") {
ok(data.pass, data.info);
results++;
} else if (data.type == "testsComplete") {
is(results, data.count, "Checking number of results received matches the number of tests that should have run");
mm.removeMessageListener("test:response", responseHandler);
deferred.resolve();
}
});
} catch (e) {
ok(false, "Failed to get all commands");
deferred.reject();
}
yield deferred.promise;
yield promisePrefsOpened;
}
},
{
desc: "Test action=signin - no user logged in",
teardown: () => gBrowser.removeCurrentTab(),
run: function* ()
{
// When this loads with no user logged-in, we expect the "normal" URL
const expected_url = "https://example.com/?is_sign_in";
setPref("identity.fxaccounts.remote.signin.uri", expected_url);
let [tab, url] = yield promiseNewTabWithIframeLoadEvent("about:accounts?action=signin");
is(url, expected_url, "action=signin got the expected URL");
// we expect the remote iframe to be shown.
yield checkVisibilities(tab, {
stage: false, // parent of 'manage' and 'intro'
manage: false,
intro: false, // this is "get started"
remote: true,
networkError: false
});
}
},
{
desc: "Test action=signin - user logged in",
teardown: function* () {
gBrowser.removeCurrentTab();
yield signOut();
},
run: function* ()
{
// When this loads with a user logged-in, we expect the normal URL to
// have been ignored and the "manage" page to be shown.
const expected_url = "https://example.com/?is_sign_in";
setPref("identity.fxaccounts.remote.signin.uri", expected_url);
yield setSignedInUser();
let tab = yield promiseNewTabLoadEvent("about:accounts?action=signin");
// about:accounts initializes after fetching the current user from Fxa -
// so we also request it - by the time we get it we know it should have
// done its thing.
yield fxAccounts.getSignedInUser();
// we expect "manage" to be shown.
yield checkVisibilities(tab, {
stage: true, // parent of 'manage' and 'intro'
manage: true,
intro: false, // this is "get started"
remote: false,
networkError: false
});
}
},
{
desc: "Test action=signin - captive portal",
teardown: () => gBrowser.removeCurrentTab(),
run: function* ()
{
const signinUrl = "https://redirproxy.example.com/test";
setPref("identity.fxaccounts.remote.signin.uri", signinUrl);
let [tab, ] = yield promiseNewTabWithIframeLoadEvent("about:accounts?action=signin");
yield checkVisibilities(tab, {
stage: true, // parent of 'manage' and 'intro'
manage: false,
intro: false, // this is "get started"
remote: false,
networkError: true
});
}
},
{
desc: "Test action=signin - offline",
teardown: () => {
gBrowser.removeCurrentTab();
BrowserOffline.toggleOfflineStatus();
},
run: function* ()
{
BrowserOffline.toggleOfflineStatus();
Services.cache2.clear();
const signinUrl = "https://unknowndomain.cow";
setPref("identity.fxaccounts.remote.signin.uri", signinUrl);
let [tab, ] = yield promiseNewTabWithIframeLoadEvent("about:accounts?action=signin");
yield checkVisibilities(tab, {
stage: true, // parent of 'manage' and 'intro'
manage: false,
intro: false, // this is "get started"
remote: false,
networkError: true
});
}
},
{
desc: "Test action=signup - no user logged in",
teardown: () => gBrowser.removeCurrentTab(),
run: function* ()
{
const expected_url = "https://example.com/?is_sign_up";
setPref("identity.fxaccounts.remote.signup.uri", expected_url);
let [tab, url] = yield promiseNewTabWithIframeLoadEvent("about:accounts?action=signup");
is(url, expected_url, "action=signup got the expected URL");
// we expect the remote iframe to be shown.
yield checkVisibilities(tab, {
stage: false, // parent of 'manage' and 'intro'
manage: false,
intro: false, // this is "get started"
remote: true,
networkError: false
});
},
},
{
desc: "Test action=signup - user logged in",
teardown: () => gBrowser.removeCurrentTab(),
run: function* ()
{
const expected_url = "https://example.com/?is_sign_up";
setPref("identity.fxaccounts.remote.signup.uri", expected_url);
yield setSignedInUser();
let tab = yield promiseNewTabLoadEvent("about:accounts?action=signup");
yield fxAccounts.getSignedInUser();
// we expect "manage" to be shown.
yield checkVisibilities(tab, {
stage: true, // parent of 'manage' and 'intro'
manage: true,
intro: false, // this is "get started"
remote: false,
networkError: false
});
},
},
{
desc: "Test action=reauth",
teardown: function* () {
gBrowser.removeCurrentTab();
yield signOut();
},
run: function* ()
{
const expected_url = "https://example.com/?is_force_auth";
setPref("identity.fxaccounts.remote.force_auth.uri", expected_url);
yield setSignedInUser();
let [, url] = yield promiseNewTabWithIframeLoadEvent("about:accounts?action=reauth");
// The current user will be appended to the url
let expected = expected_url + "&email=foo%40example.com";
is(url, expected, "action=reauth got the expected URL");
},
},
{
desc: "Test with migrateToDevEdition enabled (success)",
teardown: function* () {
gBrowser.removeCurrentTab();
yield signOut();
},
run: function* ()
{
let fxAccountsCommon = {};
Cu.import("resource://gre/modules/FxAccountsCommon.js", fxAccountsCommon);
const pref = "identity.fxaccounts.migrateToDevEdition";
changedPrefs.add(pref);
Services.prefs.setBoolPref(pref, true);
// Create the signedInUser.json file that will be used as the source of
// migrated user data.
let signedInUser = {
version: 1,
accountData: {
email: "foo@example.com",
uid: "1234@lcip.org",
sessionToken: "dead",
verified: true
}
};
// We use a sub-dir of the real profile dir as the "pretend" profile dir
// for this test.
let profD = Services.dirsvc.get("ProfD", Ci.nsIFile);
let mockDir = profD.clone();
mockDir.append("about-accounts-mock-profd");
mockDir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
let fxAccountsStorage = OS.Path.join(mockDir.path, fxAccountsCommon.DEFAULT_STORAGE_FILENAME);
yield OS.File.writeAtomic(fxAccountsStorage, JSON.stringify(signedInUser));
info("Wrote file " + fxAccountsStorage);
// this is a little subtle - we load about:robots so we get a non-remote
// tab, then we send a message which does both (a) load the URL we want and
// (b) mocks the default profile path used by about:accounts.
let tab = yield promiseNewTabLoadEvent("about:robots");
let readyPromise = promiseOneMessage(tab, "test:load-with-mocked-profile-path-response");
let mm = tab.linkedBrowser.messageManager;
mm.sendAsyncMessage("test:load-with-mocked-profile-path", {
url: "about:accounts",
profilePath: mockDir.path,
});
let response = yield readyPromise;
// We are expecting the iframe to be on the "force reauth" URL
let expected = yield fxAccounts.promiseAccountsForceSigninURI();
is(response.data.url, expected);
let userData = yield fxAccounts.getSignedInUser();
SimpleTest.isDeeply(userData, signedInUser.accountData, "All account data were migrated");
// The migration pref will have been switched off by now.
is(Services.prefs.getBoolPref(pref), false, pref + " got the expected value");
yield OS.File.remove(fxAccountsStorage);
yield OS.File.removeEmptyDir(mockDir.path);
},
},
{
desc: "Test with migrateToDevEdition enabled (no user to migrate)",
teardown: function* () {
gBrowser.removeCurrentTab();
yield signOut();
},
run: function* ()
{
const pref = "identity.fxaccounts.migrateToDevEdition";
changedPrefs.add(pref);
Services.prefs.setBoolPref(pref, true);
let profD = Services.dirsvc.get("ProfD", Ci.nsIFile);
let mockDir = profD.clone();
mockDir.append("about-accounts-mock-profd");
mockDir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
// but leave it empty, so we don't think a user is logged in.
let tab = yield promiseNewTabLoadEvent("about:robots");
let readyPromise = promiseOneMessage(tab, "test:load-with-mocked-profile-path-response");
let mm = tab.linkedBrowser.messageManager;
mm.sendAsyncMessage("test:load-with-mocked-profile-path", {
url: "about:accounts",
profilePath: mockDir.path,
});
let response = yield readyPromise;
// We are expecting the iframe to be on the "signup" URL
let expected = yield fxAccounts.promiseAccountsSignUpURI();
is(response.data.url, expected);
// and expect no signed in user.
let userData = yield fxAccounts.getSignedInUser();
is(userData, null);
// The migration pref should have still been switched off.
is(Services.prefs.getBoolPref(pref), false, pref + " got the expected value");
yield OS.File.removeEmptyDir(mockDir.path);
},
},
{
desc: "Test observers about:accounts",
teardown: function() {
gBrowser.removeCurrentTab();
},
run: function* () {
setPref("identity.fxaccounts.remote.signup.uri", "https://example.com/");
yield setSignedInUser();
let tab = yield promiseNewTabLoadEvent("about:accounts");
// sign the user out - the tab should have action=signin
yield signOut();
// wait for the new load.
yield promiseOneMessage(tab, "test:document:load");
is(tab.linkedBrowser.contentDocument.location.href, "about:accounts?action=signin");
}
},
{
desc: "Test entrypoint query string, no action, no user logged in",
teardown: () => gBrowser.removeCurrentTab(),
run: function* () {
// When this loads with no user logged-in, we expect the "normal" URL
setPref("identity.fxaccounts.remote.signup.uri", "https://example.com/");
let [, url] = yield promiseNewTabWithIframeLoadEvent("about:accounts?entrypoint=abouthome");
is(url, "https://example.com/?entrypoint=abouthome", "entrypoint=abouthome got the expected URL");
},
},
{
desc: "Test entrypoint query string for signin",
teardown: () => gBrowser.removeCurrentTab(),
run: function* () {
// When this loads with no user logged-in, we expect the "normal" URL
const expected_url = "https://example.com/?is_sign_in";
setPref("identity.fxaccounts.remote.signin.uri", expected_url);
let [, url] = yield promiseNewTabWithIframeLoadEvent("about:accounts?action=signin&entrypoint=abouthome");
is(url, expected_url + "&entrypoint=abouthome", "entrypoint=abouthome got the expected URL");
},
},
{
desc: "Test entrypoint query string for signup",
teardown: () => gBrowser.removeCurrentTab(),
run: function* () {
// When this loads with no user logged-in, we expect the "normal" URL
const sign_up_url = "https://example.com/?is_sign_up";
setPref("identity.fxaccounts.remote.signup.uri", sign_up_url);
let [, url] = yield promiseNewTabWithIframeLoadEvent("about:accounts?entrypoint=abouthome&action=signup");
is(url, sign_up_url + "&entrypoint=abouthome", "entrypoint=abouthome got the expected URL");
},
},
{
desc: "about:accounts URL params should be copied to remote URL params " +
"when remote URL has no URL params, except for 'action'",
teardown() {
gBrowser.removeCurrentTab();
},
run: function* () {
let signupURL = "https://example.com/";
setPref("identity.fxaccounts.remote.signup.uri", signupURL);
let queryStr = "email=foo%40example.com&foo=bar&baz=quux";
let [, url] =
yield promiseNewTabWithIframeLoadEvent("about:accounts?" + queryStr +
"&action=action");
is(url, signupURL + "?" + queryStr, "URL params are copied to signup URL");
},
},
{
desc: "about:accounts URL params should be copied to remote URL params " +
"when remote URL already has some URL params, except for 'action'",
teardown() {
gBrowser.removeCurrentTab();
},
run: function* () {
let signupURL = "https://example.com/?param";
setPref("identity.fxaccounts.remote.signup.uri", signupURL);
let queryStr = "email=foo%40example.com&foo=bar&baz=quux";
let [, url] =
yield promiseNewTabWithIframeLoadEvent("about:accounts?" + queryStr +
"&action=action");
is(url, signupURL + "&" + queryStr, "URL params are copied to signup URL");
},
},
]; // gTests
function test()
{
waitForExplicitFinish();
Task.spawn(function* () {
for (let testCase of gTests) {
info(testCase.desc);
try {
yield testCase.run();
} finally {
yield testCase.teardown();
}
}
finish();
});
}
function promiseOneMessage(tab, messageName) {
let mm = tab.linkedBrowser.messageManager;
let deferred = Promise.defer();
mm.addMessageListener(messageName, function onmessage(message) {
mm.removeMessageListener(messageName, onmessage);
deferred.resolve(message);
});
return deferred.promise;
}
function promiseNewTabLoadEvent(aUrl)
{
let tab = gBrowser.selectedTab = gBrowser.addTab(aUrl);
let browser = tab.linkedBrowser;
let mm = browser.messageManager;
// give it an e10s-friendly content script to help with our tests.
mm.loadFrameScript(CHROME_BASE + "content_aboutAccounts.js", true);
// and wait for it to tell us about the load.
return promiseOneMessage(tab, "test:document:load").then(
() => tab
);
}
// Returns a promise which is resolved with the iframe's URL after a new
// tab is created and the iframe in that tab loads.
function promiseNewTabWithIframeLoadEvent(aUrl) {
let deferred = Promise.defer();
let tab = gBrowser.selectedTab = gBrowser.addTab(aUrl);
let browser = tab.linkedBrowser;
let mm = browser.messageManager;
// give it an e10s-friendly content script to help with our tests.
mm.loadFrameScript(CHROME_BASE + "content_aboutAccounts.js", true);
// and wait for it to tell us about the iframe load.
mm.addMessageListener("test:iframe:load", function onFrameLoad(message) {
mm.removeMessageListener("test:iframe:load", onFrameLoad);
deferred.resolve([tab, message.data.url]);
});
return deferred.promise;
}
function checkVisibilities(tab, data) {
let ids = Object.keys(data);
let mm = tab.linkedBrowser.messageManager;
let deferred = Promise.defer();
mm.addMessageListener("test:check-visibilities-response", function onResponse(message) {
mm.removeMessageListener("test:check-visibilities-response", onResponse);
for (let id of ids) {
is(message.data[id], data[id], "Element '" + id + "' has correct visibility");
}
deferred.resolve();
});
mm.sendAsyncMessage("test:check-visibilities", {ids: ids});
return deferred.promise;
}
// watch out - these will fire observers which if you aren't careful, may
// interfere with the tests.
function setSignedInUser(data) {
if (!data) {
data = {
email: "foo@example.com",
uid: "1234@lcip.org",
assertion: "foobar",
sessionToken: "dead",
kA: "beef",
kB: "cafe",
verified: true
}
}
return fxAccounts.setSignedInUser(data);
}
function signOut() {
// we always want a "localOnly" signout here...
return fxAccounts.signOut(true);
}

View file

@ -1,409 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
// This is testing the aboutCertError page (Bug 1207107).
const GOOD_PAGE = "https://example.com/";
const BAD_CERT = "https://expired.example.com/";
const UNKNOWN_ISSUER = "https://self-signed.example.com ";
const BAD_STS_CERT = "https://badchain.include-subdomains.pinning.example.com:443";
const {TabStateFlusher} = Cu.import("resource:///modules/sessionstore/TabStateFlusher.jsm", {});
const ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
add_task(function* checkReturnToAboutHome() {
info("Loading a bad cert page directly and making sure 'return to previous page' goes to about:home");
let browser;
let certErrorLoaded;
let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => {
gBrowser.selectedTab = gBrowser.addTab(BAD_CERT);
browser = gBrowser.selectedBrowser;
certErrorLoaded = waitForCertErrorLoad(browser);
}, false);
info("Loading and waiting for the cert error");
yield certErrorLoaded;
is(browser.webNavigation.canGoBack, false, "!webNavigation.canGoBack");
is(browser.webNavigation.canGoForward, false, "!webNavigation.canGoForward");
// Populate the shistory entries manually, since it happens asynchronously
// and the following tests will be too soon otherwise.
yield TabStateFlusher.flush(browser);
let {entries} = JSON.parse(ss.getTabState(tab));
is(entries.length, 1, "there is one shistory entry");
info("Clicking the go back button on about:certerror");
yield ContentTask.spawn(browser, null, function* () {
let doc = content.document;
let returnButton = doc.getElementById("returnButton");
is(returnButton.getAttribute("autofocus"), "true", "returnButton has autofocus");
returnButton.click();
yield ContentTaskUtils.waitForEvent(this, "pageshow", true);
});
is(browser.webNavigation.canGoBack, true, "webNavigation.canGoBack");
is(browser.webNavigation.canGoForward, false, "!webNavigation.canGoForward");
is(gBrowser.currentURI.spec, "about:home", "Went back");
yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
});
add_task(function* checkReturnToPreviousPage() {
info("Loading a bad cert page and making sure 'return to previous page' goes back");
let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, GOOD_PAGE);
let browser = gBrowser.selectedBrowser;
info("Loading and waiting for the cert error");
let certErrorLoaded = waitForCertErrorLoad(browser);
BrowserTestUtils.loadURI(browser, BAD_CERT);
yield certErrorLoaded;
is(browser.webNavigation.canGoBack, true, "webNavigation.canGoBack");
is(browser.webNavigation.canGoForward, false, "!webNavigation.canGoForward");
// Populate the shistory entries manually, since it happens asynchronously
// and the following tests will be too soon otherwise.
yield TabStateFlusher.flush(browser);
let {entries} = JSON.parse(ss.getTabState(tab));
is(entries.length, 2, "there are two shistory entries");
info("Clicking the go back button on about:certerror");
yield ContentTask.spawn(browser, null, function* () {
let doc = content.document;
let returnButton = doc.getElementById("returnButton");
returnButton.click();
yield ContentTaskUtils.waitForEvent(this, "pageshow", true);
});
is(browser.webNavigation.canGoBack, false, "!webNavigation.canGoBack");
is(browser.webNavigation.canGoForward, true, "webNavigation.canGoForward");
is(gBrowser.currentURI.spec, GOOD_PAGE, "Went back");
yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
});
add_task(function* checkBadStsCert() {
info("Loading a badStsCert and making sure exception button doesn't show up");
yield BrowserTestUtils.openNewForegroundTab(gBrowser, GOOD_PAGE);
let browser = gBrowser.selectedBrowser;
info("Loading and waiting for the cert error");
let certErrorLoaded = waitForCertErrorLoad(browser);
BrowserTestUtils.loadURI(browser, BAD_STS_CERT);
yield certErrorLoaded;
let exceptionButtonHidden = yield ContentTask.spawn(browser, null, function* () {
let doc = content.document;
let exceptionButton = doc.getElementById("exceptionDialogButton");
return exceptionButton.hidden;
});
ok(exceptionButtonHidden, "Exception button is hidden");
yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
});
const PREF_BLOCKLIST_CLOCK_SKEW_SECONDS = "services.blocklist.clock_skew_seconds";
add_task(function* checkWrongSystemTimeWarning() {
function* setUpPage() {
let browser;
let certErrorLoaded;
yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => {
gBrowser.selectedTab = gBrowser.addTab(BAD_CERT);
browser = gBrowser.selectedBrowser;
certErrorLoaded = waitForCertErrorLoad(browser);
}, false);
info("Loading and waiting for the cert error");
yield certErrorLoaded;
return yield ContentTask.spawn(browser, null, function* () {
let doc = content.document;
let div = doc.getElementById("wrongSystemTimePanel");
let systemDateDiv = doc.getElementById("wrongSystemTime_systemDate");
let actualDateDiv = doc.getElementById("wrongSystemTime_actualDate");
let learnMoreLink = doc.getElementById("learnMoreLink");
return {
divDisplay: content.getComputedStyle(div).display,
text: div.textContent,
systemDate: systemDateDiv.textContent,
actualDate: actualDateDiv.textContent,
learnMoreLink: learnMoreLink.href
};
});
}
let formatter = new Intl.DateTimeFormat();
// pretend we have a positively skewed (ahead) system time
let serverDate = new Date("2015/10/27");
let serverDateFmt = formatter.format(serverDate);
let localDateFmt = formatter.format(new Date());
let skew = Math.floor((Date.now() - serverDate.getTime()) / 1000);
yield new Promise(r => SpecialPowers.pushPrefEnv({set:
[[PREF_BLOCKLIST_CLOCK_SKEW_SECONDS, skew]]}, r));
info("Loading a bad cert page with a skewed clock");
let message = yield Task.spawn(setUpPage);
isnot(message.divDisplay, "none", "Wrong time message information is visible");
ok(message.text.includes("because your clock appears to show the wrong time"),
"Correct error message found");
ok(message.text.includes("expired.example.com"), "URL found in error message");
ok(message.systemDate.includes(localDateFmt), "correct local date displayed");
ok(message.actualDate.includes(serverDateFmt), "correct server date displayed");
ok(message.learnMoreLink.includes("time-errors"), "time-errors in the Learn More URL");
yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
// pretend we have a negatively skewed (behind) system time
serverDate = new Date();
serverDate.setYear(serverDate.getFullYear() + 1);
serverDateFmt = formatter.format(serverDate);
skew = Math.floor((Date.now() - serverDate.getTime()) / 1000);
yield new Promise(r => SpecialPowers.pushPrefEnv({set:
[[PREF_BLOCKLIST_CLOCK_SKEW_SECONDS, skew]]}, r));
info("Loading a bad cert page with a skewed clock");
message = yield Task.spawn(setUpPage);
isnot(message.divDisplay, "none", "Wrong time message information is visible");
ok(message.text.includes("because your clock appears to show the wrong time"),
"Correct error message found");
ok(message.text.includes("expired.example.com"), "URL found in error message");
ok(message.systemDate.includes(localDateFmt), "correct local date displayed");
ok(message.actualDate.includes(serverDateFmt), "correct server date displayed");
yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
// pretend we only have a slightly skewed system time, four hours
skew = 60 * 60 * 4;
yield new Promise(r => SpecialPowers.pushPrefEnv({set:
[[PREF_BLOCKLIST_CLOCK_SKEW_SECONDS, skew]]}, r));
info("Loading a bad cert page with an only slightly skewed clock");
message = yield Task.spawn(setUpPage);
is(message.divDisplay, "none", "Wrong time message information is not visible");
yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
// now pretend we have no skewed system time
skew = 0;
yield new Promise(r => SpecialPowers.pushPrefEnv({set:
[[PREF_BLOCKLIST_CLOCK_SKEW_SECONDS, skew]]}, r));
info("Loading a bad cert page with no skewed clock");
message = yield Task.spawn(setUpPage);
is(message.divDisplay, "none", "Wrong time message information is not visible");
yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
});
add_task(function* checkAdvancedDetails() {
info("Loading a bad cert page and verifying the main error and advanced details section");
let browser;
let certErrorLoaded;
yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => {
gBrowser.selectedTab = gBrowser.addTab(BAD_CERT);
browser = gBrowser.selectedBrowser;
certErrorLoaded = waitForCertErrorLoad(browser);
}, false);
info("Loading and waiting for the cert error");
yield certErrorLoaded;
let message = yield ContentTask.spawn(browser, null, function* () {
let doc = content.document;
let shortDescText = doc.getElementById("errorShortDescText");
info("Main error text: " + shortDescText.textContent);
ok(shortDescText.textContent.includes("expired.example.com"),
"Should list hostname in error message.");
let advancedButton = doc.getElementById("advancedButton");
advancedButton.click();
let el = doc.getElementById("errorCode");
return { textContent: el.textContent, tagName: el.tagName };
});
is(message.textContent, "SEC_ERROR_EXPIRED_CERTIFICATE",
"Correct error message found");
is(message.tagName, "a", "Error message is a link");
message = yield ContentTask.spawn(browser, null, function* () {
let doc = content.document;
let errorCode = doc.getElementById("errorCode");
errorCode.click();
let div = doc.getElementById("certificateErrorDebugInformation");
let text = doc.getElementById("certificateErrorText");
let serhelper = Cc["@mozilla.org/network/serialization-helper;1"]
.getService(Ci.nsISerializationHelper);
let serializable = docShell.failedChannel.securityInfo
.QueryInterface(Ci.nsITransportSecurityInfo)
.QueryInterface(Ci.nsISerializable);
let serializedSecurityInfo = serhelper.serializeToString(serializable);
return {
divDisplay: content.getComputedStyle(div).display,
text: text.textContent,
securityInfoAsString: serializedSecurityInfo
};
});
isnot(message.divDisplay, "none", "Debug information is visible");
ok(message.text.includes(BAD_CERT), "Correct URL found");
ok(message.text.includes("Certificate has expired"),
"Correct error message found");
ok(message.text.includes("HTTP Strict Transport Security: false"),
"Correct HSTS value found");
ok(message.text.includes("HTTP Public Key Pinning: false"),
"Correct HPKP value found");
let certChain = getCertChain(message.securityInfoAsString);
ok(message.text.includes(certChain), "Found certificate chain");
yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
});
add_task(function* checkAdvancedDetailsForHSTS() {
info("Loading a bad STS cert page and verifying the advanced details section");
let browser;
let certErrorLoaded;
yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => {
gBrowser.selectedTab = gBrowser.addTab(BAD_STS_CERT);
browser = gBrowser.selectedBrowser;
certErrorLoaded = waitForCertErrorLoad(browser);
}, false);
info("Loading and waiting for the cert error");
yield certErrorLoaded;
let message = yield ContentTask.spawn(browser, null, function* () {
let doc = content.document;
let advancedButton = doc.getElementById("advancedButton");
advancedButton.click();
let ec = doc.getElementById("errorCode");
let cdl = doc.getElementById("cert_domain_link");
return {
ecTextContent: ec.textContent,
ecTagName: ec.tagName,
cdlTextContent: cdl.textContent,
cdlTagName: cdl.tagName
};
});
const badStsUri = Services.io.newURI(BAD_STS_CERT, null, null);
is(message.ecTextContent, "SSL_ERROR_BAD_CERT_DOMAIN",
"Correct error message found");
is(message.ecTagName, "a", "Error message is a link");
const url = badStsUri.prePath.slice(badStsUri.prePath.indexOf(".") + 1);
is(message.cdlTextContent, url,
"Correct cert_domain_link contents found");
is(message.cdlTagName, "a", "cert_domain_link is a link");
message = yield ContentTask.spawn(browser, null, function* () {
let doc = content.document;
let errorCode = doc.getElementById("errorCode");
errorCode.click();
let div = doc.getElementById("certificateErrorDebugInformation");
let text = doc.getElementById("certificateErrorText");
let serhelper = Cc["@mozilla.org/network/serialization-helper;1"]
.getService(Ci.nsISerializationHelper);
let serializable = docShell.failedChannel.securityInfo
.QueryInterface(Ci.nsITransportSecurityInfo)
.QueryInterface(Ci.nsISerializable);
let serializedSecurityInfo = serhelper.serializeToString(serializable);
return {
divDisplay: content.getComputedStyle(div).display,
text: text.textContent,
securityInfoAsString: serializedSecurityInfo
};
});
isnot(message.divDisplay, "none", "Debug information is visible");
ok(message.text.includes(badStsUri.spec), "Correct URL found");
ok(message.text.includes("requested domain name does not match the server\u2019s certificate"),
"Correct error message found");
ok(message.text.includes("HTTP Strict Transport Security: false"),
"Correct HSTS value found");
ok(message.text.includes("HTTP Public Key Pinning: true"),
"Correct HPKP value found");
let certChain = getCertChain(message.securityInfoAsString);
ok(message.text.includes(certChain), "Found certificate chain");
yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
});
add_task(function* checkUnknownIssuerLearnMoreLink() {
info("Loading a cert error for self-signed pages and checking the correct link is shown");
let browser;
let certErrorLoaded;
yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => {
gBrowser.selectedTab = gBrowser.addTab(UNKNOWN_ISSUER);
browser = gBrowser.selectedBrowser;
certErrorLoaded = waitForCertErrorLoad(browser);
}, false);
info("Loading and waiting for the cert error");
yield certErrorLoaded;
let href = yield ContentTask.spawn(browser, null, function* () {
let learnMoreLink = content.document.getElementById("learnMoreLink");
return learnMoreLink.href;
});
ok(href.endsWith("security-error"), "security-error in the Learn More URL");
yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
});
function waitForCertErrorLoad(browser) {
return new Promise(resolve => {
info("Waiting for DOMContentLoaded event");
browser.addEventListener("DOMContentLoaded", function load() {
browser.removeEventListener("DOMContentLoaded", load, false, true);
resolve();
}, false, true);
});
}
function getCertChain(securityInfoAsString) {
let certChain = "";
const serhelper = Cc["@mozilla.org/network/serialization-helper;1"]
.getService(Ci.nsISerializationHelper);
let securityInfo = serhelper.deserializeObject(securityInfoAsString);
securityInfo.QueryInterface(Ci.nsITransportSecurityInfo);
let certs = securityInfo.failedCertChain.getEnumerator();
while (certs.hasMoreElements()) {
let cert = certs.getNext();
cert.QueryInterface(Ci.nsIX509Cert);
certChain += getPEMString(cert);
}
return certChain;
}
function getDERString(cert)
{
var length = {};
var derArray = cert.getRawDER(length);
var derString = '';
for (var i = 0; i < derArray.length; i++) {
derString += String.fromCharCode(derArray[i]);
}
return derString;
}
function getPEMString(cert)
{
var derb64 = btoa(getDERString(cert));
// Wrap the Base64 string into lines of 64 characters,
// with CRLF line breaks (as specified in RFC 1421).
var wrapped = derb64.replace(/(\S{64}(?!$))/g, "$1\r\n");
return "-----BEGIN CERTIFICATE-----\r\n"
+ wrapped
+ "\r\n-----END CERTIFICATE-----\r\n";
}

View file

@ -1,139 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/
*/
XPCOMUtils.defineLazyModuleGetter(this, "Promise",
"resource://gre/modules/Promise.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Task",
"resource://gre/modules/Task.jsm");
const CHROME_BASE = "chrome://mochitests/content/browser/browser/base/content/test/general/";
const HTTPS_BASE = "https://example.com/browser/browser/base/content/test/general/";
const TELEMETRY_LOG_PREF = "toolkit.telemetry.log.level";
const telemetryOriginalLogPref = Preferences.get(TELEMETRY_LOG_PREF, null);
const originalReportUrl = Services.prefs.getCharPref("datareporting.healthreport.about.reportUrl");
registerCleanupFunction(function() {
// Ensure we don't pollute prefs for next tests.
if (telemetryOriginalLogPref) {
Preferences.set(TELEMETRY_LOG_PREF, telemetryOriginalLogPref);
} else {
Preferences.reset(TELEMETRY_LOG_PREF);
}
try {
Services.prefs.setCharPref("datareporting.healthreport.about.reportUrl", originalReportUrl);
Services.prefs.setBoolPref("datareporting.healthreport.uploadEnabled", true);
} catch (ex) {}
});
function fakeTelemetryNow(...args) {
let date = new Date(...args);
let scope = {};
const modules = [
Cu.import("resource://gre/modules/TelemetrySession.jsm", scope),
Cu.import("resource://gre/modules/TelemetryEnvironment.jsm", scope),
Cu.import("resource://gre/modules/TelemetryController.jsm", scope),
];
for (let m of modules) {
m.Policy.now = () => new Date(date);
}
return date;
}
function* setupPingArchive() {
let scope = {};
Cu.import("resource://gre/modules/TelemetryController.jsm", scope);
Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader)
.loadSubScript(CHROME_BASE + "healthreport_pingData.js", scope);
for (let p of scope.TEST_PINGS) {
fakeTelemetryNow(p.date);
p.id = yield scope.TelemetryController.submitExternalPing(p.type, p.payload);
}
}
var gTests = [
{
desc: "Test the remote commands",
setup: Task.async(function*()
{
Preferences.set(TELEMETRY_LOG_PREF, "Trace");
yield setupPingArchive();
Preferences.set("datareporting.healthreport.about.reportUrl",
HTTPS_BASE + "healthreport_testRemoteCommands.html");
}),
run: function (iframe)
{
let deferred = Promise.defer();
let results = 0;
try {
iframe.contentWindow.addEventListener("FirefoxHealthReportTestResponse", function evtHandler(event) {
let data = event.detail.data;
if (data.type == "testResult") {
ok(data.pass, data.info);
results++;
}
else if (data.type == "testsComplete") {
is(results, data.count, "Checking number of results received matches the number of tests that should have run");
iframe.contentWindow.removeEventListener("FirefoxHealthReportTestResponse", evtHandler, true);
deferred.resolve();
}
}, true);
} catch (e) {
ok(false, "Failed to get all commands");
deferred.reject();
}
return deferred.promise;
}
},
]; // gTests
function test()
{
waitForExplicitFinish();
// xxxmpc leaving this here until we resolve bug 854038 and bug 854060
requestLongerTimeout(10);
Task.spawn(function* () {
for (let testCase of gTests) {
info(testCase.desc);
yield testCase.setup();
let iframe = yield promiseNewTabLoadEvent("about:healthreport");
yield testCase.run(iframe);
gBrowser.removeCurrentTab();
}
finish();
});
}
function promiseNewTabLoadEvent(aUrl, aEventType="load")
{
let deferred = Promise.defer();
let tab = gBrowser.selectedTab = gBrowser.addTab(aUrl);
tab.linkedBrowser.addEventListener(aEventType, function load(event) {
tab.linkedBrowser.removeEventListener(aEventType, load, true);
let iframe = tab.linkedBrowser.contentDocument.getElementById("remote-report");
iframe.addEventListener("load", function frameLoad(e) {
if (iframe.contentWindow.location.href == "about:blank" ||
e.target != iframe) {
return;
}
iframe.removeEventListener("load", frameLoad, false);
deferred.resolve(iframe);
}, false);
}, true);
return deferred.promise;
}

View file

@ -1,668 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/
*/
// This test needs to be split up. See bug 1258717.
requestLongerTimeout(4);
ignoreAllUncaughtExceptions();
XPCOMUtils.defineLazyModuleGetter(this, "AboutHomeUtils",
"resource:///modules/AboutHome.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "AppConstants",
"resource://gre/modules/AppConstants.jsm");
const TEST_CONTENT_HELPER = "chrome://mochitests/content/browser/browser/base/" +
"content/test/general/aboutHome_content_script.js";
var gRightsVersion = Services.prefs.getIntPref("browser.rights.version");
registerCleanupFunction(function() {
// Ensure we don't pollute prefs for next tests.
Services.prefs.clearUserPref("network.cookies.cookieBehavior");
Services.prefs.clearUserPref("network.cookie.lifetimePolicy");
Services.prefs.clearUserPref("browser.rights.override");
Services.prefs.clearUserPref("browser.rights." + gRightsVersion + ".shown");
});
add_task(function* () {
info("Check that clearing cookies does not clear storage");
yield withSnippetsMap(
() => {
Cc["@mozilla.org/observer-service;1"]
.getService(Ci.nsIObserverService)
.notifyObservers(null, "cookie-changed", "cleared");
},
function* () {
isnot(content.gSnippetsMap.get("snippets-last-update"), null,
"snippets-last-update should have a value");
});
});
add_task(function* () {
info("Check default snippets are shown");
yield withSnippetsMap(null, function* () {
let doc = content.document;
let snippetsElt = doc.getElementById("snippets");
ok(snippetsElt, "Found snippets element")
is(snippetsElt.getElementsByTagName("span").length, 1,
"A default snippet is present.");
});
});
add_task(function* () {
info("Check default snippets are shown if snippets are invalid xml");
yield withSnippetsMap(
// This must set some incorrect xhtml code.
snippetsMap => snippetsMap.set("snippets", "<p><b></p></b>"),
function* () {
let doc = content.document;
let snippetsElt = doc.getElementById("snippets");
ok(snippetsElt, "Found snippets element");
is(snippetsElt.getElementsByTagName("span").length, 1,
"A default snippet is present.");
content.gSnippetsMap.delete("snippets");
});
});
add_task(function* () {
info("Check that performing a search fires a search event and records to Telemetry.");
yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:home" }, function* (browser) {
let currEngine = Services.search.currentEngine;
let engine = yield promiseNewEngine("searchSuggestionEngine.xml");
// Make this actually work in healthreport by giving it an ID:
Object.defineProperty(engine.wrappedJSObject, "identifier",
{ value: "org.mozilla.testsearchsuggestions" });
let p = promiseContentSearchChange(browser, engine.name);
Services.search.currentEngine = engine;
yield p;
yield ContentTask.spawn(browser, { expectedName: engine.name }, function* (args) {
let engineName = content.wrappedJSObject.gContentSearchController.defaultEngine.name;
is(engineName, args.expectedName, "Engine name in DOM should match engine we just added");
});
let numSearchesBefore = 0;
// Get the current number of recorded searches.
let histogramKey = engine.identifier + ".abouthome";
try {
let hs = Services.telemetry.getKeyedHistogramById("SEARCH_COUNTS").snapshot();
if (histogramKey in hs) {
numSearchesBefore = hs[histogramKey].sum;
}
} catch (ex) {
// No searches performed yet, not a problem, |numSearchesBefore| is 0.
}
let searchStr = "a search";
let expectedURL = Services.search.currentEngine
.getSubmission(searchStr, null, "homepage").uri.spec;
let promise = waitForDocLoadAndStopIt(expectedURL, browser);
// Perform a search to increase the SEARCH_COUNT histogram.
yield ContentTask.spawn(browser, { searchStr }, function* (args) {
let doc = content.document;
info("Perform a search.");
doc.getElementById("searchText").value = args.searchStr;
doc.getElementById("searchSubmit").click();
});
yield promise;
// Make sure the SEARCH_COUNTS histogram has the right key and count.
let hs = Services.telemetry.getKeyedHistogramById("SEARCH_COUNTS").snapshot();
Assert.ok(histogramKey in hs, "histogram with key should be recorded");
Assert.equal(hs[histogramKey].sum, numSearchesBefore + 1,
"histogram sum should be incremented");
Services.search.currentEngine = currEngine;
try {
Services.search.removeEngine(engine);
} catch (ex) {}
});
});
add_task(function* () {
info("Check snippets map is cleared if cached version is old");
yield withSnippetsMap(
snippetsMap => {
snippetsMap.set("snippets", "test");
snippetsMap.set("snippets-cached-version", 0);
},
function* () {
let snippetsMap = content.gSnippetsMap;
ok(!snippetsMap.has("snippets"), "snippets have been properly cleared");
ok(!snippetsMap.has("snippets-cached-version"),
"cached-version has been properly cleared");
});
});
add_task(function* () {
info("Check cached snippets are shown if cached version is current");
yield withSnippetsMap(
snippetsMap => snippetsMap.set("snippets", "test"),
function* (args) {
let doc = content.document;
let snippetsMap = content.gSnippetsMap
let snippetsElt = doc.getElementById("snippets");
ok(snippetsElt, "Found snippets element");
is(snippetsElt.innerHTML, "test", "Cached snippet is present.");
is(snippetsMap.get("snippets"), "test", "snippets still cached");
is(snippetsMap.get("snippets-cached-version"),
args.expectedVersion,
"cached-version is correct");
ok(snippetsMap.has("snippets-last-update"), "last-update still exists");
}, { expectedVersion: AboutHomeUtils.snippetsVersion });
});
add_task(function* () {
info("Check if the 'Know Your Rights' default snippet is shown when " +
"'browser.rights.override' pref is set and that its link works");
Services.prefs.setBoolPref("browser.rights.override", false);
ok(AboutHomeUtils.showKnowYourRights, "AboutHomeUtils.showKnowYourRights should be TRUE");
yield withSnippetsMap(null, function* () {
let doc = content.document;
let snippetsElt = doc.getElementById("snippets");
ok(snippetsElt, "Found snippets element");
let linkEl = snippetsElt.querySelector("a");
is(linkEl.href, "about:rights", "Snippet link is present.");
}, null, function* () {
let loadPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser, false, "about:rights");
yield BrowserTestUtils.synthesizeMouseAtCenter("a[href='about:rights']", {
button: 0
}, gBrowser.selectedBrowser);
yield loadPromise;
is(gBrowser.currentURI.spec, "about:rights", "about:rights should have opened.");
});
Services.prefs.clearUserPref("browser.rights.override");
});
add_task(function* () {
info("Check if the 'Know Your Rights' default snippet is NOT shown when " +
"'browser.rights.override' pref is NOT set");
Services.prefs.setBoolPref("browser.rights.override", true);
let rightsData = AboutHomeUtils.knowYourRightsData;
ok(!rightsData, "AboutHomeUtils.knowYourRightsData should be FALSE");
yield withSnippetsMap(null, function*() {
let doc = content.document;
let snippetsElt = doc.getElementById("snippets");
ok(snippetsElt, "Found snippets element");
ok(snippetsElt.getElementsByTagName("a")[0].href != "about:rights",
"Snippet link should not point to about:rights.");
});
Services.prefs.clearUserPref("browser.rights.override");
});
add_task(function* () {
info("Check POST search engine support");
yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:home" }, function* (browser) {
return new Promise(resolve => {
let searchObserver = Task.async(function* search_observer(subject, topic, data) {
let currEngine = Services.search.defaultEngine;
let engine = subject.QueryInterface(Ci.nsISearchEngine);
info("Observer: " + data + " for " + engine.name);
if (data != "engine-added")
return;
if (engine.name != "POST Search")
return;
Services.obs.removeObserver(searchObserver, "browser-search-engine-modified");
// Ready to execute the tests!
let needle = "Search for something awesome.";
let p = promiseContentSearchChange(browser, engine.name);
Services.search.defaultEngine = engine;
yield p;
let promise = BrowserTestUtils.browserLoaded(browser);
yield ContentTask.spawn(browser, { needle }, function* (args) {
let doc = content.document;
doc.getElementById("searchText").value = args.needle;
doc.getElementById("searchSubmit").click();
});
yield promise;
// When the search results load, check them for correctness.
yield ContentTask.spawn(browser, { needle }, function* (args) {
let loadedText = content.document.body.textContent;
ok(loadedText, "search page loaded");
is(loadedText, "searchterms=" + escape(args.needle.replace(/\s/g, "+")),
"Search text should arrive correctly");
});
Services.search.defaultEngine = currEngine;
try {
Services.search.removeEngine(engine);
} catch (ex) {}
resolve();
});
Services.obs.addObserver(searchObserver, "browser-search-engine-modified", false);
Services.search.addEngine("http://test:80/browser/browser/base/content/test/general/POSTSearchEngine.xml",
null, null, false);
});
});
});
add_task(function* () {
info("Make sure that a page can't imitate about:home");
yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:home" }, function* (browser) {
let promise = BrowserTestUtils.browserLoaded(browser);
browser.loadURI("https://example.com/browser/browser/base/content/test/general/test_bug959531.html");
yield promise;
yield ContentTask.spawn(browser, null, function* () {
let button = content.document.getElementById("settings");
ok(button, "Found settings button in test page");
button.click();
});
yield new Promise(resolve => {
// It may take a few turns of the event loop before the window
// is displayed, so we wait.
function check(n) {
let win = Services.wm.getMostRecentWindow("Browser:Preferences");
ok(!win, "Preferences window not showing");
if (win) {
win.close();
}
if (n > 0) {
executeSoon(() => check(n-1));
} else {
resolve();
}
}
check(5);
});
});
});
add_task(function* () {
// See browser_contentSearchUI.js for comprehensive content search UI tests.
info("Search suggestion smoke test");
yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:home" }, function* (browser) {
// Add a test engine that provides suggestions and switch to it.
let currEngine = Services.search.currentEngine;
let engine = yield promiseNewEngine("searchSuggestionEngine.xml");
let p = promiseContentSearchChange(browser, engine.name);
Services.search.currentEngine = engine;
yield p;
yield ContentTask.spawn(browser, null, function* () {
// Avoid intermittent failures.
content.wrappedJSObject.gContentSearchController.remoteTimeout = 5000;
// Type an X in the search input.
let input = content.document.getElementById("searchText");
input.focus();
});
yield BrowserTestUtils.synthesizeKey("x", {}, browser);
yield ContentTask.spawn(browser, null, function* () {
// Wait for the search suggestions to become visible.
let table = content.document.getElementById("searchSuggestionTable");
let input = content.document.getElementById("searchText");
yield new Promise(resolve => {
let observer = new content.MutationObserver(() => {
if (input.getAttribute("aria-expanded") == "true") {
observer.disconnect();
ok(!table.hidden, "Search suggestion table unhidden");
resolve();
}
});
observer.observe(input, {
attributes: true,
attributeFilter: ["aria-expanded"],
});
});
});
// Empty the search input, causing the suggestions to be hidden.
yield BrowserTestUtils.synthesizeKey("a", { accelKey: true }, browser);
yield BrowserTestUtils.synthesizeKey("VK_DELETE", {}, browser);
yield ContentTask.spawn(browser, null, function* () {
let table = content.document.getElementById("searchSuggestionTable");
yield ContentTaskUtils.waitForCondition(() => table.hidden,
"Search suggestion table hidden");
});
Services.search.currentEngine = currEngine;
try {
Services.search.removeEngine(engine);
} catch (ex) { }
});
});
add_task(function* () {
info("Clicking suggestion list while composing");
yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:home" }, function* (browser) {
// Add a test engine that provides suggestions and switch to it.
let currEngine = Services.search.currentEngine;
let engine = yield promiseNewEngine("searchSuggestionEngine.xml");
let p = promiseContentSearchChange(browser, engine.name);
Services.search.currentEngine = engine;
yield p;
yield ContentTask.spawn(browser, null, function* () {
// Start composition and type "x"
let input = content.document.getElementById("searchText");
input.focus();
});
yield BrowserTestUtils.synthesizeComposition({
type: "compositionstart",
data: ""
}, browser);
yield BrowserTestUtils.synthesizeCompositionChange({
composition: {
string: "x",
clauses: [
{ length: 1, attr: Ci.nsITextInputProcessor.ATTR_RAW_CLAUSE }
]
},
caret: { start: 1, length: 0 }
}, browser);
yield ContentTask.spawn(browser, null, function* () {
let searchController = content.wrappedJSObject.gContentSearchController;
// Wait for the search suggestions to become visible.
let table = searchController._suggestionsList;
let input = content.document.getElementById("searchText");
yield new Promise(resolve => {
let observer = new content.MutationObserver(() => {
if (input.getAttribute("aria-expanded") == "true") {
observer.disconnect();
ok(!table.hidden, "Search suggestion table unhidden");
resolve();
}
});
observer.observe(input, {
attributes: true,
attributeFilter: ["aria-expanded"],
});
});
let row = table.children[1];
row.setAttribute("id", "TEMPID");
// ContentSearchUIController looks at the current selectedIndex when
// performing a search. Synthesizing the mouse event on the suggestion
// doesn't actually mouseover the suggestion and trigger it to be flagged
// as selected, so we manually select it first.
searchController.selectedIndex = 1;
});
// Click the second suggestion.
let expectedURL = Services.search.currentEngine
.getSubmission("xbar", null, "homepage").uri.spec;
let loadPromise = waitForDocLoadAndStopIt(expectedURL);
yield BrowserTestUtils.synthesizeMouseAtCenter("#TEMPID", {
button: 0
}, browser);
yield loadPromise;
yield ContentTask.spawn(browser, null, function* () {
let input = content.document.getElementById("searchText");
ok(input.value == "x", "Input value did not change");
let row = content.document.getElementById("TEMPID");
if (row) {
row.removeAttribute("id");
}
});
Services.search.currentEngine = currEngine;
try {
Services.search.removeEngine(engine);
} catch (ex) { }
});
});
add_task(function* () {
info("Pressing any key should focus the search box in the page, and send the key to it");
yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:home" }, function* (browser) {
yield BrowserTestUtils.synthesizeMouseAtCenter("#brandLogo", {}, browser);
yield ContentTask.spawn(browser, null, function* () {
let doc = content.document;
isnot(doc.getElementById("searchText"), doc.activeElement,
"Search input should not be the active element.");
});
yield BrowserTestUtils.synthesizeKey("a", {}, browser);
yield ContentTask.spawn(browser, null, function* () {
let doc = content.document;
let searchInput = doc.getElementById("searchText");
yield ContentTaskUtils.waitForCondition(() => doc.activeElement === searchInput,
"Search input should be the active element.");
is(searchInput.value, "a", "Search input should be 'a'.");
});
});
});
add_task(function* () {
info("Cmd+k should focus the search box in the toolbar when it's present");
yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:home" }, function* (browser) {
yield BrowserTestUtils.synthesizeMouseAtCenter("#brandLogo", {}, browser);
let doc = window.document;
let searchInput = doc.getElementById("searchbar").textbox.inputField;
isnot(searchInput, doc.activeElement, "Search bar should not be the active element.");
EventUtils.synthesizeKey("k", { accelKey: true });
yield promiseWaitForCondition(() => doc.activeElement === searchInput);
is(searchInput, doc.activeElement, "Search bar should be the active element.");
});
});
add_task(function* () {
info("Sync button should open about:preferences#sync");
yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:home" }, function* (browser) {
let oldOpenPrefs = window.openPreferences;
let openPrefsPromise = new Promise(resolve => {
window.openPreferences = function (pane, params) {
resolve({ pane: pane, params: params });
};
});
yield BrowserTestUtils.synthesizeMouseAtCenter("#sync", {}, browser);
let result = yield openPrefsPromise;
window.openPreferences = oldOpenPrefs;
is(result.pane, "paneSync", "openPreferences should be called with paneSync");
is(result.params.urlParams.entrypoint, "abouthome",
"openPreferences should be called with abouthome entrypoint");
});
});
add_task(function* () {
info("Pressing Space while the Addons button is focused should activate it");
// Skip this test on Mac, because Space doesn't activate the button there.
if (AppConstants.platform == "macosx") {
return;
}
yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:home" }, function* (browser) {
info("Waiting for about:addons tab to open...");
let promiseTabOpened = BrowserTestUtils.waitForNewTab(gBrowser, "about:addons");
yield ContentTask.spawn(browser, null, function* () {
let addOnsButton = content.document.getElementById("addons");
addOnsButton.focus();
});
yield BrowserTestUtils.synthesizeKey(" ", {}, browser);
let tab = yield promiseTabOpened;
is(tab.linkedBrowser.currentURI.spec, "about:addons",
"Should have seen the about:addons tab");
yield BrowserTestUtils.removeTab(tab);
});
});
/**
* Cleans up snippets and ensures that by default we don't try to check for
* remote snippets since that may cause network bustage or slowness.
*
* @param aSetupFn
* The setup function to be run.
* @param testFn
* the content task to run
* @param testArgs (optional)
* the parameters to pass to the content task
* @param parentFn (optional)
* the function to run in the parent after the content task has completed.
* @return {Promise} resolved when the snippets are ready. Gets the snippets map.
*/
function* withSnippetsMap(setupFn, testFn, testArgs = null, parentFn = null) {
let setupFnSource;
if (setupFn) {
setupFnSource = setupFn.toSource();
}
yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" }, function* (browser) {
let promiseAfterLocationChange = () => {
return ContentTask.spawn(browser, {
setupFnSource,
version: AboutHomeUtils.snippetsVersion,
}, function* (args) {
return new Promise(resolve => {
let document = content.document;
// We're not using Promise-based listeners, because they resolve asynchronously.
// The snippets test setup code relies on synchronous behaviour here.
document.addEventListener("AboutHomeLoadSnippets", function loadSnippets() {
document.removeEventListener("AboutHomeLoadSnippets", loadSnippets);
let updateSnippets;
if (args.setupFnSource) {
updateSnippets = eval(`(() => (${args.setupFnSource}))()`);
}
content.wrappedJSObject.ensureSnippetsMapThen(snippetsMap => {
snippetsMap = Cu.waiveXrays(snippetsMap);
info("Got snippets map: " +
"{ last-update: " + snippetsMap.get("snippets-last-update") +
", cached-version: " + snippetsMap.get("snippets-cached-version") +
" }");
// Don't try to update.
snippetsMap.set("snippets-last-update", Date.now());
snippetsMap.set("snippets-cached-version", args.version);
// Clear snippets.
snippetsMap.delete("snippets");
if (updateSnippets) {
updateSnippets(snippetsMap);
}
// Tack it to the global object
content.gSnippetsMap = snippetsMap;
resolve();
});
});
});
});
};
// We'd like to listen to the 'AboutHomeLoadSnippets' event on a fresh
// document as soon as technically possible, so we use webProgress.
let promise = new Promise(resolve => {
let wpl = {
onLocationChange() {
gBrowser.removeProgressListener(wpl);
// Phase 2: retrieving the snippets map is the next promise on our agenda.
promiseAfterLocationChange().then(resolve);
},
onProgressChange() {},
onStatusChange() {},
onSecurityChange() {}
};
gBrowser.addProgressListener(wpl);
});
// Set the URL to 'about:home' here to allow capturing the 'AboutHomeLoadSnippets'
// event.
browser.loadURI("about:home");
// Wait for LocationChange.
yield promise;
yield ContentTask.spawn(browser, testArgs, testFn);
if (parentFn) {
yield parentFn();
}
});
}
function promiseContentSearchChange(browser, newEngineName) {
return ContentTask.spawn(browser, { newEngineName }, function* (args) {
return new Promise(resolve => {
content.addEventListener("ContentSearchService", function listener(aEvent) {
if (aEvent.detail.type == "CurrentState" &&
content.wrappedJSObject.gContentSearchController.defaultEngine.name == args.newEngineName) {
content.removeEventListener("ContentSearchService", listener);
resolve();
}
});
});
});
}
function promiseNewEngine(basename) {
info("Waiting for engine to be added: " + basename);
return new Promise((resolve, reject) => {
let url = getRootDirectory(gTestPath) + basename;
Services.search.addEngine(url, null, "", false, {
onSuccess: function (engine) {
info("Search engine added: " + basename);
registerCleanupFunction(() => {
try {
Services.search.removeEngine(engine);
} catch (ex) { /* Can't remove the engine more than once */ }
});
resolve(engine);
},
onError: function (errCode) {
ok(false, "addEngine failed with error code " + errCode);
reject();
},
});
});
}

View file

@ -1,28 +0,0 @@
add_task(function* () {
let newWindow = yield BrowserTestUtils.openNewBrowserWindow();
let resizedPromise = BrowserTestUtils.waitForEvent(newWindow, "resize");
newWindow.resizeTo(300, 300);
yield resizedPromise;
yield BrowserTestUtils.openNewForegroundTab(newWindow.gBrowser, "about:home");
yield ContentTask.spawn(newWindow.gBrowser.selectedBrowser, {}, function* () {
Assert.equal(content.document.body.getAttribute("narrow"), "true", "narrow mode");
});
resizedPromise = BrowserTestUtils.waitForContentEvent(newWindow.gBrowser.selectedBrowser, "resize");
yield ContentTask.spawn(newWindow.gBrowser.selectedBrowser, {}, function* () {
content.window.resizeTo(800, 800);
});
yield resizedPromise;
yield ContentTask.spawn(newWindow.gBrowser.selectedBrowser, {}, function* () {
Assert.equal(content.document.body.hasAttribute("narrow"), false, "non-narrow mode");
});
yield BrowserTestUtils.closeWindow(newWindow);
});

View file

@ -1,47 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
// Set ourselves up for TLS error
Services.prefs.setIntPref("security.tls.version.max", 3);
Services.prefs.setIntPref("security.tls.version.min", 3);
const LOW_TLS_VERSION = "https://tls1.example.com/";
const {TabStateFlusher} = Cu.import("resource:///modules/sessionstore/TabStateFlusher.jsm", {});
const ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
add_task(function* checkReturnToPreviousPage() {
info("Loading a TLS page that isn't supported, ensure we have a fix button and clicking it then loads the page");
let browser;
let pageLoaded;
yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => {
gBrowser.selectedTab = gBrowser.addTab(LOW_TLS_VERSION);
browser = gBrowser.selectedBrowser;
pageLoaded = BrowserTestUtils.waitForErrorPage(browser);
}, false);
info("Loading and waiting for the net error");
yield pageLoaded;
// NB: This code assumes that the error page and the test page load in the
// same process. If this test starts to fail, it could be because they load
// in different processes.
yield ContentTask.spawn(browser, LOW_TLS_VERSION, function* (LOW_TLS_VERSION_) {
ok(content.document.getElementById("prefResetButton").getBoundingClientRect().left >= 0,
"Should have a visible button");
ok(content.document.documentURI.startsWith("about:neterror"), "Should be showing error page");
let doc = content.document;
let prefResetButton = doc.getElementById("prefResetButton");
is(prefResetButton.getAttribute("autofocus"), "true", "prefResetButton has autofocus");
prefResetButton.click();
yield ContentTaskUtils.waitForEvent(this, "pageshow", true);
is(content.document.documentURI, LOW_TLS_VERSION_, "Should not be showing page");
});
yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
});

View file

@ -1,26 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
//
// Whitelisting this test.
// As part of bug 1077403, the leaking uncaught rejection should be fixed.
//
thisTestLeaksUncaughtRejectionsAndShouldBeFixed("TypeError: window.location is null");
add_task(function* checkIdentityOfAboutSupport() {
let tab = gBrowser.loadOneTab("about:support", {
referrerURI: null,
inBackground: false,
allowThirdPartyFixup: false,
relatedToCurrent: false,
skipAnimation: true,
allowMixedContent: false
});
yield promiseTabLoaded(tab);
let identityBox = document.getElementById("identity-box");
is(identityBox.className, "chromeUI", "Should know that we're chrome.");
gBrowser.removeTab(tab);
});

View file

@ -1,82 +0,0 @@
add_task(function *() {
yield pushPrefs(["ui.key.contentAccess", 5], ["ui.key.chromeAccess", 5]);
const gPageURL1 = "data:text/html,<body><p>" +
"<button id='button' accesskey='y'>Button</button>" +
"<input id='checkbox' type='checkbox' accesskey='z'>Checkbox" +
"</p></body>";
let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, gPageURL1);
tab1.linkedBrowser.messageManager.loadFrameScript("data:,(" + childHandleFocus.toString() + ")();", false);
Services.focus.clearFocus(window);
// Press an accesskey in the child document while the chrome is focused.
let focusedId = yield performAccessKey("y");
is(focusedId, "button", "button accesskey");
// Press an accesskey in the child document while the content document is focused.
focusedId = yield performAccessKey("z");
is(focusedId, "checkbox", "checkbox accesskey");
// Add an element with an accesskey to the chrome and press its accesskey while the chrome is focused.
let newButton = document.createElement("button");
newButton.id = "chromebutton";
newButton.setAttribute("accesskey", "z");
document.documentElement.appendChild(newButton);
Services.focus.clearFocus(window);
focusedId = yield performAccessKeyForChrome("z");
is(focusedId, "chromebutton", "chromebutton accesskey");
// Add a second tab and ensure that accesskey from the first tab is not used.
const gPageURL2 = "data:text/html,<body>" +
"<button id='tab2button' accesskey='y'>Button in Tab 2</button>" +
"</body>";
let tab2 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, gPageURL2);
tab2.linkedBrowser.messageManager.loadFrameScript("data:,(" + childHandleFocus.toString() + ")();", false);
Services.focus.clearFocus(window);
focusedId = yield performAccessKey("y");
is(focusedId, "tab2button", "button accesskey in tab2");
// Press the accesskey for the chrome element while the content document is focused.
focusedId = yield performAccessKeyForChrome("z");
is(focusedId, "chromebutton", "chromebutton accesskey");
newButton.parentNode.removeChild(newButton);
gBrowser.removeTab(tab1);
gBrowser.removeTab(tab2);
});
function childHandleFocus() {
content.document.body.firstChild.addEventListener("focus", function focused(event) {
let focusedElement = content.document.activeElement;
focusedElement.blur();
sendAsyncMessage("Test:FocusFromAccessKey", { focus: focusedElement.id })
}, true);
}
function performAccessKey(key)
{
return new Promise(resolve => {
let mm = gBrowser.selectedBrowser.messageManager;
mm.addMessageListener("Test:FocusFromAccessKey", function listenForFocus(msg) {
mm.removeMessageListener("Test:FocusFromAccessKey", listenForFocus);
resolve(msg.data.focus);
});
EventUtils.synthesizeKey(key, { altKey: true, shiftKey: true });
});
}
// This version is used when a chrome elemnt is expected to be found for an accesskey.
function* performAccessKeyForChrome(key, inChild)
{
let waitFocusChangePromise = BrowserTestUtils.waitForEvent(document, "focus", true);
EventUtils.synthesizeKey(key, { altKey: true, shiftKey: true });
yield waitFocusChangePromise;
return document.activeElement.id;
}

View file

@ -1,50 +0,0 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Test adding a certificate exception by attempting to browse to a site with
// a bad certificate, being redirected to the internal about:certerror page,
// using the button contained therein to load the certificate exception
// dialog, using that to add an exception, and finally successfully visiting
// the site, including showing the right identity box and control center icons.
add_task(function* () {
yield BrowserTestUtils.openNewForegroundTab(gBrowser);
yield loadBadCertPage("https://expired.example.com");
checkControlPanelIcons();
let certOverrideService = Cc["@mozilla.org/security/certoverride;1"]
.getService(Ci.nsICertOverrideService);
certOverrideService.clearValidityOverride("expired.example.com", -1);
yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
});
// Check for the correct icons in the identity box and control center.
function checkControlPanelIcons() {
let { gIdentityHandler } = gBrowser.ownerGlobal;
gIdentityHandler._identityBox.click();
document.getElementById("identity-popup-security-expander").click();
is_element_visible(document.getElementById("connection-icon"), "Should see connection icon");
let connectionIconImage = gBrowser.ownerGlobal
.getComputedStyle(document.getElementById("connection-icon"), "")
.getPropertyValue("list-style-image");
let securityViewBG = gBrowser.ownerGlobal
.getComputedStyle(document.getElementById("identity-popup-securityView"), "")
.getPropertyValue("background-image");
let securityContentBG = gBrowser.ownerGlobal
.getComputedStyle(document.getElementById("identity-popup-security-content"), "")
.getPropertyValue("background-image");
is(connectionIconImage,
"url(\"chrome://browser/skin/connection-mixed-passive-loaded.svg#icon\")",
"Using expected icon image in the identity block");
is(securityViewBG,
"url(\"chrome://browser/skin/connection-mixed-passive-loaded.svg#icon\")",
"Using expected icon image in the Control Center main view");
is(securityContentBG,
"url(\"chrome://browser/skin/connection-mixed-passive-loaded.svg#icon\")",
"Using expected icon image in the Control Center subview");
gIdentityHandler._identityPopup.hidden = true;
}

View file

@ -1,81 +0,0 @@
var testData = [
{ desc: "No path",
action: "http://example.com/",
param: "q",
},
{ desc: "With path",
action: "http://example.com/new-path-here/",
param: "q",
},
{ desc: "No action",
action: "",
param: "q",
},
{ desc: "With Query String",
action: "http://example.com/search?oe=utf-8",
param: "q",
},
];
add_task(function*() {
const TEST_URL = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URL);
let count = 0;
for (let method of ["GET", "POST"]) {
for (let {desc, action, param } of testData) {
info(`Running ${method} keyword test '${desc}'`);
let id = `keyword-form-${count++}`;
let contextMenu = document.getElementById("contentAreaContextMenu");
let contextMenuPromise =
BrowserTestUtils.waitForEvent(contextMenu, "popupshown")
.then(() => gContextMenuContentData.popupNode);
yield ContentTask.spawn(tab.linkedBrowser,
{ action, param, method, id }, function* (args) {
let doc = content.document;
let form = doc.createElement("form");
form.id = args.id;
form.method = args.method;
form.action = args.action;
let element = doc.createElement("input");
element.setAttribute("type", "text");
element.setAttribute("name", args.param);
form.appendChild(element);
doc.body.appendChild(form);
});
yield BrowserTestUtils.synthesizeMouseAtCenter(`#${id} > input`,
{ type : "contextmenu", button : 2 },
tab.linkedBrowser);
let target = yield contextMenuPromise;
yield new Promise(resolve => {
let url = action || tab.linkedBrowser.currentURI.spec;
let mm = tab.linkedBrowser.messageManager;
let onMessage = (message) => {
mm.removeMessageListener("ContextMenu:SearchFieldBookmarkData:Result", onMessage);
if (method == "GET") {
ok(message.data.spec.endsWith(`${param}=%s`),
`Check expected url for field named ${param} and action ${action}`);
} else {
is(message.data.spec, url,
`Check expected url for field named ${param} and action ${action}`);
is(message.data.postData, `${param}%3D%25s`,
`Check expected POST data for field named ${param} and action ${action}`);
}
resolve();
};
mm.addMessageListener("ContextMenu:SearchFieldBookmarkData:Result", onMessage);
mm.sendAsyncMessage("ContextMenu:SearchFieldBookmarkData", null, { target });
});
let popupHiddenPromise = BrowserTestUtils.waitForEvent(contextMenu, "popuphidden");
contextMenu.hidePopup();
yield popupHiddenPromise;
}
}
yield BrowserTestUtils.removeTab(tab);
});

View file

@ -1,206 +0,0 @@
var Ci = Components.interfaces;
const gCompleteState = Ci.nsIWebProgressListener.STATE_STOP +
Ci.nsIWebProgressListener.STATE_IS_NETWORK;
var gFrontProgressListener = {
onProgressChange: function (aWebProgress, aRequest,
aCurSelfProgress, aMaxSelfProgress,
aCurTotalProgress, aMaxTotalProgress) {
},
onStateChange: function (aWebProgress, aRequest, aStateFlags, aStatus) {
var state = "onStateChange";
info("FrontProgress: " + state + " 0x" + aStateFlags.toString(16));
ok(gFrontNotificationsPos < gFrontNotifications.length, "Got an expected notification for the front notifications listener");
is(state, gFrontNotifications[gFrontNotificationsPos], "Got a notification for the front notifications listener");
gFrontNotificationsPos++;
},
onLocationChange: function (aWebProgress, aRequest, aLocationURI, aFlags) {
var state = "onLocationChange";
info("FrontProgress: " + state + " " + aLocationURI.spec);
ok(gFrontNotificationsPos < gFrontNotifications.length, "Got an expected notification for the front notifications listener");
is(state, gFrontNotifications[gFrontNotificationsPos], "Got a notification for the front notifications listener");
gFrontNotificationsPos++;
},
onStatusChange: function (aWebProgress, aRequest, aStatus, aMessage) {
},
onSecurityChange: function (aWebProgress, aRequest, aState) {
var state = "onSecurityChange";
info("FrontProgress: " + state + " 0x" + aState.toString(16));
ok(gFrontNotificationsPos < gFrontNotifications.length, "Got an expected notification for the front notifications listener");
is(state, gFrontNotifications[gFrontNotificationsPos], "Got a notification for the front notifications listener");
gFrontNotificationsPos++;
}
}
var gAllProgressListener = {
onStateChange: function (aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) {
var state = "onStateChange";
info("AllProgress: " + state + " 0x" + aStateFlags.toString(16));
ok(aBrowser == gTestBrowser, state + " notification came from the correct browser");
ok(gAllNotificationsPos < gAllNotifications.length, "Got an expected notification for the all notifications listener");
is(state, gAllNotifications[gAllNotificationsPos], "Got a notification for the all notifications listener");
gAllNotificationsPos++;
if ((aStateFlags & gCompleteState) == gCompleteState) {
ok(gAllNotificationsPos == gAllNotifications.length, "Saw the expected number of notifications");
ok(gFrontNotificationsPos == gFrontNotifications.length, "Saw the expected number of frontnotifications");
executeSoon(gNextTest);
}
},
onLocationChange: function (aBrowser, aWebProgress, aRequest, aLocationURI,
aFlags) {
var state = "onLocationChange";
info("AllProgress: " + state + " " + aLocationURI.spec);
ok(aBrowser == gTestBrowser, state + " notification came from the correct browser");
ok(gAllNotificationsPos < gAllNotifications.length, "Got an expected notification for the all notifications listener");
is(state, gAllNotifications[gAllNotificationsPos], "Got a notification for the all notifications listener");
gAllNotificationsPos++;
},
onStatusChange: function (aBrowser, aWebProgress, aRequest, aStatus, aMessage) {
var state = "onStatusChange";
ok(aBrowser == gTestBrowser, state + " notification came from the correct browser");
},
onSecurityChange: function (aBrowser, aWebProgress, aRequest, aState) {
var state = "onSecurityChange";
info("AllProgress: " + state + " 0x" + aState.toString(16));
ok(aBrowser == gTestBrowser, state + " notification came from the correct browser");
ok(gAllNotificationsPos < gAllNotifications.length, "Got an expected notification for the all notifications listener");
is(state, gAllNotifications[gAllNotificationsPos], "Got a notification for the all notifications listener");
gAllNotificationsPos++;
}
}
var gFrontNotifications, gAllNotifications, gFrontNotificationsPos, gAllNotificationsPos;
var gBackgroundTab, gForegroundTab, gBackgroundBrowser, gForegroundBrowser, gTestBrowser;
var gTestPage = "/browser/browser/base/content/test/general/alltabslistener.html";
const kBasePage = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
var gNextTest;
function test() {
waitForExplicitFinish();
gBackgroundTab = gBrowser.addTab();
gForegroundTab = gBrowser.addTab();
gBackgroundBrowser = gBrowser.getBrowserForTab(gBackgroundTab);
gForegroundBrowser = gBrowser.getBrowserForTab(gForegroundTab);
gBrowser.selectedTab = gForegroundTab;
// We must wait until a page has completed loading before
// starting tests or we get notifications from that
let promises = [
waitForDocLoadComplete(gBackgroundBrowser),
waitForDocLoadComplete(gForegroundBrowser)
];
gBackgroundBrowser.loadURI(kBasePage);
gForegroundBrowser.loadURI(kBasePage);
Promise.all(promises).then(startTest1);
}
function runTest(browser, url, next) {
gFrontNotificationsPos = 0;
gAllNotificationsPos = 0;
gNextTest = next;
gTestBrowser = browser;
browser.loadURI(url);
}
function startTest1() {
info("\nTest 1");
gBrowser.addProgressListener(gFrontProgressListener);
gBrowser.addTabsProgressListener(gAllProgressListener);
gAllNotifications = [
"onStateChange",
"onLocationChange",
"onSecurityChange",
"onStateChange"
];
gFrontNotifications = gAllNotifications;
runTest(gForegroundBrowser, "http://example.org" + gTestPage, startTest2);
}
function startTest2() {
info("\nTest 2");
gAllNotifications = [
"onStateChange",
"onLocationChange",
"onSecurityChange",
"onSecurityChange",
"onStateChange"
];
gFrontNotifications = gAllNotifications;
runTest(gForegroundBrowser, "https://example.com" + gTestPage, startTest3);
}
function startTest3() {
info("\nTest 3");
gAllNotifications = [
"onStateChange",
"onLocationChange",
"onSecurityChange",
"onStateChange"
];
gFrontNotifications = [];
runTest(gBackgroundBrowser, "http://example.org" + gTestPage, startTest4);
}
function startTest4() {
info("\nTest 4");
gAllNotifications = [
"onStateChange",
"onLocationChange",
"onSecurityChange",
"onSecurityChange",
"onStateChange"
];
gFrontNotifications = [];
runTest(gBackgroundBrowser, "https://example.com" + gTestPage, startTest5);
}
function startTest5() {
info("\nTest 5");
// Switch the foreground browser
[gForegroundBrowser, gBackgroundBrowser] = [gBackgroundBrowser, gForegroundBrowser];
[gForegroundTab, gBackgroundTab] = [gBackgroundTab, gForegroundTab];
// Avoid the onLocationChange this will fire
gBrowser.removeProgressListener(gFrontProgressListener);
gBrowser.selectedTab = gForegroundTab;
gBrowser.addProgressListener(gFrontProgressListener);
gAllNotifications = [
"onStateChange",
"onLocationChange",
"onSecurityChange",
"onStateChange"
];
gFrontNotifications = gAllNotifications;
runTest(gForegroundBrowser, "http://example.org" + gTestPage, startTest6);
}
function startTest6() {
info("\nTest 6");
gAllNotifications = [
"onStateChange",
"onLocationChange",
"onSecurityChange",
"onStateChange"
];
gFrontNotifications = [];
runTest(gBackgroundBrowser, "http://example.org" + gTestPage, finishTest);
}
function finishTest() {
gBrowser.removeProgressListener(gFrontProgressListener);
gBrowser.removeTabsProgressListener(gAllProgressListener);
gBrowser.removeTab(gBackgroundTab);
gBrowser.removeTab(gForegroundTab);
finish();
}

View file

@ -1,504 +0,0 @@
const PAGE = "https://example.com/browser/browser/base/content/test/general/file_mediaPlayback.html";
const TABATTR_REMOVAL_PREFNAME = "browser.tabs.delayHidingAudioPlayingIconMS";
const INITIAL_TABATTR_REMOVAL_DELAY_MS = Services.prefs.getIntPref(TABATTR_REMOVAL_PREFNAME);
function* wait_for_tab_playing_event(tab, expectPlaying) {
if (tab.soundPlaying == expectPlaying) {
ok(true, "The tab should " + (expectPlaying ? "" : "not ") + "be playing");
return true;
}
return yield BrowserTestUtils.waitForEvent(tab, "TabAttrModified", false, (event) => {
if (event.detail.changed.includes("soundplaying")) {
is(tab.hasAttribute("soundplaying"), expectPlaying, "The tab should " + (expectPlaying ? "" : "not ") + "be playing");
is(tab.soundPlaying, expectPlaying, "The tab should " + (expectPlaying ? "" : "not ") + "be playing");
return true;
}
return false;
});
}
function* play(tab) {
let browser = tab.linkedBrowser;
yield ContentTask.spawn(browser, {}, function* () {
let audio = content.document.querySelector("audio");
audio.play();
});
yield wait_for_tab_playing_event(tab, true);
}
function* pause(tab, options) {
ok(tab.hasAttribute("soundplaying"), "The tab should have the soundplaying attribute when pause() is called");
let extendedDelay = options && options.extendedDelay;
if (extendedDelay) {
// Use 10s to remove possibility of race condition with attr removal.
Services.prefs.setIntPref(TABATTR_REMOVAL_PREFNAME, 10000);
}
try {
let browser = tab.linkedBrowser;
let awaitDOMAudioPlaybackStopped =
BrowserTestUtils.waitForEvent(browser, "DOMAudioPlaybackStopped", "DOMAudioPlaybackStopped event should get fired after pause");
let awaitTabPausedAttrModified =
wait_for_tab_playing_event(tab, false);
yield ContentTask.spawn(browser, {}, function* () {
let audio = content.document.querySelector("audio");
audio.pause();
});
if (extendedDelay) {
ok(tab.hasAttribute("soundplaying"), "The tab should still have the soundplaying attribute immediately after pausing");
yield awaitDOMAudioPlaybackStopped;
ok(tab.hasAttribute("soundplaying"), "The tab should still have the soundplaying attribute immediately after DOMAudioPlaybackStopped");
}
yield awaitTabPausedAttrModified;
ok(!tab.hasAttribute("soundplaying"), "The tab should not have the soundplaying attribute after the timeout has resolved");
} finally {
// Make sure other tests don't timeout if an exception gets thrown above.
// Need to use setIntPref instead of clearUserPref because prefs_general.js
// overrides the default value to help this and other tests run faster.
Services.prefs.setIntPref(TABATTR_REMOVAL_PREFNAME, INITIAL_TABATTR_REMOVAL_DELAY_MS);
}
}
function disable_non_test_mouse(disable) {
let utils = window.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowUtils);
utils.disableNonTestMouseEvents(disable);
}
function* hover_icon(icon, tooltip) {
disable_non_test_mouse(true);
let popupShownPromise = BrowserTestUtils.waitForEvent(tooltip, "popupshown");
EventUtils.synthesizeMouse(icon, 1, 1, {type: "mouseover"});
EventUtils.synthesizeMouse(icon, 2, 2, {type: "mousemove"});
EventUtils.synthesizeMouse(icon, 3, 3, {type: "mousemove"});
EventUtils.synthesizeMouse(icon, 4, 4, {type: "mousemove"});
return popupShownPromise;
}
function leave_icon(icon) {
EventUtils.synthesizeMouse(icon, 0, 0, {type: "mouseout"});
EventUtils.synthesizeMouseAtCenter(document.documentElement, {type: "mousemove"});
EventUtils.synthesizeMouseAtCenter(document.documentElement, {type: "mousemove"});
EventUtils.synthesizeMouseAtCenter(document.documentElement, {type: "mousemove"});
disable_non_test_mouse(false);
}
function* test_tooltip(icon, expectedTooltip, isActiveTab) {
let tooltip = document.getElementById("tabbrowser-tab-tooltip");
yield hover_icon(icon, tooltip);
if (isActiveTab) {
// The active tab should have the keybinding shortcut in the tooltip.
// We check this by ensuring that the strings are not equal but the expected
// message appears in the beginning.
isnot(tooltip.getAttribute("label"), expectedTooltip, "Tooltips should not be equal");
is(tooltip.getAttribute("label").indexOf(expectedTooltip), 0, "Correct tooltip expected");
} else {
is(tooltip.getAttribute("label"), expectedTooltip, "Tooltips should not be equal");
}
leave_icon(icon);
}
// The set of tabs which have ever had their mute state changed.
// Used to determine whether the tab should have a muteReason value.
let everMutedTabs = new WeakSet();
function get_wait_for_mute_promise(tab, expectMuted) {
return BrowserTestUtils.waitForEvent(tab, "TabAttrModified", false, event => {
if (event.detail.changed.includes("muted")) {
is(tab.hasAttribute("muted"), expectMuted, "The tab should " + (expectMuted ? "" : "not ") + "be muted");
is(tab.muted, expectMuted, "The tab muted property " + (expectMuted ? "" : "not ") + "be true");
if (expectMuted || everMutedTabs.has(tab)) {
everMutedTabs.add(tab);
is(tab.muteReason, null, "The tab should have a null muteReason value");
} else {
is(tab.muteReason, undefined, "The tab should have an undefined muteReason value");
}
return true;
}
return false;
});
}
function* test_mute_tab(tab, icon, expectMuted) {
let mutedPromise = test_mute_keybinding(tab, expectMuted);
let activeTab = gBrowser.selectedTab;
let tooltip = document.getElementById("tabbrowser-tab-tooltip");
yield hover_icon(icon, tooltip);
EventUtils.synthesizeMouseAtCenter(icon, {button: 0});
leave_icon(icon);
is(gBrowser.selectedTab, activeTab, "Clicking on mute should not change the currently selected tab");
return mutedPromise;
}
function get_tab_state(tab) {
const ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
return JSON.parse(ss.getTabState(tab));
}
function* test_muting_using_menu(tab, expectMuted) {
// Show the popup menu
let contextMenu = document.getElementById("tabContextMenu");
let popupShownPromise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
EventUtils.synthesizeMouseAtCenter(tab, {type: "contextmenu", button: 2});
yield popupShownPromise;
// Check the menu
let expectedLabel = expectMuted ? "Unmute Tab" : "Mute Tab";
let toggleMute = document.getElementById("context_toggleMuteTab");
is(toggleMute.label, expectedLabel, "Correct label expected");
is(toggleMute.accessKey, "M", "Correct accessKey expected");
is(toggleMute.hasAttribute("muted"), expectMuted, "Should have the correct state for the muted attribute");
ok(!toggleMute.hasAttribute("soundplaying"), "Should not have the soundplaying attribute");
yield play(tab);
is(toggleMute.hasAttribute("muted"), expectMuted, "Should have the correct state for the muted attribute");
ok(toggleMute.hasAttribute("soundplaying"), "Should have the soundplaying attribute");
yield pause(tab);
is(toggleMute.hasAttribute("muted"), expectMuted, "Should have the correct state for the muted attribute");
ok(!toggleMute.hasAttribute("soundplaying"), "Should not have the soundplaying attribute");
// Click on the menu and wait for the tab to be muted.
let mutedPromise = get_wait_for_mute_promise(tab, !expectMuted);
let popupHiddenPromise = BrowserTestUtils.waitForEvent(contextMenu, "popuphidden");
EventUtils.synthesizeMouseAtCenter(toggleMute, {});
yield popupHiddenPromise;
yield mutedPromise;
}
function* test_playing_icon_on_tab(tab, browser, isPinned) {
let icon = document.getAnonymousElementByAttribute(tab, "anonid",
isPinned ? "overlay-icon" : "soundplaying-icon");
let isActiveTab = tab === gBrowser.selectedTab;
yield play(tab);
yield test_tooltip(icon, "Mute tab", isActiveTab);
ok(!("muted" in get_tab_state(tab)), "No muted attribute should be persisted");
ok(!("muteReason" in get_tab_state(tab)), "No muteReason property should be persisted");
yield test_mute_tab(tab, icon, true);
ok("muted" in get_tab_state(tab), "Muted attribute should be persisted");
ok("muteReason" in get_tab_state(tab), "muteReason property should be persisted");
yield test_tooltip(icon, "Unmute tab", isActiveTab);
yield test_mute_tab(tab, icon, false);
ok(!("muted" in get_tab_state(tab)), "No muted attribute should be persisted");
ok(!("muteReason" in get_tab_state(tab)), "No muteReason property should be persisted");
yield test_tooltip(icon, "Mute tab", isActiveTab);
yield test_mute_tab(tab, icon, true);
yield pause(tab);
ok(tab.hasAttribute("muted") &&
!tab.hasAttribute("soundplaying"), "Tab should still be muted but not playing");
ok(tab.muted && !tab.soundPlaying, "Tab should still be muted but not playing");
yield test_tooltip(icon, "Unmute tab", isActiveTab);
yield test_mute_tab(tab, icon, false);
ok(!tab.hasAttribute("muted") &&
!tab.hasAttribute("soundplaying"), "Tab should not be be muted or playing");
ok(!tab.muted && !tab.soundPlaying, "Tab should not be be muted or playing");
// Make sure it's possible to mute using the context menu.
yield test_muting_using_menu(tab, false);
// Make sure it's possible to unmute using the context menu.
yield test_muting_using_menu(tab, true);
}
function* test_swapped_browser_while_playing(oldTab, newBrowser) {
ok(oldTab.hasAttribute("muted"), "Expected the correct muted attribute on the old tab");
is(oldTab.muteReason, null, "Expected the correct muteReason attribute on the old tab");
ok(oldTab.hasAttribute("soundplaying"), "Expected the correct soundplaying attribute on the old tab");
let newTab = gBrowser.getTabForBrowser(newBrowser);
let AttrChangePromise = BrowserTestUtils.waitForEvent(newTab, "TabAttrModified", false, event => {
return event.detail.changed.includes("soundplaying") &&
event.detail.changed.includes("muted");
});
gBrowser.swapBrowsersAndCloseOther(newTab, oldTab);
yield AttrChangePromise;
ok(newTab.hasAttribute("muted"), "Expected the correct muted attribute on the new tab");
is(newTab.muteReason, null, "Expected the correct muteReason property on the new tab");
ok(newTab.hasAttribute("soundplaying"), "Expected the correct soundplaying attribute on the new tab");
let icon = document.getAnonymousElementByAttribute(newTab, "anonid",
"soundplaying-icon");
yield test_tooltip(icon, "Unmute tab", true);
}
function* test_swapped_browser_while_not_playing(oldTab, newBrowser) {
ok(oldTab.hasAttribute("muted"), "Expected the correct muted attribute on the old tab");
is(oldTab.muteReason, null, "Expected the correct muteReason property on the old tab");
ok(!oldTab.hasAttribute("soundplaying"), "Expected the correct soundplaying attribute on the old tab");
let newTab = gBrowser.getTabForBrowser(newBrowser);
let AttrChangePromise = BrowserTestUtils.waitForEvent(newTab, "TabAttrModified", false, event => {
return event.detail.changed.includes("muted");
});
let AudioPlaybackPromise = new Promise(resolve => {
let observer = (subject, topic, data) => {
ok(false, "Should not see an audio-playback notification");
};
Services.obs.addObserver(observer, "audiochannel-activity-normal", false);
setTimeout(() => {
Services.obs.removeObserver(observer, "audiochannel-activity-normal");
resolve();
}, 100);
});
gBrowser.swapBrowsersAndCloseOther(newTab, oldTab);
yield AttrChangePromise;
ok(newTab.hasAttribute("muted"), "Expected the correct muted attribute on the new tab");
is(newTab.muteReason, null, "Expected the correct muteReason property on the new tab");
ok(!newTab.hasAttribute("soundplaying"), "Expected the correct soundplaying attribute on the new tab");
// Wait to see if an audio-playback event is dispatched.
yield AudioPlaybackPromise;
ok(newTab.hasAttribute("muted"), "Expected the correct muted attribute on the new tab");
is(newTab.muteReason, null, "Expected the correct muteReason property on the new tab");
ok(!newTab.hasAttribute("soundplaying"), "Expected the correct soundplaying attribute on the new tab");
let icon = document.getAnonymousElementByAttribute(newTab, "anonid",
"soundplaying-icon");
yield test_tooltip(icon, "Unmute tab", true);
}
function* test_browser_swapping(tab, browser) {
// First, test swapping with a playing but muted tab.
yield play(tab);
let icon = document.getAnonymousElementByAttribute(tab, "anonid",
"soundplaying-icon");
yield test_mute_tab(tab, icon, true);
yield BrowserTestUtils.withNewTab({
gBrowser,
url: "about:blank",
}, function*(newBrowser) {
yield test_swapped_browser_while_playing(tab, newBrowser)
// Now, test swapping with a muted but not playing tab.
// Note that the tab remains muted, so we only need to pause playback.
tab = gBrowser.getTabForBrowser(newBrowser);
yield pause(tab);
yield BrowserTestUtils.withNewTab({
gBrowser,
url: "about:blank",
}, secondAboutBlankBrowser => test_swapped_browser_while_not_playing(tab, secondAboutBlankBrowser));
});
}
function* test_click_on_pinned_tab_after_mute() {
function* taskFn(browser) {
let tab = gBrowser.getTabForBrowser(browser);
gBrowser.selectedTab = originallySelectedTab;
isnot(tab, gBrowser.selectedTab, "Sanity check, the tab should not be selected!");
// Steps to reproduce the bug:
// Pin the tab.
gBrowser.pinTab(tab);
// Start playback and wait for it to finish.
yield play(tab);
// Mute the tab.
let icon = document.getAnonymousElementByAttribute(tab, "anonid", "overlay-icon");
yield test_mute_tab(tab, icon, true);
// Pause playback and wait for it to finish.
yield pause(tab);
// Unmute tab.
yield test_mute_tab(tab, icon, false);
// Now click on the tab.
let image = document.getAnonymousElementByAttribute(tab, "anonid", "tab-icon-image");
EventUtils.synthesizeMouseAtCenter(image, {button: 0});
is(tab, gBrowser.selectedTab, "Tab switch should be successful");
// Cleanup.
gBrowser.unpinTab(tab);
gBrowser.selectedTab = originallySelectedTab;
}
let originallySelectedTab = gBrowser.selectedTab;
yield BrowserTestUtils.withNewTab({
gBrowser,
url: PAGE
}, taskFn);
}
// This test only does something useful in e10s!
function* test_cross_process_load() {
function* taskFn(browser) {
let tab = gBrowser.getTabForBrowser(browser);
// Start playback and wait for it to finish.
yield play(tab);
let soundPlayingStoppedPromise = BrowserTestUtils.waitForEvent(tab, "TabAttrModified", false,
event => event.detail.changed.includes("soundplaying")
);
// Go to a different process.
browser.loadURI("about:");
yield BrowserTestUtils.browserLoaded(browser);
yield soundPlayingStoppedPromise;
ok(!tab.hasAttribute("soundplaying"), "Tab should not be playing sound any more");
ok(!tab.soundPlaying, "Tab should not be playing sound any more");
}
yield BrowserTestUtils.withNewTab({
gBrowser,
url: PAGE
}, taskFn);
}
function* test_mute_keybinding() {
function* test_muting_using_keyboard(tab) {
let mutedPromise = get_wait_for_mute_promise(tab, true);
EventUtils.synthesizeKey("m", {ctrlKey: true});
yield mutedPromise;
mutedPromise = get_wait_for_mute_promise(tab, false);
EventUtils.synthesizeKey("m", {ctrlKey: true});
yield mutedPromise;
}
function* taskFn(browser) {
let tab = gBrowser.getTabForBrowser(browser);
// Make sure it's possible to mute before the tab is playing.
yield test_muting_using_keyboard(tab);
// Start playback and wait for it to finish.
yield play(tab);
// Make sure it's possible to mute after the tab is playing.
yield test_muting_using_keyboard(tab);
// Pause playback and wait for it to finish.
yield pause(tab);
// Make sure things work if the tab is pinned.
gBrowser.pinTab(tab);
// Make sure it's possible to mute before the tab is playing.
yield test_muting_using_keyboard(tab);
// Start playback and wait for it to finish.
yield play(tab);
// Make sure it's possible to mute after the tab is playing.
yield test_muting_using_keyboard(tab);
gBrowser.unpinTab(tab);
}
yield BrowserTestUtils.withNewTab({
gBrowser,
url: PAGE
}, taskFn);
}
function* test_on_browser(browser) {
let tab = gBrowser.getTabForBrowser(browser);
// Test the icon in a normal tab.
yield test_playing_icon_on_tab(tab, browser, false);
gBrowser.pinTab(tab);
// Test the icon in a pinned tab.
yield test_playing_icon_on_tab(tab, browser, true);
gBrowser.unpinTab(tab);
// Retest with another browser in the foreground tab
if (gBrowser.selectedBrowser.currentURI.spec == PAGE) {
yield BrowserTestUtils.withNewTab({
gBrowser,
url: "data:text/html,test"
}, () => test_on_browser(browser));
} else {
yield test_browser_swapping(tab, browser);
}
}
function* test_delayed_tabattr_removal() {
function* taskFn(browser) {
let tab = gBrowser.getTabForBrowser(browser);
yield play(tab);
// Extend the delay to guarantee the soundplaying attribute
// is not removed from the tab when audio is stopped. Without
// the extended delay the attribute could be removed in the
// same tick and the test wouldn't catch that this broke.
yield pause(tab, {extendedDelay: true});
}
yield BrowserTestUtils.withNewTab({
gBrowser,
url: PAGE
}, taskFn);
}
add_task(function*() {
yield new Promise((resolve) => {
SpecialPowers.pushPrefEnv({"set": [
["browser.tabs.showAudioPlayingIcon", true],
]}, resolve);
});
});
requestLongerTimeout(2);
add_task(function* test_page() {
yield BrowserTestUtils.withNewTab({
gBrowser,
url: PAGE
}, test_on_browser);
});
add_task(test_click_on_pinned_tab_after_mute);
add_task(test_cross_process_load);
add_task(test_mute_keybinding);
add_task(test_delayed_tabattr_removal);

View file

@ -1,42 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/
*/
add_task(function* () {
let firstLocation = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
yield BrowserTestUtils.openNewForegroundTab(gBrowser, firstLocation);
yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
// Push the state before maximizing the window and clicking below.
content.history.pushState("page2", "page2", "page2");
// While in the child process, add a listener for the popstate event here. This
// event will fire when the mouse click happens.
content.addEventListener("popstate", function onPopState() {
content.removeEventListener("popstate", onPopState, false);
sendAsyncMessage("Test:PopStateOccurred", { location: content.document.location.href });
}, false);
});
window.maximize();
// Find where the nav-bar is vertically.
var navBar = document.getElementById("nav-bar");
var boundingRect = navBar.getBoundingClientRect();
var yPixel = boundingRect.top + Math.floor(boundingRect.height / 2);
var xPixel = 0; // Use the first pixel of the screen since it is maximized.
let resultLocation = yield new Promise(resolve => {
messageManager.addMessageListener("Test:PopStateOccurred", function statePopped(message) {
messageManager.removeMessageListener("Test:PopStateOccurred", statePopped);
resolve(message.data.location);
});
EventUtils.synthesizeMouseAtPoint(xPixel, yPixel, {}, window);
});
is(resultLocation, firstLocation, "Clicking the first pixel should have navigated back.");
window.restore();
gBrowser.removeCurrentTab();
});

View file

@ -1,76 +0,0 @@
const TEST_PAGE = "http://mochi.test:8888/browser/browser/base/content/test/general/file_double_close_tab.html";
var expectingDialog = false;
var wantToClose = true;
var resolveDialogPromise;
function onTabModalDialogLoaded(node) {
ok(expectingDialog, "Should be expecting this dialog.");
expectingDialog = false;
if (wantToClose) {
// This accepts the dialog, closing it
node.Dialog.ui.button0.click();
} else {
// This keeps the page open
node.Dialog.ui.button1.click();
}
if (resolveDialogPromise) {
resolveDialogPromise();
}
}
SpecialPowers.pushPrefEnv({"set": [["dom.require_user_interaction_for_beforeunload", false]]});
// Listen for the dialog being created
Services.obs.addObserver(onTabModalDialogLoaded, "tabmodal-dialog-loaded", false);
registerCleanupFunction(() => {
Services.prefs.clearUserPref("browser.tabs.warnOnClose");
Services.obs.removeObserver(onTabModalDialogLoaded, "tabmodal-dialog-loaded");
});
add_task(function* closeLastTabInWindow() {
let newWin = yield promiseOpenAndLoadWindow({}, true);
let firstTab = newWin.gBrowser.selectedTab;
yield promiseTabLoadEvent(firstTab, TEST_PAGE);
let windowClosedPromise = promiseWindowWillBeClosed(newWin);
expectingDialog = true;
// close tab:
document.getAnonymousElementByAttribute(firstTab, "anonid", "close-button").click();
yield windowClosedPromise;
ok(!expectingDialog, "There should have been a dialog.");
ok(newWin.closed, "Window should be closed.");
});
add_task(function* closeWindowWithMultipleTabsIncludingOneBeforeUnload() {
Services.prefs.setBoolPref("browser.tabs.warnOnClose", false);
let newWin = yield promiseOpenAndLoadWindow({}, true);
let firstTab = newWin.gBrowser.selectedTab;
yield promiseTabLoadEvent(firstTab, TEST_PAGE);
yield promiseTabLoadEvent(newWin.gBrowser.addTab(), "http://example.com/");
let windowClosedPromise = promiseWindowWillBeClosed(newWin);
expectingDialog = true;
newWin.BrowserTryToCloseWindow();
yield windowClosedPromise;
ok(!expectingDialog, "There should have been a dialog.");
ok(newWin.closed, "Window should be closed.");
Services.prefs.clearUserPref("browser.tabs.warnOnClose");
});
add_task(function* closeWindoWithSingleTabTwice() {
let newWin = yield promiseOpenAndLoadWindow({}, true);
let firstTab = newWin.gBrowser.selectedTab;
yield promiseTabLoadEvent(firstTab, TEST_PAGE);
let windowClosedPromise = promiseWindowWillBeClosed(newWin);
expectingDialog = true;
wantToClose = false;
let firstDialogShownPromise = new Promise((resolve, reject) => { resolveDialogPromise = resolve; });
document.getAnonymousElementByAttribute(firstTab, "anonid", "close-button").click();
yield firstDialogShownPromise;
info("Got initial dialog, now trying again");
expectingDialog = true;
wantToClose = true;
resolveDialogPromise = null;
document.getAnonymousElementByAttribute(firstTab, "anonid", "close-button").click();
yield windowClosedPromise;
ok(!expectingDialog, "There should have been a dialog.");
ok(newWin.closed, "Window should be closed.");
});

View file

@ -1,11 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
Cu.import("resource://gre/modules/NetUtil.jsm");
function test() {
var file = new File([new Blob(['test'], {type: 'text/plain'})], "test-name");
var url = URL.createObjectURL(file);
var channel = NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true});
is(channel.contentDispositionFilename, 'test-name', "filename matches");
}

View file

@ -1,101 +0,0 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Test that visiting a site pinned with HPKP headers does not succeed when it
// uses a certificate with a key not in the pinset. This should result in an
// about:neterror page
// Also verify that removal of the HPKP headers succeeds (via HPKP headers)
// and that after removal the visit to the site with the previously
// unauthorized pins succeeds.
//
// This test required three certs to be created in build/pgo/certs:
// 1. A new trusted root:
// a. certutil -S -s "Alternate trusted authority" -s "CN=Alternate Trusted Authority" -t "C,," -x -m 1 -v 120 -n "alternateTrustedAuthority" -Z SHA256 -g 2048 -2 -d .
// b. (export) certutil -L -d . -n "alternateTrustedAuthority" -a -o alternateroot.ca
// (files ended in .ca are added as trusted roots by the mochitest harness)
// 2. A good pinning server cert (signed by the pgo root):
// certutil -S -n "dynamicPinningGood" -s "CN=dynamic-pinning.example.com" -c "pgo temporary ca" -t "P,," -k rsa -g 2048 -Z SHA256 -m 8939454 -v 120 -8 "*.include-subdomains.pinning-dynamic.example.com,*.pinning-dynamic.example.com" -d .
// 3. A certificate with a different issuer, so as to cause a key pinning violation."
// certutil -S -n "dynamicPinningBad" -s "CN=bad.include-subdomains.pinning-dynamic.example.com" -c "alternateTrustedAuthority" -t "P,," -k rsa -g 2048 -Z SHA256 -m 893945439 -v 120 -8 "bad.include-subdomains.pinning-dynamic.example.com" -d .
const gSSService = Cc["@mozilla.org/ssservice;1"]
.getService(Ci.nsISiteSecurityService);
const gIOService = Cc["@mozilla.org/network/io-service;1"]
.getService(Ci.nsIIOService);
const kPinningDomain = "include-subdomains.pinning-dynamic.example.com";
const khpkpPinninEnablePref = "security.cert_pinning.process_headers_from_non_builtin_roots";
const kpkpEnforcementPref = "security.cert_pinning.enforcement_level";
const kBadPinningDomain = "bad.include-subdomains.pinning-dynamic.example.com";
const kURLPath = "/browser/browser/base/content/test/general/pinning_headers.sjs?";
function test() {
waitForExplicitFinish();
// Enable enforcing strict pinning and processing headers from
// non-builtin roots.
Services.prefs.setIntPref(kpkpEnforcementPref, 2);
Services.prefs.setBoolPref(khpkpPinninEnablePref, true);
registerCleanupFunction(function () {
Services.prefs.clearUserPref(kpkpEnforcementPref);
Services.prefs.clearUserPref(khpkpPinninEnablePref);
let uri = gIOService.newURI("https://" + kPinningDomain, null, null);
gSSService.removeState(Ci.nsISiteSecurityService.HEADER_HPKP, uri, 0);
});
whenNewTabLoaded(window, loadPinningPage);
}
// Start by making a successful connection to a domain that will pin a site
function loadPinningPage() {
BrowserTestUtils.loadURI(gBrowser.selectedBrowser, "https://" + kPinningDomain + kURLPath + "valid").then(function() {
gBrowser.selectedBrowser.addEventListener("load",
successfulPinningPageListener,
true);
});
}
// After the site is pinned try to load with a subdomain site that should
// fail to validate
var successfulPinningPageListener = {
handleEvent: function() {
gBrowser.selectedBrowser.removeEventListener("load", this, true);
BrowserTestUtils.loadURI(gBrowser.selectedBrowser, "https://" + kBadPinningDomain).then(function() {
return promiseErrorPageLoaded(gBrowser.selectedBrowser);
}).then(errorPageLoaded);
}
};
// The browser should load about:neterror, when this happens, proceed
// to load the pinning domain again, this time removing the pinning information
function errorPageLoaded() {
ContentTask.spawn(gBrowser.selectedBrowser, null, function*() {
let textElement = content.document.getElementById("errorShortDescText");
let text = textElement.innerHTML;
ok(text.indexOf("MOZILLA_PKIX_ERROR_KEY_PINNING_FAILURE") > 0,
"Got a pinning error page");
}).then(function() {
BrowserTestUtils.loadURI(gBrowser.selectedBrowser, "https://" + kPinningDomain + kURLPath + "zeromaxagevalid").then(function() {
return BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
}).then(pinningRemovalLoaded);
});
}
// After the pinning information has been removed (successful load) proceed
// to load again with the invalid pin domain.
function pinningRemovalLoaded() {
BrowserTestUtils.loadURI(gBrowser.selectedBrowser, "https://" + kBadPinningDomain).then(function() {
return BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
}).then(badPinningPageLoaded);
}
// Finally, we should successfully load
// https://bad.include-subdomains.pinning-dynamic.example.com.
function badPinningPageLoaded() {
BrowserTestUtils.removeTab(gBrowser.selectedTab).then(function() {
ok(true, "load complete");
finish();
});
}

View file

@ -1,431 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
/**
* Test opening and closing the bookmarks panel.
*/
let bookmarkPanel = document.getElementById("editBookmarkPanel");
let bookmarkStar = document.getElementById("bookmarks-menu-button");
let bookmarkPanelTitle = document.getElementById("editBookmarkPanelTitle");
let editBookmarkPanelRemoveButtonRect;
StarUI._closePanelQuickForTesting = true;
function* test_bookmarks_popup({isNewBookmark, popupShowFn, popupEditFn,
shouldAutoClose, popupHideFn, isBookmarkRemoved}) {
yield BrowserTestUtils.withNewTab({gBrowser, url: "about:home"}, function*(browser) {
try {
if (!isNewBookmark) {
yield PlacesUtils.bookmarks.insert({
parentGuid: PlacesUtils.bookmarks.unfiledGuid,
url: "about:home",
title: "Home Page"
});
}
info(`BookmarkingUI.status is ${BookmarkingUI.status}`);
yield BrowserTestUtils.waitForCondition(
() => BookmarkingUI.status != BookmarkingUI.STATUS_UPDATING,
"BookmarkingUI should not be updating");
is(bookmarkStar.hasAttribute("starred"), !isNewBookmark,
"Page should only be starred prior to popupshown if editing bookmark");
is(bookmarkPanel.state, "closed", "Panel should be 'closed' to start test");
let shownPromise = promisePopupShown(bookmarkPanel);
yield popupShowFn(browser);
yield shownPromise;
is(bookmarkPanel.state, "open", "Panel should be 'open' after shownPromise is resolved");
editBookmarkPanelRemoveButtonRect =
document.getElementById("editBookmarkPanelRemoveButton").getBoundingClientRect();
if (popupEditFn) {
yield popupEditFn();
}
let bookmarks = [];
yield PlacesUtils.bookmarks.fetch({url: "about:home"}, bm => bookmarks.push(bm));
is(bookmarks.length, 1, "Only one bookmark should exist");
is(bookmarkStar.getAttribute("starred"), "true", "Page is starred");
is(bookmarkPanelTitle.value,
isNewBookmark ?
gNavigatorBundle.getString("editBookmarkPanel.pageBookmarkedTitle") :
gNavigatorBundle.getString("editBookmarkPanel.editBookmarkTitle"),
"title should match isEditingBookmark state");
if (!shouldAutoClose) {
yield new Promise(resolve => setTimeout(resolve, 400));
is(bookmarkPanel.state, "open", "Panel should still be 'open' for non-autoclose");
}
let hiddenPromise = promisePopupHidden(bookmarkPanel);
if (popupHideFn) {
yield popupHideFn();
}
yield hiddenPromise;
is(bookmarkStar.hasAttribute("starred"), !isBookmarkRemoved,
"Page is starred after closing");
} finally {
let bookmark = yield PlacesUtils.bookmarks.fetch({url: "about:home"});
is(!!bookmark, !isBookmarkRemoved,
"bookmark should not be present if a panel action should've removed it");
if (bookmark) {
yield PlacesUtils.bookmarks.remove(bookmark);
}
}
});
}
add_task(function* panel_shown_for_new_bookmarks_and_autocloses() {
yield test_bookmarks_popup({
isNewBookmark: true,
popupShowFn() {
bookmarkStar.click();
},
shouldAutoClose: true,
isBookmarkRemoved: false,
});
});
add_task(function* panel_shown_once_for_doubleclick_on_new_bookmark_star_and_autocloses() {
yield test_bookmarks_popup({
isNewBookmark: true,
popupShowFn() {
EventUtils.synthesizeMouse(bookmarkStar, 10, 10, { clickCount: 2 },
window);
},
shouldAutoClose: true,
isBookmarkRemoved: false,
});
});
add_task(function* panel_shown_once_for_slow_doubleclick_on_new_bookmark_star_and_autocloses() {
todo(false, "bug 1250267, may need to add some tracking state to " +
"browser-places.js for this.");
return;
/*
yield test_bookmarks_popup({
isNewBookmark: true,
*popupShowFn() {
EventUtils.synthesizeMouse(bookmarkStar, 10, 10, window);
yield new Promise(resolve => setTimeout(resolve, 300));
EventUtils.synthesizeMouse(bookmarkStar, 10, 10, window);
},
shouldAutoClose: true,
isBookmarkRemoved: false,
});
*/
});
add_task(function* panel_shown_for_keyboardshortcut_on_new_bookmark_star_and_autocloses() {
yield test_bookmarks_popup({
isNewBookmark: true,
popupShowFn() {
EventUtils.synthesizeKey("D", {accelKey: true}, window);
},
shouldAutoClose: true,
isBookmarkRemoved: false,
});
});
add_task(function* panel_shown_for_new_bookmarks_mousemove_mouseout() {
yield test_bookmarks_popup({
isNewBookmark: true,
popupShowFn() {
bookmarkStar.click();
},
*popupEditFn() {
let mouseMovePromise = BrowserTestUtils.waitForEvent(bookmarkPanel, "mousemove");
EventUtils.synthesizeMouseAtCenter(bookmarkPanel, {type: "mousemove"});
info("Waiting for mousemove event");
yield mouseMovePromise;
info("Got mousemove event");
yield new Promise(resolve => setTimeout(resolve, 400));
is(bookmarkPanel.state, "open", "Panel should still be open on mousemove");
},
*popupHideFn() {
let mouseOutPromise = BrowserTestUtils.waitForEvent(bookmarkPanel, "mouseout");
EventUtils.synthesizeMouse(bookmarkPanel, 0, 0, {type: "mouseout"});
EventUtils.synthesizeMouseAtCenter(document.documentElement, {type: "mousemove"});
info("Waiting for mouseout event");
yield mouseOutPromise;
info("Got mouseout event, should autoclose now");
},
shouldAutoClose: false,
isBookmarkRemoved: false,
});
});
add_task(function* panel_shown_for_new_bookmark_no_autoclose_close_with_ESC() {
yield test_bookmarks_popup({
isNewBookmark: false,
popupShowFn() {
bookmarkStar.click();
},
shouldAutoClose: false,
popupHideFn() {
EventUtils.synthesizeKey("VK_ESCAPE", {accelKey: true}, window);
},
isBookmarkRemoved: false,
});
});
add_task(function* panel_shown_for_editing_no_autoclose_close_with_ESC() {
yield test_bookmarks_popup({
isNewBookmark: false,
popupShowFn() {
bookmarkStar.click();
},
shouldAutoClose: false,
popupHideFn() {
EventUtils.synthesizeKey("VK_ESCAPE", {accelKey: true}, window);
},
isBookmarkRemoved: false,
});
});
add_task(function* panel_shown_for_new_bookmark_keypress_no_autoclose() {
yield test_bookmarks_popup({
isNewBookmark: true,
popupShowFn() {
bookmarkStar.click();
},
popupEditFn() {
EventUtils.sendChar("VK_TAB", window);
},
shouldAutoClose: false,
popupHideFn() {
bookmarkPanel.hidePopup();
},
isBookmarkRemoved: false,
});
});
add_task(function* panel_shown_for_new_bookmark_compositionstart_no_autoclose() {
yield test_bookmarks_popup({
isNewBookmark: true,
popupShowFn() {
bookmarkStar.click();
},
*popupEditFn() {
let compositionStartPromise = BrowserTestUtils.waitForEvent(bookmarkPanel, "compositionstart");
EventUtils.synthesizeComposition({ type: "compositionstart" }, window);
info("Waiting for compositionstart event");
yield compositionStartPromise;
info("Got compositionstart event");
},
shouldAutoClose: false,
popupHideFn() {
EventUtils.synthesizeComposition({ type: "compositioncommitasis" });
bookmarkPanel.hidePopup();
},
isBookmarkRemoved: false,
});
});
add_task(function* panel_shown_for_new_bookmark_compositionstart_mouseout_no_autoclose() {
yield test_bookmarks_popup({
isNewBookmark: true,
popupShowFn() {
bookmarkStar.click();
},
*popupEditFn() {
let mouseMovePromise = BrowserTestUtils.waitForEvent(bookmarkPanel, "mousemove");
EventUtils.synthesizeMouseAtCenter(bookmarkPanel, {type: "mousemove"});
info("Waiting for mousemove event");
yield mouseMovePromise;
info("Got mousemove event");
let compositionStartPromise = BrowserTestUtils.waitForEvent(bookmarkPanel, "compositionstart");
EventUtils.synthesizeComposition({ type: "compositionstart" }, window);
info("Waiting for compositionstart event");
yield compositionStartPromise;
info("Got compositionstart event");
let mouseOutPromise = BrowserTestUtils.waitForEvent(bookmarkPanel, "mouseout");
EventUtils.synthesizeMouse(bookmarkPanel, 0, 0, {type: "mouseout"});
EventUtils.synthesizeMouseAtCenter(document.documentElement, {type: "mousemove"});
info("Waiting for mouseout event");
yield mouseOutPromise;
info("Got mouseout event, but shouldn't run autoclose");
},
shouldAutoClose: false,
popupHideFn() {
EventUtils.synthesizeComposition({ type: "compositioncommitasis" });
bookmarkPanel.hidePopup();
},
isBookmarkRemoved: false,
});
});
add_task(function* panel_shown_for_new_bookmark_compositionend_no_autoclose() {
yield test_bookmarks_popup({
isNewBookmark: true,
popupShowFn() {
bookmarkStar.click();
},
*popupEditFn() {
let mouseMovePromise = BrowserTestUtils.waitForEvent(bookmarkPanel, "mousemove");
EventUtils.synthesizeMouseAtCenter(bookmarkPanel, {type: "mousemove"});
info("Waiting for mousemove event");
yield mouseMovePromise;
info("Got mousemove event");
EventUtils.synthesizeComposition({ type: "compositioncommit", data: "committed text" });
},
popupHideFn() {
bookmarkPanel.hidePopup();
},
shouldAutoClose: false,
isBookmarkRemoved: false,
});
});
add_task(function* contextmenu_new_bookmark_keypress_no_autoclose() {
yield test_bookmarks_popup({
isNewBookmark: true,
*popupShowFn(browser) {
let contextMenu = document.getElementById("contentAreaContextMenu");
let awaitPopupShown = BrowserTestUtils.waitForEvent(contextMenu,
"popupshown");
let awaitPopupHidden = BrowserTestUtils.waitForEvent(contextMenu,
"popuphidden");
yield BrowserTestUtils.synthesizeMouseAtCenter("body", {
type: "contextmenu",
button: 2
}, browser);
yield awaitPopupShown;
document.getElementById("context-bookmarkpage").click();
contextMenu.hidePopup();
yield awaitPopupHidden;
},
popupEditFn() {
EventUtils.sendChar("VK_TAB", window);
},
shouldAutoClose: false,
popupHideFn() {
bookmarkPanel.hidePopup();
},
isBookmarkRemoved: false,
});
});
add_task(function* bookmarks_menu_new_bookmark_remove_bookmark() {
yield test_bookmarks_popup({
isNewBookmark: true,
popupShowFn(browser) {
document.getElementById("menu_bookmarkThisPage").doCommand();
},
shouldAutoClose: true,
popupHideFn() {
document.getElementById("editBookmarkPanelRemoveButton").click();
},
isBookmarkRemoved: true,
});
});
add_task(function* ctrl_d_edit_bookmark_remove_bookmark() {
yield test_bookmarks_popup({
isNewBookmark: false,
popupShowFn(browser) {
EventUtils.synthesizeKey("D", {accelKey: true}, window);
},
shouldAutoClose: true,
popupHideFn() {
document.getElementById("editBookmarkPanelRemoveButton").click();
},
isBookmarkRemoved: true,
});
});
add_task(function* enter_on_remove_bookmark_should_remove_bookmark() {
if (AppConstants.platform == "macosx") {
// "Full Keyboard Access" is disabled by default, and thus doesn't allow
// keyboard navigation to the "Remove Bookmarks" button by default.
return;
}
yield test_bookmarks_popup({
isNewBookmark: true,
popupShowFn(browser) {
EventUtils.synthesizeKey("D", {accelKey: true}, window);
},
shouldAutoClose: true,
popupHideFn() {
while (!document.activeElement ||
document.activeElement.id != "editBookmarkPanelRemoveButton") {
EventUtils.sendChar("VK_TAB", window);
}
EventUtils.sendChar("VK_RETURN", window);
},
isBookmarkRemoved: true,
});
});
add_task(function* ctrl_d_new_bookmark_mousedown_mouseout_no_autoclose() {
yield test_bookmarks_popup({
isNewBookmark: true,
popupShowFn(browser) {
EventUtils.synthesizeKey("D", {accelKey: true}, window);
},
*popupEditFn() {
let mouseMovePromise = BrowserTestUtils.waitForEvent(bookmarkPanel, "mousemove");
EventUtils.synthesizeMouseAtCenter(bookmarkPanel, {type: "mousemove"});
info("Waiting for mousemove event");
yield mouseMovePromise;
info("Got mousemove event");
yield new Promise(resolve => setTimeout(resolve, 400));
is(bookmarkPanel.state, "open", "Panel should still be open on mousemove");
EventUtils.synthesizeMouseAtCenter(bookmarkPanelTitle, {button: 1, type: "mousedown"});
let mouseOutPromise = BrowserTestUtils.waitForEvent(bookmarkPanel, "mouseout");
EventUtils.synthesizeMouse(bookmarkPanel, 0, 0, {type: "mouseout"});
EventUtils.synthesizeMouseAtCenter(document.documentElement, {type: "mousemove"});
info("Waiting for mouseout event");
yield mouseOutPromise;
},
shouldAutoClose: false,
popupHideFn() {
document.getElementById("editBookmarkPanelRemoveButton").click();
},
isBookmarkRemoved: true,
});
});
add_task(function* mouse_hovering_panel_should_prevent_autoclose() {
if (AppConstants.platform != "win") {
// This test requires synthesizing native mouse movement which is
// best supported on Windows.
return;
}
yield test_bookmarks_popup({
isNewBookmark: true,
*popupShowFn(browser) {
yield new Promise(resolve => {
EventUtils.synthesizeNativeMouseMove(
document.documentElement,
editBookmarkPanelRemoveButtonRect.left,
editBookmarkPanelRemoveButtonRect.top,
resolve);
});
EventUtils.synthesizeKey("D", {accelKey: true}, window);
},
shouldAutoClose: false,
popupHideFn() {
document.getElementById("editBookmarkPanelRemoveButton").click();
},
isBookmarkRemoved: true,
});
});
registerCleanupFunction(function() {
delete StarUI._closePanelQuickForTesting;
});

View file

@ -1,98 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// This file is tests for the default titles that new bookmarks get.
var tests = [
// Common page.
['http://example.com/browser/browser/base/content/test/general/dummy_page.html',
'Dummy test page'],
// Data URI.
['data:text/html;charset=utf-8,<title>test%20data:%20url</title>',
'test data: url'],
// about:neterror
['data:application/vnd.mozilla.xul+xml,',
'data:application/vnd.mozilla.xul+xml,'],
// about:certerror
['https://untrusted.example.com/somepage.html',
'https://untrusted.example.com/somepage.html']
];
add_task(function* () {
gBrowser.selectedTab = gBrowser.addTab();
let browser = gBrowser.selectedBrowser;
browser.stop(); // stop the about:blank load.
// Test that a bookmark of each URI gets the corresponding default title.
for (let i = 0; i < tests.length; ++i) {
let [uri, title] = tests[i];
let promiseLoaded = promisePageLoaded(browser);
BrowserTestUtils.loadURI(browser, uri);
yield promiseLoaded;
yield checkBookmark(uri, title);
}
// Network failure test: now that dummy_page.html is in history, bookmarking
// it should give the last known page title as the default bookmark title.
// Simulate a network outage with offline mode. (Localhost is still
// accessible in offline mode, so disable the test proxy as well.)
BrowserOffline.toggleOfflineStatus();
let proxy = Services.prefs.getIntPref('network.proxy.type');
Services.prefs.setIntPref('network.proxy.type', 0);
registerCleanupFunction(function () {
BrowserOffline.toggleOfflineStatus();
Services.prefs.setIntPref('network.proxy.type', proxy);
});
// LOAD_FLAGS_BYPASS_CACHE isn't good enough. So clear the cache.
Services.cache2.clear();
let [uri, title] = tests[0];
let promiseLoaded = promisePageLoaded(browser);
BrowserTestUtils.loadURI(browser, uri);
yield promiseLoaded;
// The offline mode test is only good if the page failed to load.
yield ContentTask.spawn(browser, null, function() {
is(content.document.documentURI.substring(0, 14), 'about:neterror',
"Offline mode successfully simulated network outage.");
});
yield checkBookmark(uri, title);
gBrowser.removeCurrentTab();
});
// Bookmark the current page and confirm that the new bookmark has the expected
// title. (Then delete the bookmark.)
function* checkBookmark(uri, expected_title) {
is(gBrowser.selectedBrowser.currentURI.spec, uri,
"Trying to bookmark the expected uri");
let promiseBookmark = promiseOnBookmarkItemAdded(gBrowser.selectedBrowser.currentURI);
PlacesCommandHook.bookmarkCurrentPage(false);
yield promiseBookmark;
let id = PlacesUtils.getMostRecentBookmarkForURI(PlacesUtils._uri(uri));
ok(id > 0, "Found the expected bookmark");
let title = PlacesUtils.bookmarks.getItemTitle(id);
is(title, expected_title, "Bookmark got a good default title.");
PlacesUtils.bookmarks.removeItem(id);
}
// BrowserTestUtils.browserLoaded doesn't work for the about pages, so use a
// custom page load listener.
function promisePageLoaded(browser)
{
return ContentTask.spawn(browser, null, function* () {
yield ContentTaskUtils.waitForEvent(this, "DOMContentLoaded", true,
(event) => {
return event.originalTarget === content.document &&
event.target.location.href !== "about:blank"
});
});
}

View file

@ -1,54 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const TEST_PAGE = "http://example.org/browser/browser/base/content/test/general/zoom_test.html";
var gTab1, gTab2, gLevel1;
function test() {
waitForExplicitFinish();
Task.spawn(function* () {
gTab1 = gBrowser.addTab();
gTab2 = gBrowser.addTab();
yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab1);
yield FullZoomHelper.load(gTab1, TEST_PAGE);
yield FullZoomHelper.load(gTab2, TEST_PAGE);
}).then(zoomTab1, FullZoomHelper.failAndContinue(finish));
}
function zoomTab1() {
Task.spawn(function* () {
is(gBrowser.selectedTab, gTab1, "Tab 1 is selected");
FullZoomHelper.zoomTest(gTab1, 1, "Initial zoom of tab 1 should be 1");
FullZoomHelper.zoomTest(gTab2, 1, "Initial zoom of tab 2 should be 1");
let browser1 = gBrowser.getBrowserForTab(gTab1);
yield BrowserTestUtils.synthesizeMouse(null, 10, 10, {
wheel: true, ctrlKey: true, deltaY: -1, deltaMode: WheelEvent.DOM_DELTA_LINE
}, browser1);
info("Waiting for tab 1 to be zoomed");
yield promiseWaitForCondition(() => {
gLevel1 = ZoomManager.getZoomForBrowser(browser1);
return gLevel1 > 1;
});
yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab2);
FullZoomHelper.zoomTest(gTab2, gLevel1, "Tab 2 should have zoomed along with tab 1");
}).then(finishTest, FullZoomHelper.failAndContinue(finish));
}
function finishTest() {
Task.spawn(function* () {
yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab1);
yield FullZoom.reset();
yield FullZoomHelper.removeTabAndWaitForLocationChange(gTab1);
yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab2);
yield FullZoom.reset();
yield FullZoomHelper.removeTabAndWaitForLocationChange(gTab2);
}).then(finish, FullZoomHelper.failAndContinue(finish));
}

View file

@ -1,68 +0,0 @@
// Test that the Mixed Content Doorhanger Action to re-enable protection works
const PREF_ACTIVE = "security.mixed_content.block_active_content";
var origBlockActive;
add_task(function* () {
registerCleanupFunction(function() {
Services.prefs.setBoolPref(PREF_ACTIVE, origBlockActive);
gBrowser.removeCurrentTab();
});
// Store original preferences so we can restore settings after testing
origBlockActive = Services.prefs.getBoolPref(PREF_ACTIVE);
// Make sure mixed content blocking is on
Services.prefs.setBoolPref(PREF_ACTIVE, true);
var url =
"https://test1.example.com/browser/browser/base/content/test/general/" +
"file_bug1045809_1.html";
let tab = gBrowser.selectedTab = gBrowser.addTab();
// Test 1: mixed content must be blocked
yield promiseTabLoadEvent(tab, url);
yield* test1(gBrowser.getBrowserForTab(tab));
yield promiseTabLoadEvent(tab);
// Test 2: mixed content must NOT be blocked
yield* test2(gBrowser.getBrowserForTab(tab));
// Test 3: mixed content must be blocked again
yield promiseTabLoadEvent(tab);
yield* test3(gBrowser.getBrowserForTab(tab));
});
function* test1(gTestBrowser) {
assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
yield ContentTask.spawn(gTestBrowser, null, function() {
var x = content.document.getElementsByTagName("iframe")[0].contentDocument.getElementById("mixedContentContainer");
is(x, null, "Mixed Content is NOT to be found in Test1");
});
// Disable Mixed Content Protection for the page (and reload)
gIdentityHandler.disableMixedContentProtection();
}
function* test2(gTestBrowser) {
assertMixedContentBlockingState(gTestBrowser, {activeLoaded: true, activeBlocked: false, passiveLoaded: false});
yield ContentTask.spawn(gTestBrowser, null, function() {
var x = content.document.getElementsByTagName("iframe")[0].contentDocument.getElementById("mixedContentContainer");
isnot(x, null, "Mixed Content is to be found in Test2");
});
// Re-enable Mixed Content Protection for the page (and reload)
gIdentityHandler.enableMixedContentProtection();
}
function* test3(gTestBrowser) {
assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
yield ContentTask.spawn(gTestBrowser, null, function() {
var x = content.document.getElementsByTagName("iframe")[0].contentDocument.getElementById("mixedContentContainer");
is(x, null, "Mixed Content is NOT to be found in Test3");
});
}

View file

@ -1,36 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
add_task(function* () {
// Test that changing the URL in a pinned tab works correctly
let TEST_LINK_INITIAL = "about:";
let TEST_LINK_CHANGED = "about:support";
let appTab = gBrowser.addTab(TEST_LINK_INITIAL);
let browser = appTab.linkedBrowser;
yield BrowserTestUtils.browserLoaded(browser);
gBrowser.pinTab(appTab);
is(appTab.pinned, true, "Tab was successfully pinned");
let initialTabsNo = gBrowser.tabs.length;
let goButton = document.getElementById("urlbar-go-button");
gBrowser.selectedTab = appTab;
gURLBar.focus();
gURLBar.value = TEST_LINK_CHANGED;
goButton.click();
yield BrowserTestUtils.browserLoaded(browser);
is(appTab.linkedBrowser.currentURI.spec, TEST_LINK_CHANGED,
"New page loaded in the app tab");
is(gBrowser.tabs.length, initialTabsNo, "No additional tabs were opened");
});
registerCleanupFunction(function () {
gBrowser.removeTab(gBrowser.selectedTab);
});

View file

@ -1,73 +0,0 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
* Tests for Bug 1261299
* Test that the service menu code path is called properly and the
* current selection (transferable) is cached properly on the parent process.
*/
add_task(function* test_content_and_chrome_selection()
{
let testPage =
'data:text/html,' +
'<textarea id="textarea">Write something here</textarea>';
let DOMWindowUtils = EventUtils._getDOMWindowUtils(window);
let selectedText;
let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, testPage);
yield BrowserTestUtils.synthesizeMouse("#textarea", 0, 0, {}, gBrowser.selectedBrowser);
yield BrowserTestUtils.synthesizeKey("KEY_ArrowRight",
{shiftKey: true, ctrlKey: true, code: "ArrowRight"}, gBrowser.selectedBrowser);
selectedText = DOMWindowUtils.GetSelectionAsPlaintext();
is(selectedText, "Write something here", "The macOS services got the selected content text");
gURLBar.value = "test.mozilla.org";
yield gURLBar.focus();
yield BrowserTestUtils.synthesizeKey("KEY_ArrowRight",
{shiftKey: true, ctrlKey: true, code: "ArrowRight"}, gBrowser.selectedBrowser);
selectedText = DOMWindowUtils.GetSelectionAsPlaintext();
is(selectedText, "test.mozilla.org", "The macOS services got the selected chrome text");
yield BrowserTestUtils.removeTab(tab);
});
// Test switching active selection.
// Each tab has a content selection and when you switch to that tab, its selection becomes
// active aka the current selection.
// Expect: The active selection is what is being sent to OSX service menu.
add_task(function* test_active_selection_switches_properly()
{
let testPage1 =
'data:text/html,' +
'<textarea id="textarea">Write something here</textarea>';
let testPage2 =
'data:text/html,' +
'<textarea id="textarea">Nothing available</textarea>';
let DOMWindowUtils = EventUtils._getDOMWindowUtils(window);
let selectedText;
let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, testPage1);
yield BrowserTestUtils.synthesizeMouse("#textarea", 0, 0, {}, gBrowser.selectedBrowser);
yield BrowserTestUtils.synthesizeKey("KEY_ArrowRight",
{shiftKey: true, ctrlKey: true, code: "ArrowRight"}, gBrowser.selectedBrowser);
let tab2 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, testPage2);
yield BrowserTestUtils.synthesizeMouse("#textarea", 0, 0, {}, gBrowser.selectedBrowser);
yield BrowserTestUtils.synthesizeKey("KEY_ArrowRight",
{shiftKey: true, ctrlKey: true, code: "ArrowRight"}, gBrowser.selectedBrowser);
yield BrowserTestUtils.switchTab(gBrowser, tab1);
selectedText = DOMWindowUtils.GetSelectionAsPlaintext();
is(selectedText, "Write something here", "The macOS services got the selected content text");
yield BrowserTestUtils.switchTab(gBrowser, tab2);
selectedText = DOMWindowUtils.GetSelectionAsPlaintext();
is(selectedText, "Nothing available", "The macOS services got the selected content text");
yield BrowserTestUtils.removeTab(tab1);
yield BrowserTestUtils.removeTab(tab2);
});

View file

@ -1,114 +0,0 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
* Test for Bug 1297539
* Test that the content event "pasteTransferable"
* (mozilla::EventMessage::eContentCommandPasteTransferable)
* is handled correctly for plain text and html in the remote case.
*
* Original test test_bug525389.html for command content event
* "pasteTransferable" runs only in the content process.
* This doesn't test the remote case.
*
*/
"use strict";
function getLoadContext() {
return window.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsILoadContext);
}
function getTransferableFromClipboard(asHTML) {
let trans = Cc["@mozilla.org/widget/transferable;1"].
createInstance(Ci.nsITransferable);
trans.init(getLoadContext());
if (asHTML) {
trans.addDataFlavor("text/html");
} else {
trans.addDataFlavor("text/unicode");
}
let clip = Cc["@mozilla.org/widget/clipboard;1"].getService(Ci.nsIClipboard);
clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard);
return trans;
}
function* cutCurrentSelection(elementQueryString, property, browser) {
// Cut the current selection.
yield BrowserTestUtils.synthesizeKey("x", {accelKey: true}, browser);
// The editor should be empty after cut.
yield ContentTask.spawn(browser, [elementQueryString, property],
function* ([contentElementQueryString, contentProperty]) {
let element = content.document.querySelector(contentElementQueryString);
is(element[contentProperty], "",
`${contentElementQueryString} should be empty after cut (superkey + x)`);
});
}
// Test that you are able to pasteTransferable for plain text
// which is handled by TextEditor::PasteTransferable to paste into the editor.
add_task(function* test_paste_transferable_plain_text()
{
let testPage =
'data:text/html,' +
'<textarea id="textarea">Write something here</textarea>';
yield BrowserTestUtils.withNewTab(testPage, function* (browser) {
// Select all the content in your editor element.
yield BrowserTestUtils.synthesizeMouse("#textarea", 0, 0, {}, browser);
yield BrowserTestUtils.synthesizeKey("a", {accelKey: true}, browser);
yield* cutCurrentSelection("#textarea", "value", browser);
let trans = getTransferableFromClipboard(false);
let DOMWindowUtils = EventUtils._getDOMWindowUtils(window);
DOMWindowUtils.sendContentCommandEvent("pasteTransferable", trans);
yield ContentTask.spawn(browser, null, function* () {
let textArea = content.document.querySelector('#textarea');
is(textArea.value, "Write something here",
"Send content command pasteTransferable successful");
});
});
});
// Test that you are able to pasteTransferable for html
// which is handled by HTMLEditor::PasteTransferable to paste into the editor.
//
// On Linux,
// BrowserTestUtils.synthesizeKey("a", {accelKey: true}, browser);
// doesn't seem to trigger for contenteditable which is why we use
// Selection to select the contenteditable contents.
add_task(function* test_paste_transferable_html()
{
let testPage =
'data:text/html,' +
'<div contenteditable="true"><b>Bold Text</b><i>italics</i></div>';
yield BrowserTestUtils.withNewTab(testPage, function* (browser) {
// Select all the content in your editor element.
yield BrowserTestUtils.synthesizeMouse("div", 0, 0, {}, browser);
yield ContentTask.spawn(browser, {}, function* () {
let element = content.document.querySelector("div");
let selection = content.window.getSelection();
selection.selectAllChildren(element);
});
yield* cutCurrentSelection("div", "textContent", browser);
let trans = getTransferableFromClipboard(true);
let DOMWindowUtils = EventUtils._getDOMWindowUtils(window);
DOMWindowUtils.sendContentCommandEvent("pasteTransferable", trans);
yield ContentTask.spawn(browser, null, function* () {
let textArea = content.document.querySelector('div');
is(textArea.innerHTML, "<b>Bold Text</b><i>italics</i>",
"Send content command pasteTransferable successful");
});
});
});

View file

@ -1,71 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
const { addObserver, removeObserver } = Cc["@mozilla.org/observer-service;1"].
getService(Ci.nsIObserverService);
function receive(topic) {
return new Promise((resolve, reject) => {
let timeout = setTimeout(() => {
reject(new Error("Timeout"));
}, 90000);
const observer = {
observe: subject => {
removeObserver(observer, topic);
clearTimeout(timeout);
resolve(subject);
}
};
addObserver(observer, topic, false);
});
}
add_task(function* () {
yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com");
yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
content.history.pushState({}, "2", "2.html");
});
yield receive("sessionstore-state-write-complete");
// Wait for the session data to be flushed before continuing the test
yield new Promise(resolve => SessionStore.getSessionHistory(gBrowser.selectedTab, resolve));
let backButton = document.getElementById("back-button");
let contextMenu = document.getElementById("backForwardMenu");
info("waiting for the history menu to open");
let popupShownPromise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
EventUtils.synthesizeMouseAtCenter(backButton, {type: "contextmenu", button: 2});
let event = yield popupShownPromise;
ok(true, "history menu opened");
// Wait for the session data to be flushed before continuing the test
yield new Promise(resolve => SessionStore.getSessionHistory(gBrowser.selectedTab, resolve));
is(event.target.children.length, 2, "Two history items");
let node = event.target.firstChild;
is(node.getAttribute("uri"), "http://example.com/2.html", "first item uri");
is(node.getAttribute("index"), "1", "first item index");
is(node.getAttribute("historyindex"), "0", "first item historyindex");
node = event.target.lastChild;
is(node.getAttribute("uri"), "http://example.com/", "second item uri");
is(node.getAttribute("index"), "0", "second item index");
is(node.getAttribute("historyindex"), "-1", "second item historyindex");
let popupHiddenPromise = BrowserTestUtils.waitForEvent(contextMenu, "popuphidden");
event.target.hidePopup();
yield popupHiddenPromise;
info("Hidden popup");
let onClose = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "TabClose");
yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
yield onClose;
info("Tab closed");
});

View file

@ -1,80 +0,0 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
* vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const kTestString = " hello hello \n world\nworld ";
var gTests = [
{ desc: "Urlbar strips newlines and surrounding whitespace",
element: gURLBar,
expected: kTestString.replace(/\s*\n\s*/g, '')
},
{ desc: "Searchbar replaces newlines with spaces",
element: document.getElementById('searchbar'),
expected: kTestString.replace(/\n/g, ' ')
},
];
// Test for bug 23485 and bug 321000.
// Urlbar should strip newlines,
// search bar should replace newlines with spaces.
function test() {
waitForExplicitFinish();
let cbHelper = Cc["@mozilla.org/widget/clipboardhelper;1"].
getService(Ci.nsIClipboardHelper);
// Put a multi-line string in the clipboard.
// Setting the clipboard value is an async OS operation, so we need to poll
// the clipboard for valid data before going on.
waitForClipboard(kTestString, function() { cbHelper.copyString(kTestString); },
next_test, finish);
}
function next_test() {
if (gTests.length)
test_paste(gTests.shift());
else
finish();
}
function test_paste(aCurrentTest) {
var element = aCurrentTest.element;
// Register input listener.
var inputListener = {
test: aCurrentTest,
handleEvent: function(event) {
element.removeEventListener(event.type, this, false);
is(element.value, this.test.expected, this.test.desc);
// Clear the field and go to next test.
element.value = "";
setTimeout(next_test, 0);
}
}
element.addEventListener("input", inputListener, false);
// Focus the window.
window.focus();
gBrowser.selectedBrowser.focus();
// Focus the element and wait for focus event.
info("About to focus " + element.id);
element.addEventListener("focus", function() {
element.removeEventListener("focus", arguments.callee, false);
executeSoon(function() {
// Pasting is async because the Accel+V codepath ends up going through
// nsDocumentViewer::FireClipboardEvent.
info("Pasting into " + element.id);
EventUtils.synthesizeKey("v", { accelKey: true });
});
}, false);
element.focus();
}

View file

@ -1,93 +0,0 @@
// Bug 356571 - loadOneOrMoreURIs gives up if one of the URLs has an unknown protocol
var Cr = Components.results;
var Cm = Components.manager;
// Set to true when docShell alerts for unknown protocol error
var didFail = false;
// Override Alert to avoid blocking the test due to unknown protocol error
const kPromptServiceUUID = "{6cc9c9fe-bc0b-432b-a410-253ef8bcc699}";
const kPromptServiceContractID = "@mozilla.org/embedcomp/prompt-service;1";
// Save original prompt service factory
const kPromptServiceFactory = Cm.getClassObject(Cc[kPromptServiceContractID],
Ci.nsIFactory);
var fakePromptServiceFactory = {
createInstance: function(aOuter, aIid) {
if (aOuter != null)
throw Cr.NS_ERROR_NO_AGGREGATION;
return promptService.QueryInterface(aIid);
}
};
var promptService = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsIPromptService]),
alert: function() {
didFail = true;
}
};
/* FIXME
Cm.QueryInterface(Ci.nsIComponentRegistrar)
.registerFactory(Components.ID(kPromptServiceUUID), "Prompt Service",
kPromptServiceContractID, fakePromptServiceFactory);
*/
const kCompleteState = Ci.nsIWebProgressListener.STATE_STOP +
Ci.nsIWebProgressListener.STATE_IS_NETWORK;
const kDummyPage = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
const kURIs = [
"bad://www.mozilla.org/",
kDummyPage,
kDummyPage,
];
var gProgressListener = {
_runCount: 0,
onStateChange: function (aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) {
if ((aStateFlags & kCompleteState) == kCompleteState) {
if (++this._runCount != kURIs.length)
return;
// Check we failed on unknown protocol (received an alert from docShell)
ok(didFail, "Correctly failed on unknown protocol");
// Check we opened all tabs
ok(gBrowser.tabs.length == kURIs.length, "Correctly opened all expected tabs");
finishTest();
}
}
}
function test() {
todo(false, "temp. disabled");
return; /* FIXME */
/*
waitForExplicitFinish();
// Wait for all tabs to finish loading
gBrowser.addTabsProgressListener(gProgressListener);
loadOneOrMoreURIs(kURIs.join("|"));
*/
}
function finishTest() {
// Unregister the factory so we do not leak
Cm.QueryInterface(Ci.nsIComponentRegistrar)
.unregisterFactory(Components.ID(kPromptServiceUUID),
fakePromptServiceFactory);
// Restore the original factory
Cm.QueryInterface(Ci.nsIComponentRegistrar)
.registerFactory(Components.ID(kPromptServiceUUID), "Prompt Service",
kPromptServiceContractID, kPromptServiceFactory);
// Remove the listener
gBrowser.removeTabsProgressListener(gProgressListener);
// Close opened tabs
for (var i = gBrowser.tabs.length-1; i > 0; i--)
gBrowser.removeTab(gBrowser.tabs[i]);
finish();
}

View file

@ -1,11 +0,0 @@
function test() {
var tab = gBrowser.addTab("about:blank", { skipAnimation: true });
gBrowser.removeTab(tab);
is(tab.parentNode, null, "tab removed immediately");
tab = gBrowser.addTab("about:blank", { skipAnimation: true });
gBrowser.removeTab(tab, { animate: true });
gBrowser.removeTab(tab);
is(tab.parentNode, null, "tab removed immediately when calling removeTab again after the animation was kicked off");
}

View file

@ -1,89 +0,0 @@
var gTestPage = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
var gTestImage = "http://example.org/browser/browser/base/content/test/general/moz.png";
var gTab1, gTab2, gTab3;
var gLevel;
const BACK = 0;
const FORWARD = 1;
function test() {
waitForExplicitFinish();
Task.spawn(function* () {
gTab1 = gBrowser.addTab(gTestPage);
gTab2 = gBrowser.addTab();
gTab3 = gBrowser.addTab();
yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab1);
yield FullZoomHelper.load(gTab1, gTestPage);
yield FullZoomHelper.load(gTab2, gTestPage);
}).then(secondPageLoaded, FullZoomHelper.failAndContinue(finish));
}
function secondPageLoaded() {
Task.spawn(function* () {
FullZoomHelper.zoomTest(gTab1, 1, "Initial zoom of tab 1 should be 1");
FullZoomHelper.zoomTest(gTab2, 1, "Initial zoom of tab 2 should be 1");
FullZoomHelper.zoomTest(gTab3, 1, "Initial zoom of tab 3 should be 1");
// Now have three tabs, two with the test page, one blank. Tab 1 is selected
// Zoom tab 1
FullZoom.enlarge();
gLevel = ZoomManager.getZoomForBrowser(gBrowser.getBrowserForTab(gTab1));
ok(gLevel > 1, "New zoom for tab 1 should be greater than 1");
FullZoomHelper.zoomTest(gTab2, 1, "Zooming tab 1 should not affect tab 2");
FullZoomHelper.zoomTest(gTab3, 1, "Zooming tab 1 should not affect tab 3");
yield FullZoomHelper.load(gTab3, gTestPage);
}).then(thirdPageLoaded, FullZoomHelper.failAndContinue(finish));
}
function thirdPageLoaded() {
Task.spawn(function* () {
FullZoomHelper.zoomTest(gTab1, gLevel, "Tab 1 should still be zoomed");
FullZoomHelper.zoomTest(gTab2, 1, "Tab 2 should still not be affected");
FullZoomHelper.zoomTest(gTab3, gLevel, "Tab 3 should have zoomed as it was loading in the background");
// Switching to tab 2 should update its zoom setting.
yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab2);
FullZoomHelper.zoomTest(gTab1, gLevel, "Tab 1 should still be zoomed");
FullZoomHelper.zoomTest(gTab2, gLevel, "Tab 2 should be zoomed now");
FullZoomHelper.zoomTest(gTab3, gLevel, "Tab 3 should still be zoomed");
yield FullZoomHelper.load(gTab1, gTestImage);
}).then(imageLoaded, FullZoomHelper.failAndContinue(finish));
}
function imageLoaded() {
Task.spawn(function* () {
FullZoomHelper.zoomTest(gTab1, 1, "Zoom should be 1 when image was loaded in the background");
yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab1);
FullZoomHelper.zoomTest(gTab1, 1, "Zoom should still be 1 when tab with image is selected");
}).then(imageZoomSwitch, FullZoomHelper.failAndContinue(finish));
}
function imageZoomSwitch() {
Task.spawn(function* () {
yield FullZoomHelper.navigate(BACK);
yield FullZoomHelper.navigate(FORWARD);
FullZoomHelper.zoomTest(gTab1, 1, "Tab 1 should not be zoomed when an image loads");
yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab2);
FullZoomHelper.zoomTest(gTab1, 1, "Tab 1 should still not be zoomed when deselected");
}).then(finishTest, FullZoomHelper.failAndContinue(finish));
}
var finishTestStarted = false;
function finishTest() {
Task.spawn(function* () {
ok(!finishTestStarted, "finishTest called more than once");
finishTestStarted = true;
yield FullZoomHelper.selectTabAndWaitForLocationChange(gTab1);
yield FullZoom.reset();
yield FullZoomHelper.removeTabAndWaitForLocationChange(gTab1);
yield FullZoom.reset();
yield FullZoomHelper.removeTabAndWaitForLocationChange(gTab2);
yield FullZoom.reset();
yield FullZoomHelper.removeTabAndWaitForLocationChange(gTab3);
}).then(finish, FullZoomHelper.failAndContinue(finish));
}

View file

@ -1,54 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* "TabClose" event is possibly used for closing related tabs of the current.
* "removeTab" method should work correctly even if the number of tabs are
* changed while "TabClose" event.
*/
var count = 0;
const URIS = ["about:config",
"about:plugins",
"about:buildconfig",
"data:text/html,<title>OK</title>"];
function test() {
waitForExplicitFinish();
URIS.forEach(addTab);
}
function addTab(aURI, aIndex) {
var tab = gBrowser.addTab(aURI);
if (aIndex == 0)
gBrowser.removeTab(gBrowser.tabs[0], {skipPermitUnload: true});
tab.linkedBrowser.addEventListener("load", function (event) {
event.currentTarget.removeEventListener("load", arguments.callee, true);
if (++count == URIS.length)
executeSoon(doTabsTest);
}, true);
}
function doTabsTest() {
is(gBrowser.tabs.length, URIS.length, "Correctly opened all expected tabs");
// sample of "close related tabs" feature
gBrowser.tabContainer.addEventListener("TabClose", function (event) {
event.currentTarget.removeEventListener("TabClose", arguments.callee, true);
var closedTab = event.originalTarget;
var scheme = closedTab.linkedBrowser.currentURI.scheme;
Array.slice(gBrowser.tabs).forEach(function (aTab) {
if (aTab != closedTab && aTab.linkedBrowser.currentURI.scheme == scheme)
gBrowser.removeTab(aTab, {skipPermitUnload: true});
});
}, true);
gBrowser.removeTab(gBrowser.tabs[0], {skipPermitUnload: true});
is(gBrowser.tabs.length, 1, "Related tabs are not closed unexpectedly");
gBrowser.addTab("about:blank");
gBrowser.removeTab(gBrowser.tabs[0], {skipPermitUnload: true});
finish();
}

View file

@ -1,45 +0,0 @@
add_task(function* test() {
let testPath = getRootDirectory(gTestPath);
yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" },
function* (tabBrowser) {
const URI = testPath + "file_with_favicon.html";
const expectedIcon = testPath + "file_generic_favicon.ico";
let got_favicon = Promise.defer();
let listener = {
onLinkIconAvailable(browser, iconURI) {
if (got_favicon && iconURI && browser === tabBrowser) {
got_favicon.resolve(iconURI);
got_favicon = null;
}
}
};
gBrowser.addTabsProgressListener(listener);
BrowserTestUtils.loadURI(tabBrowser, URI);
let iconURI = yield got_favicon.promise;
is(iconURI, expectedIcon, "Correct icon before pushState.");
got_favicon = Promise.defer();
got_favicon.promise.then(() => { ok(false, "shouldn't be called"); }, (e) => e);
yield ContentTask.spawn(tabBrowser, null, function() {
content.location.href += "#foo";
});
// We've navigated and shouldn't get a call to onLinkIconAvailable.
TestUtils.executeSoon(() => {
got_favicon.reject(gBrowser.getIcon(gBrowser.getTabForBrowser(tabBrowser)));
});
try {
yield got_favicon.promise;
} catch (e) {
iconURI = e;
}
is(iconURI, expectedIcon, "Correct icon after pushState.");
gBrowser.removeTabsProgressListener(listener);
});
});

View file

@ -1,83 +0,0 @@
function test() {
waitForExplicitFinish();
// XXX This looks a bit odd, but is needed to avoid throwing when removing the
// event listeners below. See bug 310955.
document.getElementById("sidebar").addEventListener("load", delayedOpenUrl, true);
SidebarUI.show("viewWebPanelsSidebar");
}
function delayedOpenUrl() {
ok(true, "Ran delayedOpenUrl");
setTimeout(openPanelUrl, 100);
}
function openPanelUrl(event) {
ok(!document.getElementById("sidebar-box").hidden, "Sidebar showing");
var sidebar = document.getElementById("sidebar");
var root = sidebar.contentDocument.documentElement;
ok(root.nodeName != "parsererror", "Sidebar is well formed");
sidebar.removeEventListener("load", delayedOpenUrl, true);
// XXX See comment above
sidebar.contentDocument.addEventListener("load", delayedRunTest, true);
var url = 'data:text/html,<div%20id="test_bug409481">Content!</div><a id="link" href="http://www.example.com/ctest">Link</a><input id="textbox">';
sidebar.contentWindow.loadWebPanel(url);
}
function delayedRunTest() {
ok(true, "Ran delayedRunTest");
setTimeout(runTest, 100);
}
function runTest(event) {
var sidebar = document.getElementById("sidebar");
sidebar.contentDocument.removeEventListener("load", delayedRunTest, true);
var browser = sidebar.contentDocument.getElementById("web-panels-browser");
var div = browser && browser.contentDocument.getElementById("test_bug409481");
ok(div && div.textContent == "Content!", "Sidebar content loaded");
var link = browser && browser.contentDocument.getElementById("link");
sidebar.contentDocument.addEventListener("popupshown", contextMenuOpened, false);
EventUtils.synthesizeMouseAtCenter(link, { type: "contextmenu", button: 2 }, browser.contentWindow);
}
function contextMenuOpened()
{
var sidebar = document.getElementById("sidebar");
sidebar.contentDocument.removeEventListener("popupshown", contextMenuOpened, false);
var copyLinkCommand = sidebar.contentDocument.getElementById("context-copylink");
copyLinkCommand.addEventListener("command", copyLinkCommandExecuted, false);
copyLinkCommand.doCommand();
}
function copyLinkCommandExecuted(event)
{
event.target.removeEventListener("command", copyLinkCommandExecuted, false);
var sidebar = document.getElementById("sidebar");
var browser = sidebar.contentDocument.getElementById("web-panels-browser");
var textbox = browser && browser.contentDocument.getElementById("textbox");
textbox.focus();
document.commandDispatcher.getControllerForCommand("cmd_paste").doCommand("cmd_paste");
is(textbox.value, "http://www.example.com/ctest", "copy link command");
sidebar.contentDocument.addEventListener("popuphidden", contextMenuClosed, false);
event.target.parentNode.hidePopup();
}
function contextMenuClosed()
{
var sidebar = document.getElementById("sidebar");
sidebar.contentDocument.removeEventListener("popuphidden", contextMenuClosed, false);
SidebarUI.hide();
ok(document.getElementById("sidebar-box").hidden, "Sidebar successfully hidden");
finish();
}

View file

@ -1,57 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
XPCOMUtils.defineLazyModuleGetter(this, "FormHistory",
"resource://gre/modules/FormHistory.jsm");
add_task(function* test() {
// This test relies on the form history being empty to start with delete
// all the items first.
yield new Promise((resolve, reject) => {
FormHistory.update({ op: "remove" },
{ handleError(error) {
reject(error);
},
handleCompletion(reason) {
if (!reason) {
resolve();
} else {
reject();
}
},
});
});
let prefService = Cc["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService);
let tempScope = {};
Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader)
.loadSubScript("chrome://browser/content/sanitize.js", tempScope);
let Sanitizer = tempScope.Sanitizer;
let s = new Sanitizer();
s.prefDomain = "privacy.cpd.";
let prefBranch = prefService.getBranch(s.prefDomain);
prefBranch.setBoolPref("cache", false);
prefBranch.setBoolPref("cookies", false);
prefBranch.setBoolPref("downloads", false);
prefBranch.setBoolPref("formdata", true);
prefBranch.setBoolPref("history", false);
prefBranch.setBoolPref("offlineApps", false);
prefBranch.setBoolPref("passwords", false);
prefBranch.setBoolPref("sessions", false);
prefBranch.setBoolPref("siteSettings", false);
// Sanitize now so we can test the baseline point.
yield s.sanitize();
ok(!gFindBar.hasTransactions, "pre-test baseline for sanitizer");
gFindBar.getElement("findbar-textbox").value = "m";
ok(gFindBar.hasTransactions, "formdata can be cleared after input");
yield s.sanitize();
is(gFindBar.getElement("findbar-textbox").value, "", "findBar textbox should be empty after sanitize");
ok(!gFindBar.hasTransactions, "No transactions after sanitize");
});

View file

@ -1,62 +0,0 @@
XPCOMUtils.defineLazyModuleGetter(this, "Feeds",
"resource:///modules/Feeds.jsm");
function test() {
var exampleUri = makeURI("http://example.com/");
var secman = Cc["@mozilla.org/scriptsecuritymanager;1"].getService(Ci.nsIScriptSecurityManager);
var principal = secman.createCodebasePrincipal(exampleUri, {});
function testIsFeed(aTitle, aHref, aType, aKnown) {
var link = { title: aTitle, href: aHref, type: aType };
return Feeds.isValidFeed(link, principal, aKnown);
}
var href = "http://example.com/feed/";
var atomType = "application/atom+xml";
var funkyAtomType = " aPPLICAtion/Atom+XML ";
var rssType = "application/rss+xml";
var funkyRssType = " Application/RSS+XML ";
var rdfType = "application/rdf+xml";
var texmlType = "text/xml";
var appxmlType = "application/xml";
var noRss = "Foo";
var rss = "RSS";
// things that should be valid
ok(testIsFeed(noRss, href, atomType, false) == atomType,
"detect Atom feed");
ok(testIsFeed(noRss, href, funkyAtomType, false) == atomType,
"clean up and detect Atom feed");
ok(testIsFeed(noRss, href, rssType, false) == rssType,
"detect RSS feed");
ok(testIsFeed(noRss, href, funkyRssType, false) == rssType,
"clean up and detect RSS feed");
// things that should not be feeds
ok(testIsFeed(noRss, href, rdfType, false) == null,
"should not detect RDF non-feed");
ok(testIsFeed(rss, href, rdfType, false) == null,
"should not detect RDF feed from type and title");
ok(testIsFeed(noRss, href, texmlType, false) == null,
"should not detect text/xml non-feed");
ok(testIsFeed(rss, href, texmlType, false) == null,
"should not detect text/xml feed from type and title");
ok(testIsFeed(noRss, href, appxmlType, false) == null,
"should not detect application/xml non-feed");
ok(testIsFeed(rss, href, appxmlType, false) == null,
"should not detect application/xml feed from type and title");
// security check only, returns cleaned up type or "application/rss+xml"
ok(testIsFeed(noRss, href, atomType, true) == atomType,
"feed security check should return Atom type");
ok(testIsFeed(noRss, href, funkyAtomType, true) == atomType,
"feed security check should return cleaned up Atom type");
ok(testIsFeed(noRss, href, rssType, true) == rssType,
"feed security check should return RSS type");
ok(testIsFeed(noRss, href, funkyRssType, true) == rssType,
"feed security check should return cleaned up RSS type");
ok(testIsFeed(noRss, href, "", true) == rssType,
"feed security check without type should return RSS type");
ok(testIsFeed(noRss, href, "garbage", true) == "garbage",
"feed security check with garbage type should return garbage");
}

View file

@ -1,43 +0,0 @@
var tabElm, zoomLevel;
function start_test_prefNotSet() {
Task.spawn(function* () {
is(ZoomManager.zoom, 1, "initial zoom level should be 1");
FullZoom.enlarge();
// capture the zoom level to test later
zoomLevel = ZoomManager.zoom;
isnot(zoomLevel, 1, "zoom level should have changed");
yield FullZoomHelper.load(gBrowser.selectedTab, "http://mochi.test:8888/browser/browser/base/content/test/general/moz.png");
}).then(continue_test_prefNotSet, FullZoomHelper.failAndContinue(finish));
}
function continue_test_prefNotSet () {
Task.spawn(function* () {
is(ZoomManager.zoom, 1, "zoom level pref should not apply to an image");
yield FullZoom.reset();
yield FullZoomHelper.load(gBrowser.selectedTab, "http://mochi.test:8888/browser/browser/base/content/test/general/zoom_test.html");
}).then(end_test_prefNotSet, FullZoomHelper.failAndContinue(finish));
}
function end_test_prefNotSet() {
Task.spawn(function* () {
is(ZoomManager.zoom, zoomLevel, "the zoom level should have persisted");
// Reset the zoom so that other tests have a fresh zoom level
yield FullZoom.reset();
yield FullZoomHelper.removeTabAndWaitForLocationChange();
finish();
});
}
function test() {
waitForExplicitFinish();
Task.spawn(function* () {
tabElm = gBrowser.addTab();
yield FullZoomHelper.selectTabAndWaitForLocationChange(tabElm);
yield FullZoomHelper.load(tabElm, "http://mochi.test:8888/browser/browser/base/content/test/general/zoom_test.html");
}).then(start_test_prefNotSet, FullZoomHelper.failAndContinue(finish));
}

View file

@ -1,30 +0,0 @@
add_task(function* () {
let loadedPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser, true);
const htmlContent = "data:text/html, <iframe src='data:text/html,text text'></iframe>";
gBrowser.loadURI(htmlContent);
yield loadedPromise;
yield ContentTask.spawn(gBrowser.selectedBrowser, { }, function* (arg) {
let frame = content.frames[0];
let sel = frame.getSelection();
let range = frame.document.createRange();
let tn = frame.document.body.childNodes[0];
range.setStart(tn, 4);
range.setEnd(tn, 5);
sel.addRange(range);
frame.focus();
});
let contentAreaContextMenu = document.getElementById("contentAreaContextMenu");
let popupShownPromise = BrowserTestUtils.waitForEvent(contentAreaContextMenu, "popupshown");
yield BrowserTestUtils.synthesizeMouse("frame", 5, 5,
{ type: "contextmenu", button: 2}, gBrowser.selectedBrowser);
yield popupShownPromise;
ok(document.getElementById("frame-sep").hidden, "'frame-sep' should be hidden if the selection contains only spaces");
let popupHiddenPromise = BrowserTestUtils.waitForEvent(contentAreaContextMenu, "popuphidden");
contentAreaContextMenu.hidePopup();
yield popupHiddenPromise;
});

View file

@ -1,32 +0,0 @@
function test() {
waitForExplicitFinish();
Task.spawn(function* () {
let testPage = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
let tab1 = gBrowser.addTab();
yield FullZoomHelper.selectTabAndWaitForLocationChange(tab1);
yield FullZoomHelper.load(tab1, testPage);
let tab2 = gBrowser.addTab();
yield FullZoomHelper.load(tab2, testPage);
FullZoom.enlarge();
let tab1Zoom = ZoomManager.getZoomForBrowser(tab1.linkedBrowser);
yield FullZoomHelper.selectTabAndWaitForLocationChange(tab2);
let tab2Zoom = ZoomManager.getZoomForBrowser(tab2.linkedBrowser);
is(tab2Zoom, tab1Zoom, "Zoom should affect background tabs");
gPrefService.setBoolPref("browser.zoom.updateBackgroundTabs", false);
yield FullZoom.reset();
gBrowser.selectedTab = tab1;
tab1Zoom = ZoomManager.getZoomForBrowser(tab1.linkedBrowser);
tab2Zoom = ZoomManager.getZoomForBrowser(tab2.linkedBrowser);
isnot(tab1Zoom, tab2Zoom, "Zoom should not affect background tabs");
if (gPrefService.prefHasUserValue("browser.zoom.updateBackgroundTabs"))
gPrefService.clearUserPref("browser.zoom.updateBackgroundTabs");
yield FullZoomHelper.removeTabAndWaitForLocationChange(tab1);
yield FullZoomHelper.removeTabAndWaitForLocationChange(tab2);
}).then(finish, FullZoomHelper.failAndContinue(finish));
}

View file

@ -1,50 +0,0 @@
function test() {
waitForExplicitFinish();
// test the main (normal) browser window
testCustomize(window, testChromeless);
}
function testChromeless() {
// test a chromeless window
var newWin = openDialog(getBrowserURL(), "_blank",
"chrome,dialog=no,location=yes,toolbar=no", "about:blank");
ok(newWin, "got new window");
whenDelayedStartupFinished(newWin, function () {
// Check that the search bar is hidden
var searchBar = newWin.BrowserSearch.searchBar;
ok(searchBar, "got search bar");
var searchBarBO = searchBar.boxObject;
is(searchBarBO.width, 0, "search bar hidden");
is(searchBarBO.height, 0, "search bar hidden");
testCustomize(newWin, function () {
newWin.close();
finish();
});
});
}
function testCustomize(aWindow, aCallback) {
var fileMenu = aWindow.document.getElementById("file-menu");
ok(fileMenu, "got file menu");
is(fileMenu.disabled, false, "file menu initially enabled");
openToolbarCustomizationUI(function () {
// Can't use the property, since the binding may have since been removed
// if the element is hidden (see bug 422590)
is(fileMenu.getAttribute("disabled"), "true",
"file menu is disabled during toolbar customization");
closeToolbarCustomizationUI(onClose, aWindow);
}, aWindow);
function onClose() {
is(fileMenu.getAttribute("disabled"), "false",
"file menu is enabled after toolbar customization");
if (aCallback)
aCallback();
}
}

View file

@ -1,138 +0,0 @@
/* Tests for proper behaviour of "Show this frame" context menu options */
// Two frames, one with text content, the other an error page
var invalidPage = 'http://127.0.0.1:55555/';
var validPage = 'http://example.com/';
var testPage = 'data:text/html,<frameset cols="400,400"><frame src="' + validPage + '"><frame src="' + invalidPage + '"></frameset>';
// Store the tab and window created in tests 2 and 3 respectively
var test2tab;
var test3window;
// We use setInterval instead of setTimeout to avoid race conditions on error doc loads
var intervalID;
function test() {
waitForExplicitFinish();
gBrowser.selectedTab = gBrowser.addTab();
gBrowser.selectedBrowser.addEventListener("load", test1Setup, true);
content.location = testPage;
}
function test1Setup() {
if (content.frames.length < 2 ||
content.frames[1].location != invalidPage)
// The error frame hasn't loaded yet
return;
gBrowser.selectedBrowser.removeEventListener("load", test1Setup, true);
var badFrame = content.frames[1];
document.popupNode = badFrame.document.firstChild;
var contentAreaContextMenu = document.getElementById("contentAreaContextMenu");
var contextMenu = new nsContextMenu(contentAreaContextMenu);
// We'd like to use another load listener here, but error pages don't fire load events
contextMenu.showOnlyThisFrame();
intervalID = setInterval(testShowOnlyThisFrame, 3000);
}
function testShowOnlyThisFrame() {
if (content.location.href == testPage)
// This is a stale event from the original page loading
return;
// We should now have loaded the error page frame content directly
// in the tab, make sure the URL is right.
clearInterval(intervalID);
is(content.location.href, invalidPage, "Should navigate to page url, not about:neterror");
// Go back to the frames page
gBrowser.addEventListener("load", test2Setup, true);
content.location = testPage;
}
function test2Setup() {
if (content.frames.length < 2 ||
content.frames[1].location != invalidPage)
// The error frame hasn't loaded yet
return;
gBrowser.removeEventListener("load", test2Setup, true);
// Now let's do the whole thing again, but this time for "Open frame in new tab"
var badFrame = content.frames[1];
document.popupNode = badFrame.document.firstChild;
var contentAreaContextMenu = document.getElementById("contentAreaContextMenu");
var contextMenu = new nsContextMenu(contentAreaContextMenu);
gBrowser.tabContainer.addEventListener("TabOpen", function (event) {
test2tab = event.target;
gBrowser.tabContainer.removeEventListener("TabOpen", arguments.callee, false);
}, false);
contextMenu.openFrameInTab();
ok(test2tab, "openFrameInTab() opened a tab");
gBrowser.selectedTab = test2tab;
intervalID = setInterval(testOpenFrameInTab, 3000);
}
function testOpenFrameInTab() {
if (gBrowser.contentDocument.location.href == "about:blank")
// Wait another cycle
return;
clearInterval(intervalID);
// We should now have the error page in a new, active tab.
is(gBrowser.contentDocument.location.href, invalidPage, "New tab should have page url, not about:neterror");
// Clear up the new tab, and punt to test 3
gBrowser.removeCurrentTab();
test3Setup();
}
function test3Setup() {
// One more time, for "Open frame in new window"
var badFrame = content.frames[1];
document.popupNode = badFrame.document.firstChild;
var contentAreaContextMenu = document.getElementById("contentAreaContextMenu");
var contextMenu = new nsContextMenu(contentAreaContextMenu);
Services.ww.registerNotification(function (aSubject, aTopic, aData) {
if (aTopic == "domwindowopened")
test3window = aSubject;
Services.ww.unregisterNotification(arguments.callee);
});
contextMenu.openFrame();
intervalID = setInterval(testOpenFrame, 3000);
}
function testOpenFrame() {
if (!test3window || test3window.content.location.href == "about:blank") {
info("testOpenFrame: Wait another cycle");
return;
}
clearInterval(intervalID);
is(test3window.content.location.href, invalidPage, "New window should have page url, not about:neterror");
test3window.close();
cleanup();
}
function cleanup() {
gBrowser.removeCurrentTab();
finish();
}

View file

@ -1,52 +0,0 @@
/* Make sure that the context menu appears on form elements */
add_task(function *() {
yield BrowserTestUtils.openNewForegroundTab(gBrowser, "data:text/html,test");
let contentAreaContextMenu = document.getElementById("contentAreaContextMenu");
let tests = [
{ element: "input", type: "text" },
{ element: "input", type: "password" },
{ element: "input", type: "image" },
{ element: "input", type: "button" },
{ element: "input", type: "submit" },
{ element: "input", type: "reset" },
{ element: "input", type: "checkbox" },
{ element: "input", type: "radio" },
{ element: "button" },
{ element: "select" },
{ element: "option" },
{ element: "optgroup" }
];
for (let index = 0; index < tests.length; index++) {
let test = tests[index];
yield ContentTask.spawn(gBrowser.selectedBrowser,
{ element: test.element, type: test.type, index: index },
function* (arg) {
let element = content.document.createElement(arg.element);
element.id = "element" + arg.index;
if (arg.type) {
element.setAttribute("type", arg.type);
}
content.document.body.appendChild(element);
});
let popupShownPromise = BrowserTestUtils.waitForEvent(contentAreaContextMenu, "popupshown");
yield BrowserTestUtils.synthesizeMouseAtCenter("#element" + index,
{ type: "contextmenu", button: 2}, gBrowser.selectedBrowser);
yield popupShownPromise;
let typeAttr = test.type ? "type=" + test.type + " " : "";
is(gContextMenu.shouldDisplay, true,
"context menu behavior for <" + test.element + " " + typeAttr + "> is wrong");
let popupHiddenPromise = BrowserTestUtils.waitForEvent(contentAreaContextMenu, "popuphidden");
contentAreaContextMenu.hidePopup();
yield popupHiddenPromise;
}
gBrowser.removeCurrentTab();
});

View file

@ -1,38 +0,0 @@
"use strict";
/*
* Test bug 427559 to make sure focused elements that are no longer on the page
* will have focus transferred to the window when changing tabs back to that
* tab with the now-gone element.
*/
// Default focus on a button and have it kill itself on blur.
const URL = 'data:text/html;charset=utf-8,' +
'<body><button onblur="this.remove()">' +
'<script>document.body.firstChild.focus()</script></body>';
function getFocusedLocalName(browser) {
return ContentTask.spawn(browser, null, function* () {
return content.document.activeElement.localName;
});
}
add_task(function* () {
let testTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, URL);
let browser = testTab.linkedBrowser;
is((yield getFocusedLocalName(browser)), "button", "button is focused");
let blankTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
yield BrowserTestUtils.switchTab(gBrowser, testTab);
// Make sure focus is given to the window because the element is now gone.
is((yield getFocusedLocalName(browser)), "body", "body is focused");
// Cleanup.
gBrowser.removeTab(blankTab);
gBrowser.removeCurrentTab();
});

View file

@ -1,50 +0,0 @@
function remote(task) {
return ContentTask.spawn(gBrowser.selectedBrowser, null, task);
}
add_task(function* () {
gBrowser.selectedTab = gBrowser.addTab();
let promise = remote(function () {
return ContentTaskUtils.waitForEvent(this, "DOMContentLoaded", true, event => {
return content.document.documentURI != "about:blank";
}).then(() => 0); // don't want to send the event to the chrome process
});
gBrowser.loadURI("https://nocert.example.com/");
yield promise;
yield remote(() => {
// Confirm that we are displaying the contributed error page, not the default
let uri = content.document.documentURI;
Assert.ok(uri.startsWith("about:certerror"), "Broken page should go to about:certerror, not about:neterror");
});
yield remote(() => {
let div = content.document.getElementById("badCertAdvancedPanel");
// Confirm that the expert section is collapsed
Assert.ok(div, "Advanced content div should exist");
Assert.equal(div.ownerGlobal.getComputedStyle(div).display,
"none", "Advanced content should not be visible by default");
});
// Tweak the expert mode pref
gPrefService.setBoolPref("browser.xul.error_pages.expert_bad_cert", true);
promise = remote(function () {
return ContentTaskUtils.waitForEvent(this, "DOMContentLoaded", true);
});
gBrowser.reload();
yield promise;
yield remote(() => {
let div = content.document.getElementById("badCertAdvancedPanel");
Assert.ok(div, "Advanced content div should exist");
Assert.equal(div.ownerGlobal.getComputedStyle(div).display,
"block", "Advanced content should be visible by default");
});
// Clean up
gBrowser.removeCurrentTab();
if (gPrefService.prefHasUserValue("browser.xul.error_pages.expert_bad_cert"))
gPrefService.clearUserPref("browser.xul.error_pages.expert_bad_cert");
});

View file

@ -1,127 +0,0 @@
function invokeUsingCtrlD(phase) {
switch (phase) {
case 1:
EventUtils.synthesizeKey("d", { accelKey: true });
break;
case 2:
case 4:
EventUtils.synthesizeKey("VK_ESCAPE", {});
break;
case 3:
EventUtils.synthesizeKey("d", { accelKey: true });
EventUtils.synthesizeKey("d", { accelKey: true });
break;
}
}
function invokeUsingStarButton(phase) {
switch (phase) {
case 1:
EventUtils.synthesizeMouseAtCenter(BookmarkingUI.star, {});
break;
case 2:
case 4:
EventUtils.synthesizeKey("VK_ESCAPE", {});
break;
case 3:
EventUtils.synthesizeMouseAtCenter(BookmarkingUI.star,
{ clickCount: 2 });
break;
}
}
var testURL = "data:text/plain,Content";
var bookmarkId;
function add_bookmark(aURI, aTitle) {
return PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
aURI, PlacesUtils.bookmarks.DEFAULT_INDEX,
aTitle);
}
// test bug 432599
function test() {
waitForExplicitFinish();
gBrowser.selectedTab = gBrowser.addTab();
gBrowser.selectedBrowser.addEventListener("load", function onLoad() {
gBrowser.selectedBrowser.removeEventListener("load", onLoad, true);
waitForStarChange(false, initTest);
}, true);
content.location = testURL;
}
function initTest() {
// First, bookmark the page.
bookmarkId = add_bookmark(makeURI(testURL), "Bug 432599 Test");
checkBookmarksPanel(invokers[currentInvoker], 1);
}
function waitForStarChange(aValue, aCallback) {
let expectedStatus = aValue ? BookmarkingUI.STATUS_STARRED
: BookmarkingUI.STATUS_UNSTARRED;
if (BookmarkingUI.status == BookmarkingUI.STATUS_UPDATING ||
BookmarkingUI.status != expectedStatus) {
info("Waiting for star button change.");
setTimeout(waitForStarChange, 50, aValue, aCallback);
return;
}
aCallback();
}
var invokers = [invokeUsingStarButton, invokeUsingCtrlD];
var currentInvoker = 0;
var initialValue;
var initialRemoveHidden;
var popupElement = document.getElementById("editBookmarkPanel");
var titleElement = document.getElementById("editBookmarkPanelTitle");
var removeElement = document.getElementById("editBookmarkPanelRemoveButton");
function checkBookmarksPanel(invoker, phase)
{
let onPopupShown = function(aEvent) {
if (aEvent.originalTarget == popupElement) {
popupElement.removeEventListener("popupshown", arguments.callee, false);
checkBookmarksPanel(invoker, phase + 1);
}
};
let onPopupHidden = function(aEvent) {
if (aEvent.originalTarget == popupElement) {
popupElement.removeEventListener("popuphidden", arguments.callee, false);
if (phase < 4) {
checkBookmarksPanel(invoker, phase + 1);
} else {
++currentInvoker;
if (currentInvoker < invokers.length) {
checkBookmarksPanel(invokers[currentInvoker], 1);
} else {
gBrowser.removeTab(gBrowser.selectedTab, {skipPermitUnload: true});
PlacesUtils.bookmarks.removeItem(bookmarkId);
executeSoon(finish);
}
}
}
};
switch (phase) {
case 1:
case 3:
popupElement.addEventListener("popupshown", onPopupShown, false);
break;
case 2:
popupElement.addEventListener("popuphidden", onPopupHidden, false);
initialValue = titleElement.value;
initialRemoveHidden = removeElement.hidden;
break;
case 4:
popupElement.addEventListener("popuphidden", onPopupHidden, false);
is(titleElement.value, initialValue, "The bookmark panel's title should be the same");
is(removeElement.hidden, initialRemoveHidden, "The bookmark panel's visibility should not change");
break;
}
invoker(phase);
}

View file

@ -1,17 +0,0 @@
function test() {
waitForExplicitFinish();
gBrowser.selectedTab = gBrowser.addTab();
BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser).then(() => {
is(document.getElementById("identity-box").className,
"unknownIdentity mixedDisplayContent",
"identity box has class name for mixed content");
gBrowser.removeCurrentTab();
finish();
});
gBrowser.loadURI(
"https://example.com/browser/browser/base/content/test/general/test_bug435035.html"
);
}

View file

@ -1,69 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
/* Ensure that clicking the button in the Offline mode neterror page makes the browser go online. See bug 435325. */
var proxyPrefValue;
function test() {
waitForExplicitFinish();
// Go offline and disable the proxy and cache, then try to load the test URL.
Services.io.offline = true;
// Tests always connect to localhost, and per bug 87717, localhost is now
// reachable in offline mode. To avoid this, disable any proxy.
proxyPrefValue = Services.prefs.getIntPref("network.proxy.type");
Services.prefs.setIntPref("network.proxy.type", 0);
Services.prefs.setBoolPref("browser.cache.disk.enable", false);
Services.prefs.setBoolPref("browser.cache.memory.enable", false);
gBrowser.selectedTab = gBrowser.addTab("http://example.com/");
let contentScript = `
let listener = function () {
removeEventListener("DOMContentLoaded", listener);
sendAsyncMessage("Test:DOMContentLoaded", { uri: content.document.documentURI });
};
addEventListener("DOMContentLoaded", listener);
`;
function pageloaded({ data }) {
mm.removeMessageListener("Test:DOMContentLoaded", pageloaded);
checkPage(data);
}
let mm = gBrowser.selectedBrowser.messageManager;
mm.addMessageListener("Test:DOMContentLoaded", pageloaded);
mm.loadFrameScript("data:," + contentScript, true);
}
function checkPage(data) {
ok(Services.io.offline, "Setting Services.io.offline to true.");
is(data.uri.substring(0, 27),
"about:neterror?e=netOffline", "Loading the Offline mode neterror page.");
// Re-enable the proxy so example.com is resolved to localhost, rather than
// the actual example.com.
Services.prefs.setIntPref("network.proxy.type", proxyPrefValue);
Services.obs.addObserver(function observer(aSubject, aTopic) {
ok(!Services.io.offline, "After clicking the Try Again button, we're back " +
"online.");
Services.obs.removeObserver(observer, "network:offline-status-changed", false);
finish();
}, "network:offline-status-changed", false);
ContentTask.spawn(gBrowser.selectedBrowser, null, function* () {
content.document.getElementById("errorTryAgain").click();
});
}
registerCleanupFunction(function() {
Services.prefs.setBoolPref("browser.cache.disk.enable", true);
Services.prefs.setBoolPref("browser.cache.memory.enable", true);
Services.io.offline = false;
gBrowser.removeCurrentTab();
});

View file

@ -1,46 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* Test the fix for bug 441778 to ensure site-specific page zoom doesn't get
* modified by sub-document loads of content from a different domain.
*/
function test() {
waitForExplicitFinish();
const TEST_PAGE_URL = 'data:text/html,<body><iframe src=""></iframe></body>';
const TEST_IFRAME_URL = "http://test2.example.org/";
Task.spawn(function* () {
// Prepare the test tab
let tab = gBrowser.addTab();
yield FullZoomHelper.selectTabAndWaitForLocationChange(tab);
let testBrowser = tab.linkedBrowser;
yield FullZoomHelper.load(tab, TEST_PAGE_URL);
// Change the zoom level and then save it so we can compare it to the level
// after loading the sub-document.
FullZoom.enlarge();
var zoomLevel = ZoomManager.zoom;
// Start the sub-document load.
let deferred = Promise.defer();
executeSoon(function () {
BrowserTestUtils.browserLoaded(testBrowser, true).then(url => {
is(url, TEST_IFRAME_URL, "got the load event for the iframe");
is(ZoomManager.zoom, zoomLevel, "zoom is retained after sub-document load");
FullZoomHelper.removeTabAndWaitForLocationChange().
then(() => deferred.resolve());
});
ContentTask.spawn(testBrowser, TEST_IFRAME_URL, url => {
content.document.querySelector("iframe").src = url;
});
});
yield deferred.promise;
}).then(finish, FullZoomHelper.failAndContinue(finish));
}

View file

@ -1,20 +0,0 @@
add_task(function*() {
is(gBrowser.tabs.length, 1, "one tab is open");
gBrowser.selectedBrowser.focus();
isnot(document.activeElement, gURLBar.inputField, "location bar is not focused");
var tab = gBrowser.selectedTab;
gPrefService.setBoolPref("browser.tabs.closeWindowWithLastTab", false);
let tabClosedPromise = BrowserTestUtils.removeTab(tab, {dontRemove: true});
EventUtils.synthesizeKey("w", { accelKey: true });
yield tabClosedPromise;
is(tab.parentNode, null, "ctrl+w removes the tab");
is(gBrowser.tabs.length, 1, "a new tab has been opened");
is(document.activeElement, gURLBar.inputField, "location bar is focused for the new tab");
if (gPrefService.prefHasUserValue("browser.tabs.closeWindowWithLastTab"))
gPrefService.clearUserPref("browser.tabs.closeWindowWithLastTab");
});

View file

@ -1,51 +0,0 @@
/* Check proper image url retrieval from all kinds of elements/styles */
function test() {
waitForExplicitFinish();
gBrowser.selectedTab = gBrowser.addTab();
gBrowser.selectedBrowser.addEventListener("load", function () {
gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
var pageInfo = BrowserPageInfo(gBrowser.selectedBrowser.currentURI.spec,
"mediaTab");
pageInfo.addEventListener("load", function () {
pageInfo.removeEventListener("load", arguments.callee, true);
pageInfo.onFinished.push(function () {
executeSoon(function () {
var imageTree = pageInfo.document.getElementById("imagetree");
var imageRowsNum = imageTree.view.rowCount;
ok(imageTree, "Image tree is null (media tab is broken)");
ok(imageRowsNum == 7, "Number of images listed: " +
imageRowsNum + ", should be 7");
pageInfo.close();
gBrowser.removeCurrentTab();
finish();
});
});
}, true);
}, true);
content.location =
"data:text/html," +
"<html>" +
" <head>" +
" <title>Test for media tab</title>" +
" <link rel='shortcut icon' href='file:///dummy_icon.ico'>" + // Icon
" </head>" +
" <body style='background-image:url(about:logo?a);'>" + // Background
" <img src='file:///dummy_image.gif'>" + // Image
" <ul>" +
" <li style='list-style:url(about:logo?b);'>List Item 1</li>" + // Bullet
" </ul> " +
" <div style='-moz-border-image: url(about:logo?c) 20 20 20 20;'>test</div>" + // Border
" <a href='' style='cursor: url(about:logo?d),default;'>test link</a>" + // Cursor
" <object type='image/svg+xml' width=20 height=20 data='file:///dummy_object.svg'></object>" + // Object
" </body>" +
"</html>";
}

View file

@ -1,81 +0,0 @@
var tab1, tab2;
function focus_in_navbar()
{
var parent = document.activeElement.parentNode;
while (parent && parent.id != "nav-bar")
parent = parent.parentNode;
return parent != null;
}
function test()
{
waitForExplicitFinish();
tab1 = gBrowser.addTab("about:blank", {skipAnimation: true});
tab2 = gBrowser.addTab("about:blank", {skipAnimation: true});
EventUtils.synthesizeMouseAtCenter(tab1, {});
executeSoon(step2);
}
function step2()
{
is(gBrowser.selectedTab, tab1, "1st click on tab1 selects tab");
isnot(document.activeElement, tab1, "1st click on tab1 does not activate tab");
EventUtils.synthesizeMouseAtCenter(tab1, {});
executeSoon(step3);
}
function step3()
{
is(gBrowser.selectedTab, tab1, "2nd click on selected tab1 keeps tab selected");
isnot(document.activeElement, tab1, "2nd click on selected tab1 does not activate tab");
ok(true, "focusing URLBar then sending 1 Shift+Tab.");
gURLBar.focus();
EventUtils.synthesizeKey("VK_TAB", {shiftKey: true});
is(gBrowser.selectedTab, tab1, "tab key to selected tab1 keeps tab selected");
is(document.activeElement, tab1, "tab key to selected tab1 activates tab");
EventUtils.synthesizeMouseAtCenter(tab1, {});
executeSoon(step4);
}
function step4()
{
is(gBrowser.selectedTab, tab1, "3rd click on activated tab1 keeps tab selected");
is(document.activeElement, tab1, "3rd click on activated tab1 keeps tab activated");
gBrowser.addEventListener("TabSwitchDone", step5);
EventUtils.synthesizeMouseAtCenter(tab2, {});
}
function step5()
{
gBrowser.removeEventListener("TabSwitchDone", step5);
// The tabbox selects a tab within a setTimeout in a bubbling mousedown event
// listener, and focuses the current tab if another tab previously had focus.
is(gBrowser.selectedTab, tab2, "click on tab2 while tab1 is activated selects tab");
is(document.activeElement, tab2, "click on tab2 while tab1 is activated activates tab");
info("focusing content then sending middle-button mousedown to tab2.");
gBrowser.selectedBrowser.focus();
EventUtils.synthesizeMouseAtCenter(tab2, {button: 1, type: "mousedown"});
executeSoon(step6);
}
function step6()
{
is(gBrowser.selectedTab, tab2, "middle-button mousedown on selected tab2 keeps tab selected");
isnot(document.activeElement, tab2, "middle-button mousedown on selected tab2 does not activate tab");
gBrowser.removeTab(tab2);
gBrowser.removeTab(tab1);
finish();
}

View file

@ -1,36 +0,0 @@
add_task(function* () {
var win = openDialog(getBrowserURL(), "_blank", "chrome,all,dialog=no");
yield SimpleTest.promiseFocus(win);
let tab = win.gBrowser.tabContainer.firstChild;
yield promiseTabLoadEvent(tab, getRootDirectory(gTestPath) + "test_bug462673.html");
is(win.gBrowser.browsers.length, 2, "test_bug462673.html has opened a second tab");
is(win.gBrowser.selectedTab, tab.nextSibling, "dependent tab is selected");
win.gBrowser.removeTab(tab);
// Closing a tab will also close its parent chrome window, but async
yield promiseWindowWillBeClosed(win);
});
add_task(function* () {
var win = openDialog(getBrowserURL(), "_blank", "chrome,all,dialog=no");
yield SimpleTest.promiseFocus(win);
let tab = win.gBrowser.tabContainer.firstChild;
yield promiseTabLoadEvent(tab, getRootDirectory(gTestPath) + "test_bug462673.html");
var newTab = win.gBrowser.addTab();
var newBrowser = newTab.linkedBrowser;
win.gBrowser.removeTab(tab);
ok(!win.closed, "Window stays open");
if (!win.closed) {
is(win.gBrowser.tabContainer.childElementCount, 1, "Window has one tab");
is(win.gBrowser.browsers.length, 1, "Window has one browser");
is(win.gBrowser.selectedTab, newTab, "Remaining tab is selected");
is(win.gBrowser.selectedBrowser, newBrowser, "Browser for remaining tab is selected");
is(win.gBrowser.mTabBox.selectedPanel, newBrowser.parentNode.parentNode.parentNode.parentNode, "Panel for remaining tab is selected");
}
yield promiseWindowClosed(win);
});

View file

@ -1,25 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// That's a gecko!
const iconURLSpec = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==";
var testPage="data:text/plain,test bug 477014";
add_task(function*() {
let tabToDetach = gBrowser.addTab(testPage);
yield waitForDocLoadComplete(tabToDetach.linkedBrowser);
gBrowser.setIcon(tabToDetach, iconURLSpec,
Services.scriptSecurityManager.getSystemPrincipal());
tabToDetach.setAttribute("busy", "true");
// detach and set the listener on the new window
let newWindow = gBrowser.replaceTabWithWindow(tabToDetach);
yield promiseWaitForEvent(tabToDetach.linkedBrowser, "SwapDocShells");
is(newWindow.gBrowser.selectedTab.hasAttribute("busy"), true, "Busy attribute should be correct");
is(newWindow.gBrowser.getIcon(), iconURLSpec, "Icon should be correct");
newWindow.close();
});

View file

@ -1,17 +0,0 @@
function test() {
waitForExplicitFinish();
let tab = gBrowser.selectedTab = gBrowser.addTab(
"http://mochi.test:8888/browser/browser/base/content/test/general/browser_bug479408_sample.html");
gBrowser.addEventListener("DOMLinkAdded", function(aEvent) {
gBrowser.removeEventListener("DOMLinkAdded", arguments.callee, true);
executeSoon(function() {
ok(!tab.linkedBrowser.engines,
"the subframe's search engine wasn't detected");
gBrowser.removeTab(tab);
finish();
});
}, true);
}

View file

@ -1,4 +0,0 @@
<!DOCTYPE html>
<title>Testcase for bug 479408</title>
<iframe src='data:text/html,<link%20rel="search"%20type="application/opensearchdescription+xml"%20title="Search%20bug%20479408"%20href="http://example.com/search.xml">'>

View file

@ -1,21 +0,0 @@
function test() {
waitForExplicitFinish();
whenNewWindowLoaded(null, function (win) {
waitForFocus(function () {
function onTabClose() {
ok(false, "shouldn't have gotten the TabClose event for the last tab");
}
var tab = win.gBrowser.selectedTab;
tab.addEventListener("TabClose", onTabClose, false);
EventUtils.synthesizeKey("w", { accelKey: true }, win);
ok(win.closed, "accel+w closed the window immediately");
tab.removeEventListener("TabClose", onTabClose, false);
finish();
}, win);
});
}

View file

@ -1,23 +0,0 @@
function test() {
var contentWin = window.open("about:blank", "", "width=100,height=100");
var enumerator = Services.wm.getEnumerator("navigator:browser");
while (enumerator.hasMoreElements()) {
let win = enumerator.getNext();
if (win.content == contentWin) {
gPrefService.setBoolPref("browser.tabs.closeWindowWithLastTab", false);
win.gBrowser.removeCurrentTab();
ok(win.closed, "popup is closed");
// clean up
if (!win.closed)
win.close();
if (gPrefService.prefHasUserValue("browser.tabs.closeWindowWithLastTab"))
gPrefService.clearUserPref("browser.tabs.closeWindowWithLastTab");
return;
}
}
throw "couldn't find the content window";
}

View file

@ -1,34 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var testPage = "data:text/plain,test bug 491431 Page";
function test() {
waitForExplicitFinish();
let newWin, tabA, tabB;
// test normal close
tabA = gBrowser.addTab(testPage);
gBrowser.tabContainer.addEventListener("TabClose", function(firstTabCloseEvent) {
gBrowser.tabContainer.removeEventListener("TabClose", arguments.callee, true);
ok(!firstTabCloseEvent.detail.adoptedBy, "This was a normal tab close");
// test tab close by moving
tabB = gBrowser.addTab(testPage);
gBrowser.tabContainer.addEventListener("TabClose", function(secondTabCloseEvent) {
gBrowser.tabContainer.removeEventListener("TabClose", arguments.callee, true);
executeSoon(function() {
ok(secondTabCloseEvent.detail.adoptedBy, "This was a tab closed by moving");
// cleanup
newWin.close();
executeSoon(finish);
});
}, true);
newWin = gBrowser.replaceTabWithWindow(tabB);
}, true);
gBrowser.removeTab(tabA);
}

View file

@ -1,38 +0,0 @@
/**
* Tests that the right elements of a tab are focused when it is
* torn out into its own window.
*/
const URIS = [
"about:blank",
"about:sessionrestore",
"about:privatebrowsing",
];
add_task(function*() {
for (let uri of URIS) {
let tab = gBrowser.addTab();
yield BrowserTestUtils.loadURI(tab.linkedBrowser, uri);
let win = gBrowser.replaceTabWithWindow(tab);
yield TestUtils.topicObserved("browser-delayed-startup-finished",
subject => subject == win);
tab = win.gBrowser.selectedTab;
// BrowserTestUtils doesn't get the add-on shims, which means that
// MozAfterPaint won't get shimmed over if we add an event handler
// for it in the parent.
if (tab.linkedBrowser.isRemoteBrowser) {
yield BrowserTestUtils.waitForContentEvent(tab.linkedBrowser, "MozAfterPaint");
} else {
yield BrowserTestUtils.waitForEvent(tab.linkedBrowser, "MozAfterPaint");
}
Assert.equal(win.gBrowser.currentURI.spec, uri, uri + ": uri loaded in detached tab");
Assert.equal(win.document.activeElement, win.gBrowser.selectedBrowser, uri + ": browser is focused");
Assert.equal(win.gURLBar.value, "", uri + ": urlbar is empty");
Assert.ok(win.gURLBar.placeholder, uri + ": placeholder text is present");
yield BrowserTestUtils.closeWindow(win);
}
});

View file

@ -1,42 +0,0 @@
/* Make sure that "View Image Info" loads the correct image data */
function test() {
waitForExplicitFinish();
gBrowser.selectedTab = gBrowser.addTab();
gBrowser.selectedBrowser.addEventListener("load", function () {
gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
var doc = gBrowser.contentDocument;
var testImg = doc.getElementById("test-image");
var pageInfo = BrowserPageInfo(gBrowser.selectedBrowser.currentURI.spec,
"mediaTab", testImg);
pageInfo.addEventListener("load", function () {
pageInfo.removeEventListener("load", arguments.callee, true);
pageInfo.onFinished.push(function () {
executeSoon(function () {
var pageInfoImg = pageInfo.document.getElementById("thepreviewimage");
is(pageInfoImg.src, testImg.src, "selected image has the correct source");
is(pageInfoImg.width, testImg.width, "selected image has the correct width");
is(pageInfoImg.height, testImg.height, "selected image has the correct height");
pageInfo.close();
gBrowser.removeCurrentTab();
finish();
});
});
}, true);
}, true);
content.location =
"data:text/html," +
"<style type='text/css'>%23test-image,%23not-test-image {background-image: url('about:logo?c');}</style>" +
"<img src='about:logo?b' height=300 width=350 alt=2 id='not-test-image'>" +
"<img src='about:logo?b' height=300 width=350 alt=2>" +
"<img src='about:logo?a' height=200 width=250>" +
"<img src='about:logo?b' height=200 width=250 alt=1>" +
"<img src='about:logo?b' height=100 width=150 alt=2 id='test-image'>";
}

View file

@ -1,45 +0,0 @@
function test() {
waitForExplicitFinish();
gBrowser.addProgressListener(progressListener1);
gBrowser.addProgressListener(progressListener2);
gBrowser.addProgressListener(progressListener3);
gBrowser.loadURI("data:text/plain,bug519216");
}
var calledListener1 = false;
var progressListener1 = {
onLocationChange: function onLocationChange() {
calledListener1 = true;
gBrowser.removeProgressListener(this);
}
};
var calledListener2 = false;
var progressListener2 = {
onLocationChange: function onLocationChange() {
ok(calledListener1, "called progressListener1 before progressListener2");
calledListener2 = true;
gBrowser.removeProgressListener(this);
}
};
var progressListener3 = {
onLocationChange: function onLocationChange() {
ok(calledListener2, "called progressListener2 before progressListener3");
gBrowser.removeProgressListener(this);
gBrowser.addProgressListener(progressListener4);
executeSoon(function () {
expectListener4 = true;
gBrowser.reload();
});
}
};
var expectListener4 = false;
var progressListener4 = {
onLocationChange: function onLocationChange() {
ok(expectListener4, "didn't call progressListener4 for the first location change");
gBrowser.removeProgressListener(this);
executeSoon(finish);
}
};

View file

@ -1,15 +0,0 @@
function test() {
var tabCount = gBrowser.tabs.length;
gBrowser.selectedBrowser.focus();
browserDOMWindow.openURI(makeURI("about:blank"),
null,
Ci.nsIBrowserDOMWindow.OPEN_NEWTAB,
Ci.nsIBrowserDOMWindow.OPEN_EXTERNAL);
is(gBrowser.tabs.length, tabCount + 1,
"'--new-tab about:blank' opens a new tab");
is(gBrowser.selectedTab, gBrowser.tabs[tabCount],
"'--new-tab about:blank' selects the new tab");
is(document.activeElement, gURLBar.inputField,
"'--new-tab about:blank' focuses the location bar");
gBrowser.removeCurrentTab();
}

View file

@ -1,50 +0,0 @@
var expected = ["TabOpen", "onStateChange", "onLocationChange", "onLinkIconAvailable"];
var actual = [];
var tabIndex = -1;
this.__defineGetter__("tab", () => gBrowser.tabs[tabIndex]);
function test() {
waitForExplicitFinish();
tabIndex = gBrowser.tabs.length;
gBrowser.addTabsProgressListener(progressListener);
gBrowser.tabContainer.addEventListener("TabOpen", TabOpen, false);
gBrowser.addTab("data:text/html,<html><head><link href='about:logo' rel='shortcut icon'>");
}
function record(aName) {
info("got " + aName);
if (actual.indexOf(aName) == -1)
actual.push(aName);
if (actual.length == expected.length) {
is(actual.toString(), expected.toString(),
"got events and progress notifications in expected order");
executeSoon(function(tab) {
gBrowser.removeTab(tab);
gBrowser.removeTabsProgressListener(progressListener);
gBrowser.tabContainer.removeEventListener("TabOpen", TabOpen, false);
finish();
}.bind(null, tab));
}
}
function TabOpen(aEvent) {
if (aEvent.target == tab)
record(arguments.callee.name);
}
var progressListener = {
onLocationChange: function onLocationChange(aBrowser) {
if (aBrowser == tab.linkedBrowser)
record(arguments.callee.name);
},
onStateChange: function onStateChange(aBrowser) {
if (aBrowser == tab.linkedBrowser)
record(arguments.callee.name);
},
onLinkIconAvailable: function onLinkIconAvailable(aBrowser, aIconURL) {
if (aBrowser == tab.linkedBrowser &&
aIconURL == "about:logo")
record(arguments.callee.name);
}
};

View file

@ -1,36 +0,0 @@
function test() {
var tab1 = gBrowser.selectedTab;
var tab2 = gBrowser.addTab();
var childTab1;
var childTab2;
childTab1 = gBrowser.addTab("about:blank", { relatedToCurrent: true });
gBrowser.selectedTab = childTab1;
gBrowser.removeTab(gBrowser.selectedTab, { skipPermitUnload: true });
is(idx(gBrowser.selectedTab), idx(tab1),
"closing a tab next to its parent selects the parent");
childTab1 = gBrowser.addTab("about:blank", { relatedToCurrent: true });
gBrowser.selectedTab = tab2;
gBrowser.selectedTab = childTab1;
gBrowser.removeTab(gBrowser.selectedTab, { skipPermitUnload: true });
is(idx(gBrowser.selectedTab), idx(tab2),
"closing a tab next to its parent doesn't select the parent if another tab had been selected ad interim");
gBrowser.selectedTab = tab1;
childTab1 = gBrowser.addTab("about:blank", { relatedToCurrent: true });
childTab2 = gBrowser.addTab("about:blank", { relatedToCurrent: true });
gBrowser.selectedTab = childTab1;
gBrowser.removeTab(gBrowser.selectedTab, { skipPermitUnload: true });
is(idx(gBrowser.selectedTab), idx(childTab2),
"closing a tab next to its parent selects the next tab with the same parent");
gBrowser.removeTab(gBrowser.selectedTab, { skipPermitUnload: true });
is(idx(gBrowser.selectedTab), idx(tab2),
"closing the last tab in a set of child tabs doesn't go back to the parent");
gBrowser.removeTab(tab2, { skipPermitUnload: true });
}
function idx(tab) {
return Array.indexOf(gBrowser.tabs, tab);
}

View file

@ -1,135 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
/* Tests for bug 537013 to ensure proper tab-sequestration of find bar. */
var tabs = [];
var texts = [
"This side up.",
"The world is coming to an end. Please log off.",
"Klein bottle for sale. Inquire within.",
"To err is human; to forgive is not company policy."
];
var Clipboard = Cc["@mozilla.org/widget/clipboard;1"].getService(Ci.nsIClipboard);
var HasFindClipboard = Clipboard.supportsFindClipboard();
function addTabWithText(aText, aCallback) {
let newTab = gBrowser.addTab("data:text/html;charset=utf-8,<h1 id='h1'>" +
aText + "</h1>");
tabs.push(newTab);
gBrowser.selectedTab = newTab;
}
function setFindString(aString) {
gFindBar.open();
gFindBar._findField.focus();
gFindBar._findField.select();
EventUtils.sendString(aString);
is(gFindBar._findField.value, aString, "Set the field correctly!");
}
var newWindow;
function test() {
waitForExplicitFinish();
registerCleanupFunction(function () {
while (tabs.length) {
gBrowser.removeTab(tabs.pop());
}
});
texts.forEach(aText => addTabWithText(aText));
// Set up the first tab
gBrowser.selectedTab = tabs[0];
setFindString(texts[0]);
// Turn on highlight for testing bug 891638
gFindBar.toggleHighlight(true);
// Make sure the second tab is correct, then set it up
gBrowser.selectedTab = tabs[1];
gBrowser.selectedTab.addEventListener("TabFindInitialized", continueTests1);
// Initialize the findbar
gFindBar;
}
function continueTests1() {
gBrowser.selectedTab.removeEventListener("TabFindInitialized",
continueTests1);
ok(true, "'TabFindInitialized' event properly dispatched!");
ok(gFindBar.hidden, "Second tab doesn't show find bar!");
gFindBar.open();
is(gFindBar._findField.value, texts[0],
"Second tab kept old find value for new initialization!");
setFindString(texts[1]);
// Confirm the first tab is still correct, ensure re-hiding works as expected
gBrowser.selectedTab = tabs[0];
ok(!gFindBar.hidden, "First tab shows find bar!");
// When the Find Clipboard is supported, this test not relevant.
if (!HasFindClipboard)
is(gFindBar._findField.value, texts[0], "First tab persists find value!");
ok(gFindBar.getElement("highlight").checked,
"Highlight button state persists!");
// While we're here, let's test the backout of bug 253793.
gBrowser.reload();
gBrowser.addEventListener("DOMContentLoaded", continueTests2, true);
}
function continueTests2() {
gBrowser.removeEventListener("DOMContentLoaded", continueTests2, true);
ok(gFindBar.getElement("highlight").checked, "Highlight never reset!");
continueTests3();
}
function continueTests3() {
ok(gFindBar.getElement("highlight").checked, "Highlight button reset!");
gFindBar.close();
ok(gFindBar.hidden, "First tab doesn't show find bar!");
gBrowser.selectedTab = tabs[1];
ok(!gFindBar.hidden, "Second tab shows find bar!");
// Test for bug 892384
is(gFindBar._findField.getAttribute("focused"), "true",
"Open findbar refocused on tab change!");
gURLBar.focus();
gBrowser.selectedTab = tabs[0];
ok(gFindBar.hidden, "First tab doesn't show find bar!");
// Set up a third tab, no tests here
gBrowser.selectedTab = tabs[2];
setFindString(texts[2]);
// Now we jump to the second, then first, and then fourth
gBrowser.selectedTab = tabs[1];
// Test for bug 892384
ok(!gFindBar._findField.hasAttribute("focused"),
"Open findbar not refocused on tab change!");
gBrowser.selectedTab = tabs[0];
gBrowser.selectedTab = tabs[3];
ok(gFindBar.hidden, "Fourth tab doesn't show find bar!");
is(gFindBar, gBrowser.getFindBar(), "Find bar is right one!");
gFindBar.open();
// Disabled the following assertion due to intermittent failure on OSX 10.6 Debug.
if (!HasFindClipboard) {
is(gFindBar._findField.value, texts[1],
"Fourth tab has second tab's find value!");
}
newWindow = gBrowser.replaceTabWithWindow(tabs.pop());
whenDelayedStartupFinished(newWindow, checkNewWindow);
}
// Test that findbar gets restored when a tab is moved to a new window.
function checkNewWindow() {
ok(!newWindow.gFindBar.hidden, "New window shows find bar!");
// Disabled the following assertion due to intermittent failure on OSX 10.6 Debug.
if (!HasFindClipboard) {
is(newWindow.gFindBar._findField.value, texts[1],
"New window find bar has correct find value!");
}
ok(!newWindow.gFindBar.getElement("find-next").disabled,
"New window findbar has enabled buttons!");
newWindow.close();
finish();
}

View file

@ -1,8 +0,0 @@
add_task(function *() {
let browserLoadedPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
browserDOMWindow.openURI(makeURI("about:"), null,
Ci.nsIBrowserDOMWindow.OPEN_CURRENTWINDOW, null)
yield browserLoadedPromise;
is(gBrowser.currentURI.spec, "about:", "page loads in the current content window");
});

View file

@ -1,44 +0,0 @@
add_task(function* test() {
let testPath = getRootDirectory(gTestPath);
yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" },
function* (tabBrowser) {
const URI = testPath + "file_with_favicon.html";
const expectedIcon = testPath + "file_generic_favicon.ico";
let got_favicon = Promise.defer();
let listener = {
onLinkIconAvailable(browser, iconURI) {
if (got_favicon && iconURI && browser === tabBrowser) {
got_favicon.resolve(iconURI);
got_favicon = null;
}
}
};
gBrowser.addTabsProgressListener(listener);
BrowserTestUtils.loadURI(tabBrowser, URI);
let iconURI = yield got_favicon.promise;
is(iconURI, expectedIcon, "Correct icon before pushState.");
got_favicon = Promise.defer();
got_favicon.promise.then(() => { ok(false, "shouldn't be called"); }, (e) => e);
yield ContentTask.spawn(tabBrowser, null, function() {
content.history.pushState("page2", "page2", "page2");
});
// We've navigated and shouldn't get a call to onLinkIconAvailable.
TestUtils.executeSoon(() => {
got_favicon.reject(gBrowser.getIcon(gBrowser.getTabForBrowser(tabBrowser)));
});
try {
yield got_favicon.promise;
} catch (e) {
iconURI = e;
}
is(iconURI, expectedIcon, "Correct icon after pushState.");
gBrowser.removeTabsProgressListener(listener);
});
});

File diff suppressed because it is too large Load diff

View file

@ -1,40 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const TEST_PAGE = "/browser/browser/base/content/test/general/dummy_page.html";
var gTestTab, gBgTab, gTestZoom;
function testBackgroundLoad() {
Task.spawn(function* () {
is(ZoomManager.zoom, gTestZoom, "opening a background tab should not change foreground zoom");
yield FullZoomHelper.removeTabAndWaitForLocationChange(gBgTab);
yield FullZoom.reset();
yield FullZoomHelper.removeTabAndWaitForLocationChange(gTestTab);
finish();
});
}
function testInitialZoom() {
Task.spawn(function* () {
is(ZoomManager.zoom, 1, "initial zoom level should be 1");
FullZoom.enlarge();
gTestZoom = ZoomManager.zoom;
isnot(gTestZoom, 1, "zoom level should have changed");
gBgTab = gBrowser.addTab();
yield FullZoomHelper.load(gBgTab, "http://mochi.test:8888" + TEST_PAGE);
}).then(testBackgroundLoad, FullZoomHelper.failAndContinue(finish));
}
function test() {
waitForExplicitFinish();
Task.spawn(function* () {
gTestTab = gBrowser.addTab();
yield FullZoomHelper.selectTabAndWaitForLocationChange(gTestTab);
yield FullZoomHelper.load(gTestTab, "http://example.org" + TEST_PAGE);
}).then(testInitialZoom, FullZoomHelper.failAndContinue(finish));
}

View file

@ -1,54 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
add_task(function* () {
let testURL = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
let tabSelected = false;
// Open the base tab
let baseTab = gBrowser.addTab(testURL);
// Wait for the tab to be fully loaded so matching happens correctly
yield promiseTabLoaded(baseTab);
if (baseTab.linkedBrowser.currentURI.spec == "about:blank")
return;
baseTab.linkedBrowser.removeEventListener("load", arguments.callee, true);
let testTab = gBrowser.addTab();
// Select the testTab
gBrowser.selectedTab = testTab;
// Set the urlbar to include the moz-action
gURLBar.value = "moz-action:switchtab," + JSON.stringify({url: testURL});
// Focus the urlbar so we can press enter
gURLBar.focus();
// Functions for TabClose and TabSelect
function onTabClose(aEvent) {
gBrowser.tabContainer.removeEventListener("TabClose", onTabClose, false);
// Make sure we get the TabClose event for testTab
is(aEvent.originalTarget, testTab, "Got the TabClose event for the right tab");
// Confirm that we did select the tab
ok(tabSelected, "Confirming that the tab was selected");
gBrowser.removeTab(baseTab);
finish();
}
function onTabSelect(aEvent) {
gBrowser.tabContainer.removeEventListener("TabSelect", onTabSelect, false);
// Make sure we got the TabSelect event for baseTab
is(aEvent.originalTarget, baseTab, "Got the TabSelect event for the right tab");
// Confirm that the selected tab is in fact base tab
is(gBrowser.selectedTab, baseTab, "We've switched to the correct tab");
tabSelected = true;
}
// Add the TabClose, TabSelect event listeners before we press enter
gBrowser.tabContainer.addEventListener("TabClose", onTabClose, false);
gBrowser.tabContainer.addEventListener("TabSelect", onTabSelect, false);
// Press enter!
EventUtils.synthesizeKey("VK_RETURN", {});
});

View file

@ -1,42 +0,0 @@
var tab;
function test() {
// ----------
// Test setup
waitForExplicitFinish();
gPrefService.setBoolPref("browser.zoom.updateBackgroundTabs", true);
gPrefService.setBoolPref("browser.zoom.siteSpecific", true);
let uri = "http://example.org/browser/browser/base/content/test/general/dummy_page.html";
Task.spawn(function* () {
tab = gBrowser.addTab();
yield FullZoomHelper.load(tab, uri);
// -------------------------------------------------------------------
// Test - Trigger a tab switch that should update the zoom level
yield FullZoomHelper.selectTabAndWaitForLocationChange(tab);
ok(true, "applyPrefToSetting was called");
}).then(endTest, FullZoomHelper.failAndContinue(endTest));
}
// -------------
// Test clean-up
function endTest() {
Task.spawn(function* () {
yield FullZoomHelper.removeTabAndWaitForLocationChange(tab);
tab = null;
if (gPrefService.prefHasUserValue("browser.zoom.updateBackgroundTabs"))
gPrefService.clearUserPref("browser.zoom.updateBackgroundTabs");
if (gPrefService.prefHasUserValue("browser.zoom.siteSpecific"))
gPrefService.clearUserPref("browser.zoom.siteSpecific");
finish();
});
}

View file

@ -1,370 +0,0 @@
var gInvalidFormPopup = document.getElementById('invalid-form-popup');
ok(gInvalidFormPopup,
"The browser should have a popup to show when a form is invalid");
function checkPopupShow()
{
ok(gInvalidFormPopup.state == 'showing' || gInvalidFormPopup.state == 'open',
"[Test " + testId + "] The invalid form popup should be shown");
}
function checkPopupHide()
{
ok(gInvalidFormPopup.state != 'showing' && gInvalidFormPopup.state != 'open',
"[Test " + testId + "] The invalid form popup should not be shown");
}
var gObserver = {
QueryInterface : XPCOMUtils.generateQI([Ci.nsIFormSubmitObserver]),
notifyInvalidSubmit : function (aFormElement, aInvalidElements)
{
}
};
var testId = 0;
function incrementTest()
{
testId++;
info("Starting next part of test");
}
function getDocHeader()
{
return "<html><head><meta charset='utf-8'></head><body>" + getEmptyFrame();
}
function getDocFooter()
{
return "</body></html>";
}
function getEmptyFrame()
{
return "<iframe style='width:100px; height:30px; margin:3px; border:1px solid lightgray;' " +
"name='t' srcdoc=\"<html><head><meta charset='utf-8'></head><body>form target</body></html>\"></iframe>";
}
function* openNewTab(uri, background)
{
let tab = gBrowser.addTab();
let browser = gBrowser.getBrowserForTab(tab);
if (!background) {
gBrowser.selectedTab = tab;
}
yield promiseTabLoadEvent(tab, "data:text/html," + escape(uri));
return browser;
}
function* clickChildElement(browser)
{
yield ContentTask.spawn(browser, {}, function* () {
content.document.getElementById('s').click();
});
}
function* blurChildElement(browser)
{
yield ContentTask.spawn(browser, {}, function* () {
content.document.getElementById('i').blur();
});
}
function* checkChildFocus(browser, message)
{
yield ContentTask.spawn(browser, [message, testId], function* (args) {
let [msg, id] = args;
var focused = content.document.activeElement == content.document.getElementById('i');
var validMsg = true;
if (msg) {
validMsg = (msg == content.document.getElementById('i').validationMessage);
}
Assert.equal(focused, true, "Test " + id + " First invalid element should be focused");
Assert.equal(validMsg, true, "Test " + id + " The panel should show the message from validationMessage");
});
}
/**
* In this test, we check that no popup appears if the form is valid.
*/
add_task(function* ()
{
incrementTest();
let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input><input id='s' type='submit'></form>" + getDocFooter();
let browser = yield openNewTab(uri);
yield clickChildElement(browser);
yield new Promise((resolve, reject) => {
// XXXndeakin This isn't really going to work when the content is another process
executeSoon(function() {
checkPopupHide();
resolve();
});
});
gBrowser.removeCurrentTab();
});
/**
* In this test, we check that, when an invalid form is submitted,
* the invalid element is focused and a popup appears.
*/
add_task(function* ()
{
incrementTest();
let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input required id='i'><input id='s' type='submit'></form>" + getDocFooter();
let browser = yield openNewTab(uri);
let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
yield clickChildElement(browser);
yield popupShownPromise;
checkPopupShow();
yield checkChildFocus(browser, gInvalidFormPopup.firstChild.textContent);
gBrowser.removeCurrentTab();
});
/**
* In this test, we check that, when an invalid form is submitted,
* the first invalid element is focused and a popup appears.
*/
add_task(function* ()
{
incrementTest();
let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input><input id='i' required><input required><input id='s' type='submit'></form>" + getDocFooter();
let browser = yield openNewTab(uri);
let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
yield clickChildElement(browser);
yield popupShownPromise;
checkPopupShow();
yield checkChildFocus(browser, gInvalidFormPopup.firstChild.textContent);
gBrowser.removeCurrentTab();
});
/**
* In this test, we check that, we hide the popup by interacting with the
* invalid element if the element becomes valid.
*/
add_task(function* ()
{
incrementTest();
let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input id='i' required><input id='s' type='submit'></form>" + getDocFooter();
let browser = yield openNewTab(uri);
let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
yield clickChildElement(browser);
yield popupShownPromise;
checkPopupShow();
yield checkChildFocus(browser, gInvalidFormPopup.firstChild.textContent);
let popupHiddenPromise = promiseWaitForEvent(gInvalidFormPopup, "popuphidden");
EventUtils.synthesizeKey("a", {});
yield popupHiddenPromise;
gBrowser.removeCurrentTab();
});
/**
* In this test, we check that, we don't hide the popup by interacting with the
* invalid element if the element is still invalid.
*/
add_task(function* ()
{
incrementTest();
let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input type='email' id='i' required><input id='s' type='submit'></form>" + getDocFooter();
let browser = yield openNewTab(uri);
let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
yield clickChildElement(browser);
yield popupShownPromise;
checkPopupShow();
yield checkChildFocus(browser, gInvalidFormPopup.firstChild.textContent);
yield new Promise((resolve, reject) => {
EventUtils.synthesizeKey("a", {});
executeSoon(function() {
checkPopupShow();
resolve();
})
});
gBrowser.removeCurrentTab();
});
/**
* In this test, we check that we can hide the popup by blurring the invalid
* element.
*/
add_task(function* ()
{
incrementTest();
let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input id='i' required><input id='s' type='submit'></form>" + getDocFooter();
let browser = yield openNewTab(uri);
let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
yield clickChildElement(browser);
yield popupShownPromise;
checkPopupShow();
yield checkChildFocus(browser, gInvalidFormPopup.firstChild.textContent);
let popupHiddenPromise = promiseWaitForEvent(gInvalidFormPopup, "popuphidden");
yield blurChildElement(browser);
yield popupHiddenPromise;
gBrowser.removeCurrentTab();
});
/**
* In this test, we check that we can hide the popup by pressing TAB.
*/
add_task(function* ()
{
incrementTest();
let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input id='i' required><input id='s' type='submit'></form>" + getDocFooter();
let browser = yield openNewTab(uri);
let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
yield clickChildElement(browser);
yield popupShownPromise;
checkPopupShow();
yield checkChildFocus(browser, gInvalidFormPopup.firstChild.textContent);
let popupHiddenPromise = promiseWaitForEvent(gInvalidFormPopup, "popuphidden");
EventUtils.synthesizeKey("VK_TAB", {});
yield popupHiddenPromise;
gBrowser.removeCurrentTab();
});
/**
* In this test, we check that the popup will hide if we move to another tab.
*/
add_task(function* ()
{
incrementTest();
let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input id='i' required><input id='s' type='submit'></form>" + getDocFooter();
let browser1 = yield openNewTab(uri);
let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
yield clickChildElement(browser1);
yield popupShownPromise;
checkPopupShow();
yield checkChildFocus(browser1, gInvalidFormPopup.firstChild.textContent);
let popupHiddenPromise = promiseWaitForEvent(gInvalidFormPopup, "popuphidden");
let browser2 = yield openNewTab("data:text/html,<html></html>");
yield popupHiddenPromise;
gBrowser.removeTab(gBrowser.getTabForBrowser(browser1));
gBrowser.removeTab(gBrowser.getTabForBrowser(browser2));
});
/**
* In this test, we check that nothing happen if the invalid form is
* submitted in a background tab.
*/
add_task(function* ()
{
// Observers don't propagate currently across processes. We may add support for this in the
// future via the addon compat layer.
if (gMultiProcessBrowser) {
return;
}
incrementTest();
let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input id='i' required><input id='s' type='submit'></form>" + getDocFooter();
let browser = yield openNewTab(uri, true);
isnot(gBrowser.selectedBrowser, browser, "This tab should have been loaded in background");
let notifierPromise = new Promise((resolve, reject) => {
gObserver.notifyInvalidSubmit = function() {
executeSoon(function() {
checkPopupHide();
// Clean-up
Services.obs.removeObserver(gObserver, "invalidformsubmit");
gObserver.notifyInvalidSubmit = function () {};
resolve();
});
};
Services.obs.addObserver(gObserver, "invalidformsubmit", false);
executeSoon(function () {
browser.contentDocument.getElementById('s').click();
});
});
yield notifierPromise;
gBrowser.removeTab(gBrowser.getTabForBrowser(browser));
});
/**
* In this test, we check that the author defined error message is shown.
*/
add_task(function* ()
{
incrementTest();
let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input x-moz-errormessage='foo' required id='i'><input id='s' type='submit'></form>" + getDocFooter();
let browser = yield openNewTab(uri);
let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
yield clickChildElement(browser);
yield popupShownPromise;
checkPopupShow();
yield checkChildFocus(browser, gInvalidFormPopup.firstChild.textContent);
is(gInvalidFormPopup.firstChild.textContent, "foo",
"The panel should show the author defined error message");
gBrowser.removeCurrentTab();
});
/**
* In this test, we check that the message is correctly updated when it changes.
*/
add_task(function* ()
{
incrementTest();
let uri = getDocHeader() + "<form target='t' action='data:text/html,'><input type='email' required id='i'><input id='s' type='submit'></form>" + getDocFooter();
let browser = yield openNewTab(uri);
let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
yield clickChildElement(browser);
yield popupShownPromise;
checkPopupShow();
yield checkChildFocus(browser, gInvalidFormPopup.firstChild.textContent);
let inputPromise = promiseWaitForEvent(gBrowser.contentDocument.getElementById('i'), "input");
EventUtils.synthesizeKey('f', {});
yield inputPromise;
// Now, the element suffers from another error, the message should have
// been updated.
yield new Promise((resolve, reject) => {
// XXXndeakin This isn't really going to work when the content is another process
executeSoon(function() {
checkChildFocus(browser, gInvalidFormPopup.firstChild.textContent);
resolve();
});
});
gBrowser.removeCurrentTab();
});

View file

@ -1,30 +0,0 @@
function press(key, expectedPos) {
var originalSelectedTab = gBrowser.selectedTab;
EventUtils.synthesizeKey("VK_" + key.toUpperCase(), { accelKey: true });
is(gBrowser.selectedTab, originalSelectedTab,
"accel+" + key + " doesn't change which tab is selected");
is(gBrowser.tabContainer.selectedIndex, expectedPos,
"accel+" + key + " moves the tab to the expected position");
is(document.activeElement, gBrowser.selectedTab,
"accel+" + key + " leaves the selected tab focused");
}
function test() {
gBrowser.addTab();
gBrowser.addTab();
is(gBrowser.tabs.length, 3, "got three tabs");
is(gBrowser.tabs[0], gBrowser.selectedTab, "first tab is selected");
gBrowser.selectedTab.focus();
is(document.activeElement, gBrowser.selectedTab, "selected tab is focused");
press("right", 1);
press("down", 2);
press("left", 1);
press("up", 0);
press("end", 2);
press("home", 0);
gBrowser.removeCurrentTab();
gBrowser.removeCurrentTab();
}

Some files were not shown because too many files have changed in this diff Show more